~ubuntu-branches/ubuntu/saucy/openvpn/saucy-proposed

« back to all changes in this revision

Viewing changes to multi.c

  • Committer: Package Import Robot
  • Author(s): Stéphane Graber
  • Date: 2013-05-24 17:42:45 UTC
  • mfrom: (1.1.19) (10.2.22 sid)
  • Revision ID: package-import@ubuntu.com-20130524174245-g9y6wlforycufqy5
Tags: 2.3.1-2ubuntu1
* Merge from Debian unstable. Remaining changes:
  - debian/openvpn.init.d:
    + Do not use start-stop-daemon and </dev/null to avoid blocking boot.
    + Show per-VPN result messages.
    + Add "--script-security 2" by default for backwards compatabliity.

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
 
#include "syshead.h"
26
 
 
27
 
#if P2MP_SERVER
28
 
 
29
 
#include "multi.h"
30
 
#include "push.h"
31
 
#include "misc.h"
32
 
#include "otime.h"
33
 
#include "gremlin.h"
34
 
 
35
 
#include "memdbg.h"
36
 
 
37
 
#include "forward-inline.h"
38
 
#include "pf-inline.h"
39
 
 
40
 
/*#define MULTI_DEBUG_EVENT_LOOP*/
41
 
 
42
 
#ifdef MULTI_DEBUG_EVENT_LOOP
43
 
static const char *
44
 
id (struct multi_instance *mi)
45
 
{
46
 
  if (mi)
47
 
    return tls_common_name (mi->context.c2.tls_multi, false);
48
 
  else
49
 
    return "NULL";
50
 
}
51
 
#endif
52
 
 
53
 
#ifdef MANAGEMENT_DEF_AUTH
54
 
static void
55
 
set_cc_config (struct multi_instance *mi, struct buffer_list *cc_config)
56
 
{
57
 
  if (mi->cc_config)
58
 
    buffer_list_free (mi->cc_config);
59
 
  mi->cc_config = cc_config;
60
 
}
61
 
#endif
62
 
 
63
 
static bool
64
 
learn_address_script (const struct multi_context *m,
65
 
                      const struct multi_instance *mi,
66
 
                      const char *op,
67
 
                      const struct mroute_addr *addr)
68
 
{
69
 
  struct gc_arena gc = gc_new ();
70
 
  struct env_set *es;
71
 
  bool ret = true;
72
 
  struct plugin_list *plugins;
73
 
 
74
 
  /* get environmental variable source */
75
 
  if (mi && mi->context.c2.es)
76
 
    es = mi->context.c2.es;
77
 
  else
78
 
    es = env_set_create (&gc);
79
 
 
80
 
  /* get plugin source */
81
 
  if (mi)
82
 
    plugins = mi->context.plugins;
83
 
  else
84
 
    plugins = m->top.plugins;
85
 
 
86
 
  if (plugin_defined (plugins, OPENVPN_PLUGIN_LEARN_ADDRESS))
87
 
    {
88
 
      struct argv argv = argv_new ();
89
 
      argv_printf (&argv, "%s %s",
90
 
                   op,
91
 
                   mroute_addr_print (addr, &gc));
92
 
      if (mi)
93
 
        argv_printf_cat (&argv, "%s", tls_common_name (mi->context.c2.tls_multi, false));
94
 
      if (plugin_call (plugins, OPENVPN_PLUGIN_LEARN_ADDRESS, &argv, NULL, es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
95
 
        {
96
 
          msg (M_WARN, "WARNING: learn-address plugin call failed");
97
 
          ret = false;
98
 
        }
99
 
      argv_reset (&argv);
100
 
    }
101
 
 
102
 
  if (m->top.options.learn_address_script)
103
 
    {
104
 
      struct argv argv = argv_new ();
105
 
      setenv_str (es, "script_type", "learn-address");
106
 
      argv_printf (&argv, "%sc %s %s",
107
 
                   m->top.options.learn_address_script,
108
 
                   op,
109
 
                   mroute_addr_print (addr, &gc));
110
 
      if (mi)
111
 
        argv_printf_cat (&argv, "%s", tls_common_name (mi->context.c2.tls_multi, false));
112
 
      if (!openvpn_run_script (&argv, es, 0, "--learn-address"))
113
 
        ret = false;
114
 
      argv_reset (&argv);
115
 
    }
116
 
 
117
 
  gc_free (&gc);
118
 
  return ret;
119
 
}
120
 
 
121
 
void
122
 
multi_ifconfig_pool_persist (struct multi_context *m, bool force)
123
 
{
124
 
 /* write pool data to file */
125
 
  if (m->ifconfig_pool
126
 
      && m->top.c1.ifconfig_pool_persist
127
 
      && (force || ifconfig_pool_write_trigger (m->top.c1.ifconfig_pool_persist)))
128
 
    {
129
 
      ifconfig_pool_write (m->top.c1.ifconfig_pool_persist, m->ifconfig_pool);
130
 
    }
131
 
}
132
 
 
133
 
static void
134
 
multi_reap_range (const struct multi_context *m,
135
 
                  int start_bucket,
136
 
                  int end_bucket)
137
 
{
138
 
  struct gc_arena gc = gc_new ();
139
 
  struct hash_iterator hi;
140
 
  struct hash_element *he;
141
 
 
142
 
  if (start_bucket < 0)
143
 
    {
144
 
      start_bucket = 0;
145
 
      end_bucket = hash_n_buckets (m->vhash);
146
 
    }
147
 
 
148
 
  dmsg (D_MULTI_DEBUG, "MULTI: REAP range %d -> %d", start_bucket, end_bucket);
149
 
  hash_iterator_init_range (m->vhash, &hi, start_bucket, end_bucket);
150
 
  while ((he = hash_iterator_next (&hi)) != NULL)
151
 
    {
152
 
      struct multi_route *r = (struct multi_route *) he->value;
153
 
      if (!multi_route_defined (m, r))
154
 
        {
155
 
          dmsg (D_MULTI_DEBUG, "MULTI: REAP DEL %s",
156
 
               mroute_addr_print (&r->addr, &gc));
157
 
          learn_address_script (m, NULL, "delete", &r->addr);
158
 
          multi_route_del (r);
159
 
          hash_iterator_delete_element (&hi);
160
 
        }
161
 
    }
162
 
  hash_iterator_free (&hi);
163
 
  gc_free (&gc);
164
 
}
165
 
 
166
 
static void
167
 
multi_reap_all (const struct multi_context *m)
168
 
{
169
 
  multi_reap_range (m, -1, 0);
170
 
}
171
 
 
172
 
static struct multi_reap *
173
 
multi_reap_new (int buckets_per_pass)
174
 
{
175
 
  struct multi_reap *mr;
176
 
  ALLOC_OBJ (mr, struct multi_reap);
177
 
  mr->bucket_base = 0;
178
 
  mr->buckets_per_pass = buckets_per_pass;
179
 
  mr->last_call = now;
180
 
  return mr;
181
 
}
182
 
 
183
 
void
184
 
multi_reap_process_dowork (const struct multi_context *m)
185
 
{
186
 
  struct multi_reap *mr = m->reaper;
187
 
  if (mr->bucket_base >= hash_n_buckets (m->vhash))
188
 
    mr->bucket_base = 0;
189
 
  multi_reap_range (m, mr->bucket_base, mr->bucket_base + mr->buckets_per_pass); 
190
 
  mr->bucket_base += mr->buckets_per_pass;
191
 
  mr->last_call = now;
192
 
}
193
 
 
194
 
static void
195
 
multi_reap_free (struct multi_reap *mr)
196
 
{
197
 
  free (mr);
198
 
}
199
 
 
200
 
/*
201
 
 * How many buckets in vhash to reap per pass.
202
 
 */
203
 
static int
204
 
reap_buckets_per_pass (int n_buckets)
205
 
{
206
 
  return constrain_int (n_buckets / REAP_DIVISOR, REAP_MIN, REAP_MAX);
207
 
}
208
 
 
209
 
#ifdef MANAGEMENT_DEF_AUTH
210
 
 
211
 
static uint32_t
212
 
cid_hash_function (const void *key, uint32_t iv)
213
 
{
214
 
  const unsigned long *k = (const unsigned long *)key;
215
 
  return (uint32_t) *k;
216
 
}
217
 
 
218
 
static bool
219
 
cid_compare_function (const void *key1, const void *key2)
220
 
{
221
 
  const unsigned long *k1 = (const unsigned long *)key1;
222
 
  const unsigned long *k2 = (const unsigned long *)key2;
223
 
  return *k1 == *k2;
224
 
}
225
 
 
226
 
#endif
227
 
 
228
 
/*
229
 
 * Main initialization function, init multi_context object.
230
 
 */
231
 
void
232
 
multi_init (struct multi_context *m, struct context *t, bool tcp_mode, int thread_mode)
233
 
{
234
 
  int dev = DEV_TYPE_UNDEF;
235
 
 
236
 
  msg (D_MULTI_LOW, "MULTI: multi_init called, r=%d v=%d",
237
 
       t->options.real_hash_size,
238
 
       t->options.virtual_hash_size);
239
 
 
240
 
  /*
241
 
   * Get tun/tap/null device type
242
 
   */
243
 
  dev = dev_type_enum (t->options.dev, t->options.dev_type);
244
 
 
245
 
  /*
246
 
   * Init our multi_context object.
247
 
   */
248
 
  CLEAR (*m);
249
 
  
250
 
  m->thread_mode = thread_mode;
251
 
 
252
 
  /*
253
 
   * Real address hash table (source port number is
254
 
   * considered to be part of the address).  Used
255
 
   * to determine which client sent an incoming packet
256
 
   * which is seen on the TCP/UDP socket.
257
 
   */
258
 
  m->hash = hash_init (t->options.real_hash_size,
259
 
                       get_random (),
260
 
                       mroute_addr_hash_function,
261
 
                       mroute_addr_compare_function);
262
 
 
263
 
  /*
264
 
   * Virtual address hash table.  Used to determine
265
 
   * which client to route a packet to. 
266
 
   */
267
 
  m->vhash = hash_init (t->options.virtual_hash_size,
268
 
                        get_random (),
269
 
                        mroute_addr_hash_function,
270
 
                        mroute_addr_compare_function);
271
 
 
272
 
  /*
273
 
   * This hash table is a clone of m->hash but with a
274
 
   * bucket size of one so that it can be used
275
 
   * for fast iteration through the list.
276
 
   */
277
 
  m->iter = hash_init (1,
278
 
                       get_random (),
279
 
                       mroute_addr_hash_function,
280
 
                       mroute_addr_compare_function);
281
 
 
282
 
#ifdef MANAGEMENT_DEF_AUTH
283
 
  m->cid_hash = hash_init (t->options.real_hash_size,
284
 
                           0,
285
 
                           cid_hash_function,
286
 
                           cid_compare_function);
287
 
#endif
288
 
 
289
 
  /*
290
 
   * This is our scheduler, for time-based wakeup
291
 
   * events.
292
 
   */
293
 
  m->schedule = schedule_init ();
294
 
 
295
 
  /*
296
 
   * Limit frequency of incoming connections to control
297
 
   * DoS.
298
 
   */
299
 
  m->new_connection_limiter = frequency_limit_init (t->options.cf_max,
300
 
                                                    t->options.cf_per);
301
 
 
302
 
  /*
303
 
   * Allocate broadcast/multicast buffer list
304
 
   */
305
 
  m->mbuf = mbuf_init (t->options.n_bcast_buf);
306
 
 
307
 
  /*
308
 
   * Different status file format options are available
309
 
   */
310
 
  m->status_file_version = t->options.status_file_version;
311
 
 
312
 
  /*
313
 
   * Possibly allocate an ifconfig pool, do it
314
 
   * differently based on whether a tun or tap style
315
 
   * tunnel.
316
 
   */
317
 
  if (t->options.ifconfig_pool_defined)
318
 
    {
319
 
      int pool_type = IFCONFIG_POOL_INDIV;
320
 
 
321
 
      if ( dev == DEV_TYPE_TUN && t->options.topology == TOP_NET30 )
322
 
        pool_type = IFCONFIG_POOL_30NET;
323
 
 
324
 
      m->ifconfig_pool = ifconfig_pool_init (pool_type,
325
 
                                 t->options.ifconfig_pool_start,
326
 
                                 t->options.ifconfig_pool_end,
327
 
                                 t->options.duplicate_cn,
328
 
                                 t->options.ifconfig_ipv6_pool_defined,
329
 
                                 t->options.ifconfig_ipv6_pool_base,
330
 
                                 t->options.ifconfig_ipv6_pool_netbits );
331
 
 
332
 
      /* reload pool data from file */
333
 
      if (t->c1.ifconfig_pool_persist)
334
 
        ifconfig_pool_read (t->c1.ifconfig_pool_persist, m->ifconfig_pool);
335
 
    }
336
 
 
337
 
  /*
338
 
   * Help us keep track of routing table.
339
 
   */
340
 
  m->route_helper = mroute_helper_init (MULTI_CACHE_ROUTE_TTL);
341
 
 
342
 
  /*
343
 
   * Initialize route and instance reaper.
344
 
   */
345
 
  m->reaper = multi_reap_new (reap_buckets_per_pass (t->options.virtual_hash_size));
346
 
 
347
 
  /*
348
 
   * Get local ifconfig address
349
 
   */
350
 
  CLEAR (m->local);
351
 
  ASSERT (t->c1.tuntap);
352
 
  mroute_extract_in_addr_t (&m->local, t->c1.tuntap->local);
353
 
 
354
 
  /*
355
 
   * Per-client limits
356
 
   */
357
 
  m->max_clients = t->options.max_clients;
358
 
 
359
 
  /*
360
 
   * Initialize multi-socket TCP I/O wait object
361
 
   */
362
 
  if (tcp_mode)
363
 
    m->mtcp = multi_tcp_init (t->options.max_clients, &m->max_clients);
364
 
  m->tcp_queue_limit = t->options.tcp_queue_limit;
365
 
  
366
 
  /*
367
 
   * Allow client <-> client communication, without going through
368
 
   * tun/tap interface and network stack?
369
 
   */
370
 
  m->enable_c2c = t->options.enable_c2c;
371
 
}
372
 
 
373
 
const char *
374
 
multi_instance_string (const struct multi_instance *mi, bool null, struct gc_arena *gc)
375
 
{
376
 
  if (mi)
377
 
    {
378
 
      struct buffer out = alloc_buf_gc (256, gc);
379
 
      const char *cn = tls_common_name (mi->context.c2.tls_multi, true);
380
 
 
381
 
      if (cn)
382
 
        buf_printf (&out, "%s/", cn);
383
 
      buf_printf (&out, "%s", mroute_addr_print (&mi->real, gc));
384
 
      return BSTR (&out);
385
 
    }
386
 
  else if (null)
387
 
    return NULL;
388
 
  else
389
 
    return "UNDEF";
390
 
}
391
 
 
392
 
void
393
 
generate_prefix (struct multi_instance *mi)
394
 
{
395
 
  mi->msg_prefix = multi_instance_string (mi, true, &mi->gc);
396
 
  set_prefix (mi);
397
 
}
398
 
 
399
 
void
400
 
ungenerate_prefix (struct multi_instance *mi)
401
 
{
402
 
  mi->msg_prefix = NULL;
403
 
  set_prefix (mi);
404
 
}
405
 
 
406
 
static const char *
407
 
mi_prefix (const struct multi_instance *mi)
408
 
{
409
 
  if (mi && mi->msg_prefix)
410
 
    return mi->msg_prefix;
411
 
  else
412
 
    return "UNDEF_I";
413
 
}
414
 
 
415
 
/*
416
 
 * Tell the route helper about deleted iroutes so
417
 
 * that it can update its mask of currently used
418
 
 * CIDR netlengths.
419
 
 */
420
 
static void
421
 
multi_del_iroutes (struct multi_context *m,
422
 
                   struct multi_instance *mi)
423
 
{
424
 
  const struct iroute *ir;
425
 
  const struct iroute_ipv6 *ir6;
426
 
  if (TUNNEL_TYPE (mi->context.c1.tuntap) == DEV_TYPE_TUN)
427
 
    {
428
 
      for (ir = mi->context.options.iroutes; ir != NULL; ir = ir->next)
429
 
        mroute_helper_del_iroute (m->route_helper, ir);
430
 
 
431
 
      for ( ir6 = mi->context.options.iroutes_ipv6; ir6 != NULL; ir6 = ir6->next )
432
 
        mroute_helper_del_iroute6 (m->route_helper, ir6);
433
 
    }
434
 
}
435
 
 
436
 
static void
437
 
setenv_stats (struct context *c)
438
 
{
439
 
  setenv_counter (c->c2.es, "bytes_received", c->c2.link_read_bytes);
440
 
  setenv_counter (c->c2.es, "bytes_sent", c->c2.link_write_bytes);
441
 
}
442
 
 
443
 
static void
444
 
multi_client_disconnect_setenv (struct multi_context *m,
445
 
                                struct multi_instance *mi)
446
 
{
447
 
  /* setenv client real IP address */
448
 
  setenv_trusted (mi->context.c2.es, get_link_socket_info (&mi->context));
449
 
 
450
 
  /* setenv stats */
451
 
  setenv_stats (&mi->context);
452
 
 
453
 
  /* setenv connection duration */
454
 
  {
455
 
    const unsigned int duration = (unsigned int) now - mi->created;
456
 
    setenv_unsigned (mi->context.c2.es, "time_duration", duration);
457
 
  }
458
 
}
459
 
 
460
 
static void
461
 
multi_client_disconnect_script (struct multi_context *m,
462
 
                                struct multi_instance *mi)
463
 
{
464
 
  if ((mi->context.c2.context_auth == CAS_SUCCEEDED && mi->connection_established_flag)
465
 
      || mi->context.c2.context_auth == CAS_PARTIAL)
466
 
    {
467
 
      multi_client_disconnect_setenv (m, mi);
468
 
 
469
 
      if (plugin_defined (mi->context.plugins, OPENVPN_PLUGIN_CLIENT_DISCONNECT))
470
 
        {
471
 
          if (plugin_call (mi->context.plugins, OPENVPN_PLUGIN_CLIENT_DISCONNECT, NULL, NULL, mi->context.c2.es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
472
 
            msg (M_WARN, "WARNING: client-disconnect plugin call failed");
473
 
        }
474
 
 
475
 
      if (mi->context.options.client_disconnect_script)
476
 
        {
477
 
          struct argv argv = argv_new ();
478
 
          setenv_str (mi->context.c2.es, "script_type", "client-disconnect");
479
 
          argv_printf (&argv, "%sc", mi->context.options.client_disconnect_script);
480
 
          openvpn_run_script (&argv, mi->context.c2.es, 0, "--client-disconnect");
481
 
          argv_reset (&argv);
482
 
        }
483
 
#ifdef MANAGEMENT_DEF_AUTH
484
 
      if (management)
485
 
        management_notify_client_close (management, &mi->context.c2.mda_context, mi->context.c2.es);
486
 
#endif
487
 
 
488
 
    }
489
 
}
490
 
 
491
 
void
492
 
multi_close_instance (struct multi_context *m,
493
 
                      struct multi_instance *mi,
494
 
                      bool shutdown)
495
 
{
496
 
  perf_push (PERF_MULTI_CLOSE_INSTANCE);
497
 
 
498
 
  ASSERT (!mi->halt);
499
 
  mi->halt = true;
500
 
 
501
 
  dmsg (D_MULTI_DEBUG, "MULTI: multi_close_instance called");
502
 
 
503
 
  /* adjust current client connection count */
504
 
  m->n_clients += mi->n_clients_delta;
505
 
  mi->n_clients_delta = 0;
506
 
 
507
 
  /* prevent dangling pointers */
508
 
  if (m->pending == mi)
509
 
    multi_set_pending (m, NULL);
510
 
  if (m->earliest_wakeup == mi)
511
 
    m->earliest_wakeup = NULL;
512
 
 
513
 
  if (!shutdown)
514
 
    {
515
 
      if (mi->did_real_hash)
516
 
        {
517
 
          ASSERT (hash_remove (m->hash, &mi->real));
518
 
        }
519
 
      if (mi->did_iter)
520
 
        {
521
 
          ASSERT (hash_remove (m->iter, &mi->real));
522
 
        }
523
 
#ifdef MANAGEMENT_DEF_AUTH
524
 
      if (mi->did_cid_hash)
525
 
        {
526
 
          ASSERT (hash_remove (m->cid_hash, &mi->context.c2.mda_context.cid));
527
 
        }
528
 
#endif
529
 
 
530
 
      schedule_remove_entry (m->schedule, (struct schedule_entry *) mi);
531
 
 
532
 
      ifconfig_pool_release (m->ifconfig_pool, mi->vaddr_handle, false);
533
 
      
534
 
      if (mi->did_iroutes)
535
 
        {
536
 
          multi_del_iroutes (m, mi);
537
 
          mi->did_iroutes = false;
538
 
        }
539
 
 
540
 
      if (m->mtcp)
541
 
        multi_tcp_dereference_instance (m->mtcp, mi);
542
 
 
543
 
      mbuf_dereference_instance (m->mbuf, mi);
544
 
    }
545
 
 
546
 
#ifdef MANAGEMENT_DEF_AUTH
547
 
  set_cc_config (mi, NULL);
548
 
#endif
549
 
 
550
 
  multi_client_disconnect_script (m, mi);
551
 
 
552
 
  if (mi->did_open_context)
553
 
    close_context (&mi->context, SIGTERM, CC_GC_FREE);
554
 
 
555
 
  multi_tcp_instance_specific_free (mi);
556
 
 
557
 
  ungenerate_prefix (mi);
558
 
 
559
 
  /*
560
 
   * Don't actually delete the instance memory allocation yet,
561
 
   * because virtual routes may still point to it.  Let the
562
 
   * vhash reaper deal with it.
563
 
   */
564
 
  multi_instance_dec_refcount (mi);
565
 
 
566
 
  perf_pop ();
567
 
}
568
 
 
569
 
/*
570
 
 * Called on shutdown or restart.
571
 
 */
572
 
void
573
 
multi_uninit (struct multi_context *m)
574
 
{
575
 
  if (m->thread_mode & MC_WORK_THREAD)
576
 
    {
577
 
      multi_top_free (m);
578
 
      m->thread_mode = MC_UNDEF;
579
 
    }
580
 
  else if (m->thread_mode)
581
 
    {
582
 
      if (m->hash)
583
 
        {
584
 
          struct hash_iterator hi;
585
 
          struct hash_element *he;
586
 
 
587
 
          hash_iterator_init (m->iter, &hi);
588
 
          while ((he = hash_iterator_next (&hi)))
589
 
            {
590
 
              struct multi_instance *mi = (struct multi_instance *) he->value;
591
 
              mi->did_iter = false;
592
 
              multi_close_instance (m, mi, true);
593
 
            }
594
 
          hash_iterator_free (&hi);
595
 
 
596
 
          multi_reap_all (m);
597
 
 
598
 
          hash_free (m->hash);
599
 
          hash_free (m->vhash);
600
 
          hash_free (m->iter);
601
 
#ifdef MANAGEMENT_DEF_AUTH
602
 
          hash_free (m->cid_hash);
603
 
#endif
604
 
          m->hash = NULL;
605
 
 
606
 
          schedule_free (m->schedule);
607
 
          mbuf_free (m->mbuf);
608
 
          ifconfig_pool_free (m->ifconfig_pool);
609
 
          frequency_limit_free (m->new_connection_limiter);
610
 
          multi_reap_free (m->reaper);
611
 
          mroute_helper_free (m->route_helper);
612
 
          multi_tcp_free (m->mtcp);
613
 
          m->thread_mode = MC_UNDEF;
614
 
        }
615
 
    }
616
 
}
617
 
 
618
 
/*
619
 
 * Create a client instance object for a newly connected client.
620
 
 */
621
 
struct multi_instance *
622
 
multi_create_instance (struct multi_context *m, const struct mroute_addr *real)
623
 
{
624
 
  struct gc_arena gc = gc_new ();
625
 
  struct multi_instance *mi;
626
 
 
627
 
  perf_push (PERF_MULTI_CREATE_INSTANCE);
628
 
 
629
 
  msg (D_MULTI_LOW, "MULTI: multi_create_instance called");
630
 
 
631
 
  ALLOC_OBJ_CLEAR (mi, struct multi_instance);
632
 
 
633
 
  mi->gc = gc_new ();
634
 
  multi_instance_inc_refcount (mi);
635
 
  mi->vaddr_handle = -1;
636
 
  mi->created = now;
637
 
  mroute_addr_init (&mi->real);
638
 
 
639
 
  if (real)
640
 
    {
641
 
      mi->real = *real;
642
 
      generate_prefix (mi);
643
 
    }
644
 
 
645
 
  mi->did_open_context = true;
646
 
  inherit_context_child (&mi->context, &m->top);
647
 
  if (IS_SIG (&mi->context))
648
 
    goto err;
649
 
 
650
 
  mi->context.c2.context_auth = CAS_PENDING;
651
 
 
652
 
  if (hash_n_elements (m->hash) >= m->max_clients)
653
 
    {
654
 
      msg (D_MULTI_ERRORS, "MULTI: new incoming connection would exceed maximum number of clients (%d)", m->max_clients);
655
 
      goto err;
656
 
    }
657
 
 
658
 
  if (!real) /* TCP mode? */
659
 
    {
660
 
      if (!multi_tcp_instance_specific_init (m, mi))
661
 
        goto err;
662
 
      generate_prefix (mi);
663
 
    }
664
 
 
665
 
  if (!hash_add (m->iter, &mi->real, mi, false))
666
 
    {
667
 
      msg (D_MULTI_LOW, "MULTI: unable to add real address [%s] to iterator hash table",
668
 
           mroute_addr_print (&mi->real, &gc));
669
 
      goto err;
670
 
    }
671
 
  mi->did_iter = true;
672
 
 
673
 
#ifdef MANAGEMENT_DEF_AUTH
674
 
  do {
675
 
    mi->context.c2.mda_context.cid = m->cid_counter++;
676
 
  } while (!hash_add (m->cid_hash, &mi->context.c2.mda_context.cid, mi, false));
677
 
  mi->did_cid_hash = true;
678
 
#endif
679
 
 
680
 
  mi->context.c2.push_reply_deferred = true;
681
 
 
682
 
  if (!multi_process_post (m, mi, MPP_PRE_SELECT))
683
 
    {
684
 
      msg (D_MULTI_ERRORS, "MULTI: signal occurred during client instance initialization");
685
 
      goto err;
686
 
    }
687
 
 
688
 
  perf_pop ();
689
 
  gc_free (&gc);
690
 
  return mi;
691
 
 
692
 
 err:
693
 
  multi_close_instance (m, mi, false);
694
 
  perf_pop ();
695
 
  gc_free (&gc);
696
 
  return NULL;
697
 
}
698
 
 
699
 
/*
700
 
 * Dump tables -- triggered by SIGUSR2.
701
 
 * If status file is defined, write to file.
702
 
 * If status file is NULL, write to syslog.
703
 
 */
704
 
void
705
 
multi_print_status (struct multi_context *m, struct status_output *so, const int version)
706
 
{
707
 
  if (m->hash)
708
 
    {
709
 
      struct gc_arena gc_top = gc_new ();
710
 
      struct hash_iterator hi;
711
 
      const struct hash_element *he;
712
 
 
713
 
      status_reset (so);
714
 
 
715
 
      if (version == 1) /* WAS: m->status_file_version */
716
 
        {
717
 
          /*
718
 
           * Status file version 1
719
 
           */
720
 
          status_printf (so, "OpenVPN CLIENT LIST");
721
 
          status_printf (so, "Updated,%s", time_string (0, 0, false, &gc_top));
722
 
          status_printf (so, "Common Name,Real Address,Bytes Received,Bytes Sent,Connected Since");
723
 
          hash_iterator_init (m->hash, &hi);
724
 
          while ((he = hash_iterator_next (&hi)))
725
 
            {
726
 
              struct gc_arena gc = gc_new ();
727
 
              const struct multi_instance *mi = (struct multi_instance *) he->value;
728
 
 
729
 
              if (!mi->halt)
730
 
                {
731
 
                  status_printf (so, "%s,%s," counter_format "," counter_format ",%s",
732
 
                                 tls_common_name (mi->context.c2.tls_multi, false),
733
 
                                 mroute_addr_print (&mi->real, &gc),
734
 
                                 mi->context.c2.link_read_bytes,
735
 
                                 mi->context.c2.link_write_bytes,
736
 
                                 time_string (mi->created, 0, false, &gc));
737
 
                }
738
 
              gc_free (&gc);
739
 
            }
740
 
          hash_iterator_free (&hi);
741
 
 
742
 
          status_printf (so, "ROUTING TABLE");
743
 
          status_printf (so, "Virtual Address,Common Name,Real Address,Last Ref");
744
 
          hash_iterator_init (m->vhash, &hi);
745
 
          while ((he = hash_iterator_next (&hi)))
746
 
            {
747
 
              struct gc_arena gc = gc_new ();
748
 
              const struct multi_route *route = (struct multi_route *) he->value;
749
 
 
750
 
              if (multi_route_defined (m, route))
751
 
                {
752
 
                  const struct multi_instance *mi = route->instance;
753
 
                  const struct mroute_addr *ma = &route->addr;
754
 
                  char flags[2] = {0, 0};
755
 
 
756
 
                  if (route->flags & MULTI_ROUTE_CACHE)
757
 
                    flags[0] = 'C';
758
 
                  status_printf (so, "%s%s,%s,%s,%s",
759
 
                                 mroute_addr_print (ma, &gc),
760
 
                                 flags,
761
 
                                 tls_common_name (mi->context.c2.tls_multi, false),
762
 
                                 mroute_addr_print (&mi->real, &gc),
763
 
                                 time_string (route->last_reference, 0, false, &gc));
764
 
                }
765
 
              gc_free (&gc);
766
 
            }
767
 
          hash_iterator_free (&hi);
768
 
 
769
 
          status_printf (so, "GLOBAL STATS");
770
 
          if (m->mbuf)
771
 
            status_printf (so, "Max bcast/mcast queue length,%d",
772
 
                           mbuf_maximum_queued (m->mbuf));
773
 
 
774
 
          status_printf (so, "END");
775
 
        }
776
 
      else if (version == 2 || version == 3)
777
 
        {
778
 
          const char sep = (version == 3) ? '\t' : ',';
779
 
 
780
 
          /*
781
 
           * Status file version 2 and 3
782
 
           */
783
 
          status_printf (so, "TITLE%c%s", sep, title_string);
784
 
          status_printf (so, "TIME%c%s%c%u", sep, time_string (now, 0, false, &gc_top), sep, (unsigned int)now);
785
 
          status_printf (so, "HEADER%cCLIENT_LIST%cCommon Name%cReal Address%cVirtual Address%cBytes Received%cBytes Sent%cConnected Since%cConnected Since (time_t)",
786
 
                         sep, sep, sep, sep, sep, sep, sep, sep);
787
 
          hash_iterator_init (m->hash, &hi);
788
 
          while ((he = hash_iterator_next (&hi)))
789
 
            {
790
 
              struct gc_arena gc = gc_new ();
791
 
              const struct multi_instance *mi = (struct multi_instance *) he->value;
792
 
 
793
 
              if (!mi->halt)
794
 
                {
795
 
                  status_printf (so, "CLIENT_LIST%c%s%c%s%c%s%c" counter_format "%c" counter_format "%c%s%c%u",
796
 
                                 sep, tls_common_name (mi->context.c2.tls_multi, false),
797
 
                                 sep, mroute_addr_print (&mi->real, &gc),
798
 
                                 sep, print_in_addr_t (mi->reporting_addr, IA_EMPTY_IF_UNDEF, &gc),
799
 
                                 sep, mi->context.c2.link_read_bytes,
800
 
                                 sep, mi->context.c2.link_write_bytes,
801
 
                                 sep, time_string (mi->created, 0, false, &gc),
802
 
                                 sep, (unsigned int)mi->created);
803
 
                }
804
 
              gc_free (&gc);
805
 
            }
806
 
          hash_iterator_free (&hi);
807
 
 
808
 
          status_printf (so, "HEADER%cROUTING_TABLE%cVirtual Address%cCommon Name%cReal Address%cLast Ref%cLast Ref (time_t)",
809
 
                         sep, sep, sep, sep, sep, sep);
810
 
          hash_iterator_init (m->vhash, &hi);
811
 
          while ((he = hash_iterator_next (&hi)))
812
 
            {
813
 
              struct gc_arena gc = gc_new ();
814
 
              const struct multi_route *route = (struct multi_route *) he->value;
815
 
 
816
 
              if (multi_route_defined (m, route))
817
 
                {
818
 
                  const struct multi_instance *mi = route->instance;
819
 
                  const struct mroute_addr *ma = &route->addr;
820
 
                  char flags[2] = {0, 0};
821
 
 
822
 
                  if (route->flags & MULTI_ROUTE_CACHE)
823
 
                    flags[0] = 'C';
824
 
                  status_printf (so, "ROUTING_TABLE%c%s%s%c%s%c%s%c%s%c%u",
825
 
                                 sep, mroute_addr_print (ma, &gc), flags,
826
 
                                 sep, tls_common_name (mi->context.c2.tls_multi, false),
827
 
                                 sep, mroute_addr_print (&mi->real, &gc),
828
 
                                 sep, time_string (route->last_reference, 0, false, &gc),
829
 
                                 sep, (unsigned int)route->last_reference);
830
 
                }
831
 
              gc_free (&gc);
832
 
            }
833
 
          hash_iterator_free (&hi);
834
 
 
835
 
          if (m->mbuf)
836
 
            status_printf (so, "GLOBAL_STATS%cMax bcast/mcast queue length%c%d",
837
 
                           sep, sep, mbuf_maximum_queued (m->mbuf));
838
 
 
839
 
          status_printf (so, "END");
840
 
        }
841
 
      else
842
 
        {
843
 
          status_printf (so, "ERROR: bad status format version number");
844
 
        }
845
 
 
846
 
#ifdef PACKET_TRUNCATION_CHECK
847
 
      {
848
 
        status_printf (so, "HEADER,ERRORS,Common Name,TUN Read Trunc,TUN Write Trunc,Pre-encrypt Trunc,Post-decrypt Trunc");
849
 
        hash_iterator_init (m->hash, &hi);
850
 
        while ((he = hash_iterator_next (&hi)))
851
 
            {
852
 
              struct gc_arena gc = gc_new ();
853
 
              const struct multi_instance *mi = (struct multi_instance *) he->value;
854
 
 
855
 
              if (!mi->halt)
856
 
                {
857
 
                  status_printf (so, "ERRORS,%s," counter_format "," counter_format "," counter_format "," counter_format,
858
 
                                 tls_common_name (mi->context.c2.tls_multi, false),
859
 
                                 m->top.c2.n_trunc_tun_read,
860
 
                                 mi->context.c2.n_trunc_tun_write,
861
 
                                 mi->context.c2.n_trunc_pre_encrypt,
862
 
                                 mi->context.c2.n_trunc_post_decrypt);
863
 
                }
864
 
              gc_free (&gc);
865
 
            }
866
 
        hash_iterator_free (&hi);
867
 
      }
868
 
#endif
869
 
 
870
 
      status_flush (so);
871
 
      gc_free (&gc_top);
872
 
    }
873
 
}
874
 
 
875
 
/*
876
 
 * Learn a virtual address or route.
877
 
 * The learn will fail if the learn address
878
 
 * script/plugin fails.  In this case the
879
 
 * return value may be != mi.
880
 
 * Return the instance which owns this route,
881
 
 * or NULL if none.
882
 
 */
883
 
static struct multi_instance *
884
 
multi_learn_addr (struct multi_context *m,
885
 
                  struct multi_instance *mi,
886
 
                  const struct mroute_addr *addr,
887
 
                  const unsigned int flags)
888
 
{
889
 
  struct hash_element *he;
890
 
  const uint32_t hv = hash_value (m->vhash, addr);
891
 
  struct hash_bucket *bucket = hash_bucket (m->vhash, hv);
892
 
  struct multi_route *oldroute = NULL;
893
 
  struct multi_instance *owner = NULL;
894
 
 
895
 
  /* if route currently exists, get the instance which owns it */
896
 
  he = hash_lookup_fast (m->vhash, bucket, addr, hv);
897
 
  if (he)
898
 
    oldroute = (struct multi_route *) he->value;
899
 
  if (oldroute && multi_route_defined (m, oldroute))
900
 
    owner = oldroute->instance;
901
 
 
902
 
  /* do we need to add address to hash table? */
903
 
  if ((!owner || owner != mi)
904
 
      && mroute_learnable_address (addr)
905
 
      && !mroute_addr_equal (addr, &m->local))
906
 
    {
907
 
      struct gc_arena gc = gc_new ();
908
 
      struct multi_route *newroute;
909
 
      bool learn_succeeded = false;
910
 
 
911
 
      ALLOC_OBJ (newroute, struct multi_route);
912
 
      newroute->addr = *addr;
913
 
      newroute->instance = mi;
914
 
      newroute->flags = flags;
915
 
      newroute->last_reference = now;
916
 
      newroute->cache_generation = 0;
917
 
 
918
 
      /* The cache is invalidated when cache_generation is incremented */
919
 
      if (flags & MULTI_ROUTE_CACHE)
920
 
        newroute->cache_generation = m->route_helper->cache_generation;
921
 
 
922
 
      if (oldroute) /* route already exists? */
923
 
        {
924
 
          if (route_quota_test (m, mi) && learn_address_script (m, mi, "update", &newroute->addr))
925
 
            {
926
 
              learn_succeeded = true;
927
 
              owner = mi;
928
 
              multi_instance_inc_refcount (mi);
929
 
              route_quota_inc (mi);
930
 
 
931
 
              /* delete old route */
932
 
              multi_route_del (oldroute);
933
 
 
934
 
              /* modify hash table entry, replacing old route */
935
 
              he->key = &newroute->addr;
936
 
              he->value = newroute;
937
 
            }
938
 
        }
939
 
      else
940
 
        {
941
 
          if (route_quota_test (m, mi) && learn_address_script (m, mi, "add", &newroute->addr))
942
 
            {
943
 
              learn_succeeded = true;
944
 
              owner = mi;
945
 
              multi_instance_inc_refcount (mi);
946
 
              route_quota_inc (mi);
947
 
 
948
 
              /* add new route */
949
 
              hash_add_fast (m->vhash, bucket, &newroute->addr, hv, newroute);
950
 
            }
951
 
        }
952
 
      
953
 
      msg (D_MULTI_LOW, "MULTI: Learn%s: %s -> %s",
954
 
           learn_succeeded ? "" : " FAILED",
955
 
           mroute_addr_print (&newroute->addr, &gc),
956
 
           multi_instance_string (mi, false, &gc));
957
 
 
958
 
      if (!learn_succeeded)
959
 
        free (newroute);
960
 
 
961
 
      gc_free (&gc);
962
 
    }
963
 
 
964
 
  return owner;
965
 
}
966
 
 
967
 
/*
968
 
 * Get client instance based on virtual address.
969
 
 */
970
 
static struct multi_instance *
971
 
multi_get_instance_by_virtual_addr (struct multi_context *m,
972
 
                                    const struct mroute_addr *addr,
973
 
                                    bool cidr_routing)
974
 
{
975
 
  struct multi_route *route;
976
 
  struct multi_instance *ret = NULL;
977
 
 
978
 
  /* check for local address */
979
 
  if (mroute_addr_equal (addr, &m->local))
980
 
    return NULL;
981
 
 
982
 
  route = (struct multi_route *) hash_lookup (m->vhash, addr);
983
 
 
984
 
  /* does host route (possible cached) exist? */
985
 
  if (route && multi_route_defined (m, route))
986
 
    {
987
 
      struct multi_instance *mi = route->instance;
988
 
      route->last_reference = now;
989
 
      ret = mi;
990
 
    }
991
 
  else if (cidr_routing) /* do we need to regenerate a host route cache entry? */
992
 
    {
993
 
      struct mroute_helper *rh = m->route_helper;
994
 
      struct mroute_addr tryaddr;
995
 
      int i;
996
 
 
997
 
      /* cycle through each CIDR length */
998
 
      for (i = 0; i < rh->n_net_len; ++i)
999
 
        {
1000
 
          tryaddr = *addr;
1001
 
          tryaddr.type |= MR_WITH_NETBITS;
1002
 
          tryaddr.netbits = rh->net_len[i];
1003
 
          mroute_addr_mask_host_bits (&tryaddr);
1004
 
 
1005
 
          /* look up a possible route with netbits netmask */
1006
 
          route = (struct multi_route *) hash_lookup (m->vhash, &tryaddr);
1007
 
 
1008
 
          if (route && multi_route_defined (m, route))
1009
 
            {
1010
 
              /* found an applicable route, cache host route */
1011
 
              struct multi_instance *mi = route->instance;
1012
 
              multi_learn_addr (m, mi, addr, MULTI_ROUTE_CACHE|MULTI_ROUTE_AGEABLE);
1013
 
              ret = mi;
1014
 
              break;
1015
 
            }
1016
 
        }
1017
 
    }
1018
 
  
1019
 
#ifdef ENABLE_DEBUG
1020
 
  if (check_debug_level (D_MULTI_DEBUG))
1021
 
    {
1022
 
      struct gc_arena gc = gc_new ();
1023
 
      const char *addr_text = mroute_addr_print (addr, &gc);
1024
 
      if (ret)
1025
 
        {
1026
 
          dmsg (D_MULTI_DEBUG, "GET INST BY VIRT: %s -> %s via %s",
1027
 
               addr_text,
1028
 
               multi_instance_string (ret, false, &gc),
1029
 
               mroute_addr_print (&route->addr, &gc));
1030
 
        }
1031
 
      else
1032
 
        {
1033
 
          dmsg (D_MULTI_DEBUG, "GET INST BY VIRT: %s [failed]",
1034
 
               addr_text);
1035
 
        }
1036
 
      gc_free (&gc);
1037
 
    }
1038
 
#endif
1039
 
 
1040
 
  ASSERT (!(ret && ret->halt));
1041
 
  return ret;
1042
 
}
1043
 
 
1044
 
/*
1045
 
 * Helper function to multi_learn_addr().
1046
 
 */
1047
 
static struct multi_instance *
1048
 
multi_learn_in_addr_t (struct multi_context *m,
1049
 
                       struct multi_instance *mi,
1050
 
                       in_addr_t a,
1051
 
                       int netbits, /* -1 if host route, otherwise # of network bits in address */
1052
 
                       bool primary)
1053
 
{
1054
 
  struct openvpn_sockaddr remote_si;
1055
 
  struct mroute_addr addr;
1056
 
 
1057
 
  CLEAR (remote_si);
1058
 
  remote_si.addr.in4.sin_family = AF_INET;
1059
 
  remote_si.addr.in4.sin_addr.s_addr = htonl (a);
1060
 
  ASSERT (mroute_extract_openvpn_sockaddr (&addr, &remote_si, false));
1061
 
 
1062
 
  if (netbits >= 0)
1063
 
    {
1064
 
      addr.type |= MR_WITH_NETBITS;
1065
 
      addr.netbits = (uint8_t) netbits;
1066
 
    }
1067
 
 
1068
 
  {
1069
 
    struct multi_instance *owner = multi_learn_addr (m, mi, &addr, 0);
1070
 
#ifdef MANAGEMENT_DEF_AUTH
1071
 
    if (management && owner)
1072
 
      management_learn_addr (management, &mi->context.c2.mda_context, &addr, primary);
1073
 
#endif
1074
 
    return owner;
1075
 
  }
1076
 
}
1077
 
 
1078
 
static struct multi_instance *
1079
 
multi_learn_in6_addr  (struct multi_context *m,
1080
 
                       struct multi_instance *mi,
1081
 
                       struct in6_addr a6,
1082
 
                       int netbits, /* -1 if host route, otherwise # of network bits in address */
1083
 
                       bool primary)
1084
 
{
1085
 
  struct mroute_addr addr;
1086
 
 
1087
 
  addr.len = 16;
1088
 
  addr.type = MR_ADDR_IPV6;
1089
 
  addr.netbits = 0;
1090
 
  memcpy( &addr.addr, &a6, sizeof(a6) );
1091
 
 
1092
 
  if (netbits >= 0)
1093
 
    {
1094
 
      addr.type |= MR_WITH_NETBITS;
1095
 
      addr.netbits = (uint8_t) netbits;
1096
 
      mroute_addr_mask_host_bits( &addr );
1097
 
    }
1098
 
 
1099
 
  {
1100
 
    struct multi_instance *owner = multi_learn_addr (m, mi, &addr, 0);
1101
 
#ifdef MANAGEMENT_DEF_AUTH
1102
 
    if (management && owner)
1103
 
      management_learn_addr (management, &mi->context.c2.mda_context, &addr, primary);
1104
 
#endif
1105
 
    return owner;
1106
 
  }
1107
 
}
1108
 
 
1109
 
/*
1110
 
 * A new client has connected, add routes (server -> client)
1111
 
 * to internal routing table.
1112
 
 */
1113
 
static void
1114
 
multi_add_iroutes (struct multi_context *m,
1115
 
                   struct multi_instance *mi)
1116
 
{
1117
 
  struct gc_arena gc = gc_new ();
1118
 
  const struct iroute *ir;
1119
 
  const struct iroute_ipv6 *ir6;
1120
 
  if (TUNNEL_TYPE (mi->context.c1.tuntap) == DEV_TYPE_TUN)
1121
 
    {
1122
 
      mi->did_iroutes = true;
1123
 
      for (ir = mi->context.options.iroutes; ir != NULL; ir = ir->next)
1124
 
        {
1125
 
          if (ir->netbits >= 0)
1126
 
            msg (D_MULTI_LOW, "MULTI: internal route %s/%d -> %s",
1127
 
                 print_in_addr_t (ir->network, 0, &gc),
1128
 
                 ir->netbits,
1129
 
                 multi_instance_string (mi, false, &gc));
1130
 
          else
1131
 
            msg (D_MULTI_LOW, "MULTI: internal route %s -> %s",
1132
 
                 print_in_addr_t (ir->network, 0, &gc),
1133
 
                 multi_instance_string (mi, false, &gc));
1134
 
 
1135
 
          mroute_helper_add_iroute (m->route_helper, ir);
1136
 
      
1137
 
          multi_learn_in_addr_t (m, mi, ir->network, ir->netbits, false);
1138
 
        }
1139
 
      for ( ir6 = mi->context.options.iroutes_ipv6; ir6 != NULL; ir6 = ir6->next )
1140
 
        {
1141
 
          if (ir6->netbits >= 0)
1142
 
            msg (D_MULTI_LOW, "MULTI: internal route %s/%d -> %s",
1143
 
                 print_in6_addr (ir6->network, 0, &gc),
1144
 
                 ir6->netbits,
1145
 
                 multi_instance_string (mi, false, &gc));
1146
 
          else
1147
 
            msg (D_MULTI_LOW, "MULTI: internal route %s -> %s",
1148
 
                 print_in6_addr (ir6->network, 0, &gc),
1149
 
                 multi_instance_string (mi, false, &gc));
1150
 
 
1151
 
          mroute_helper_add_iroute6 (m->route_helper, ir6);
1152
 
      
1153
 
          multi_learn_in6_addr (m, mi, ir6->network, ir6->netbits, false);
1154
 
        }
1155
 
    }
1156
 
  gc_free (&gc);
1157
 
}
1158
 
 
1159
 
/*
1160
 
 * Given an instance (new_mi), delete all other instances which use the
1161
 
 * same common name.
1162
 
 */
1163
 
static void
1164
 
multi_delete_dup (struct multi_context *m, struct multi_instance *new_mi)
1165
 
{
1166
 
  if (new_mi)
1167
 
    {
1168
 
      const char *new_cn = tls_common_name (new_mi->context.c2.tls_multi, true);
1169
 
      if (new_cn)
1170
 
        {
1171
 
          struct hash_iterator hi;
1172
 
          struct hash_element *he;
1173
 
          int count = 0;
1174
 
 
1175
 
          hash_iterator_init (m->iter, &hi);
1176
 
          while ((he = hash_iterator_next (&hi)))
1177
 
            {
1178
 
              struct multi_instance *mi = (struct multi_instance *) he->value;
1179
 
              if (mi != new_mi && !mi->halt)
1180
 
                {
1181
 
                  const char *cn = tls_common_name (mi->context.c2.tls_multi, true);
1182
 
                  if (cn && !strcmp (cn, new_cn))
1183
 
                    {
1184
 
                      mi->did_iter = false;
1185
 
                      multi_close_instance (m, mi, false);
1186
 
                      hash_iterator_delete_element (&hi);
1187
 
                      ++count;
1188
 
                    }
1189
 
                }
1190
 
            }
1191
 
          hash_iterator_free (&hi);
1192
 
 
1193
 
          if (count)
1194
 
            msg (D_MULTI_LOW, "MULTI: new connection by client '%s' will cause previous active sessions by this client to be dropped.  Remember to use the --duplicate-cn option if you want multiple clients using the same certificate or username to concurrently connect.", new_cn);
1195
 
        }
1196
 
    }
1197
 
}
1198
 
 
1199
 
/*
1200
 
 * Ensure that endpoint to be pushed to client
1201
 
 * complies with --ifconfig-push-constraint directive.
1202
 
 */
1203
 
static bool
1204
 
ifconfig_push_constraint_satisfied (const struct context *c)
1205
 
{
1206
 
  const struct options *o = &c->options;
1207
 
  if (o->push_ifconfig_constraint_defined && c->c2.push_ifconfig_defined)
1208
 
    return (o->push_ifconfig_constraint_netmask & c->c2.push_ifconfig_local) == o->push_ifconfig_constraint_network;
1209
 
  else
1210
 
    return true;
1211
 
}
1212
 
 
1213
 
/*
1214
 
 * Select a virtual address for a new client instance.
1215
 
 * Use an --ifconfig-push directive, if given (static IP).
1216
 
 * Otherwise use an --ifconfig-pool address (dynamic IP). 
1217
 
 */
1218
 
static void
1219
 
multi_select_virtual_addr (struct multi_context *m, struct multi_instance *mi)
1220
 
{
1221
 
  struct gc_arena gc = gc_new ();
1222
 
 
1223
 
  /*
1224
 
   * If ifconfig addresses were set by dynamic config file,
1225
 
   * release pool addresses, otherwise keep them.
1226
 
   */
1227
 
  if (mi->context.options.push_ifconfig_defined)
1228
 
    {
1229
 
      /* ifconfig addresses were set statically,
1230
 
         release dynamic allocation */
1231
 
      if (mi->vaddr_handle >= 0)
1232
 
        {
1233
 
          ifconfig_pool_release (m->ifconfig_pool, mi->vaddr_handle, true);
1234
 
          mi->vaddr_handle = -1;
1235
 
        }
1236
 
 
1237
 
      mi->context.c2.push_ifconfig_defined = true;
1238
 
      mi->context.c2.push_ifconfig_local = mi->context.options.push_ifconfig_local;
1239
 
      mi->context.c2.push_ifconfig_remote_netmask = mi->context.options.push_ifconfig_remote_netmask;
1240
 
 
1241
 
      /* the current implementation does not allow "static IPv4, pool IPv6",
1242
 
       * (see below) so issue a warning if that happens - don't break the
1243
 
       * session, though, as we don't even know if this client WANTS IPv6
1244
 
       */
1245
 
      if ( mi->context.c1.tuntap->ipv6 &&
1246
 
           mi->context.options.ifconfig_ipv6_pool_defined &&
1247
 
           ! mi->context.options.push_ifconfig_ipv6_defined )
1248
 
        {
1249
 
          msg( M_INFO, "MULTI_sva: WARNING: if --ifconfig-push is used for IPv4, automatic IPv6 assignment from --ifconfig-ipv6-pool does not work.  Use --ifconfig-ipv6-push for IPv6 then." );
1250
 
        }
1251
 
    }
1252
 
  else if (m->ifconfig_pool && mi->vaddr_handle < 0) /* otherwise, choose a pool address */
1253
 
    {
1254
 
      in_addr_t local=0, remote=0;
1255
 
      struct in6_addr remote_ipv6;
1256
 
      const char *cn = NULL;
1257
 
 
1258
 
      if (!mi->context.options.duplicate_cn)
1259
 
        cn = tls_common_name (mi->context.c2.tls_multi, true);
1260
 
 
1261
 
      mi->vaddr_handle = ifconfig_pool_acquire (m->ifconfig_pool, &local, &remote, &remote_ipv6, cn);
1262
 
      if (mi->vaddr_handle >= 0)
1263
 
        {
1264
 
          const int tunnel_type = TUNNEL_TYPE (mi->context.c1.tuntap);
1265
 
          const int tunnel_topology = TUNNEL_TOPOLOGY (mi->context.c1.tuntap);
1266
 
 
1267
 
          msg( M_INFO, "MULTI_sva: pool returned IPv4=%s, IPv6=%s", 
1268
 
                    print_in_addr_t( remote, 0, &gc ),
1269
 
                    print_in6_addr( remote_ipv6, 0, &gc ) );
1270
 
 
1271
 
          /* set push_ifconfig_remote_netmask from pool ifconfig address(es) */
1272
 
          mi->context.c2.push_ifconfig_local = remote;
1273
 
          if (tunnel_type == DEV_TYPE_TAP || (tunnel_type == DEV_TYPE_TUN && tunnel_topology == TOP_SUBNET))
1274
 
            {
1275
 
              mi->context.c2.push_ifconfig_remote_netmask = mi->context.options.ifconfig_pool_netmask;
1276
 
              if (!mi->context.c2.push_ifconfig_remote_netmask)
1277
 
                mi->context.c2.push_ifconfig_remote_netmask = mi->context.c1.tuntap->remote_netmask;
1278
 
            }
1279
 
          else if (tunnel_type == DEV_TYPE_TUN)
1280
 
            {
1281
 
              if (tunnel_topology == TOP_P2P)               
1282
 
                mi->context.c2.push_ifconfig_remote_netmask = mi->context.c1.tuntap->local;
1283
 
              else if (tunnel_topology == TOP_NET30)                
1284
 
                mi->context.c2.push_ifconfig_remote_netmask = local;
1285
 
            }
1286
 
 
1287
 
          if (mi->context.c2.push_ifconfig_remote_netmask)
1288
 
            mi->context.c2.push_ifconfig_defined = true;
1289
 
          else
1290
 
            msg (D_MULTI_ERRORS, "MULTI: no --ifconfig-pool netmask parameter is available to push to %s",
1291
 
                 multi_instance_string (mi, false, &gc));
1292
 
 
1293
 
          if ( mi->context.options.ifconfig_ipv6_pool_defined )
1294
 
            {
1295
 
              mi->context.c2.push_ifconfig_ipv6_local = remote_ipv6;
1296
 
              mi->context.c2.push_ifconfig_ipv6_remote = 
1297
 
                    mi->context.c1.tuntap->local_ipv6;
1298
 
              mi->context.c2.push_ifconfig_ipv6_netbits = 
1299
 
                    mi->context.options.ifconfig_ipv6_pool_netbits;
1300
 
              mi->context.c2.push_ifconfig_ipv6_defined = true;
1301
 
            }
1302
 
        }
1303
 
      else
1304
 
        {
1305
 
          msg (D_MULTI_ERRORS, "MULTI: no free --ifconfig-pool addresses are available");
1306
 
        }
1307
 
    }
1308
 
 
1309
 
  /* IPv6 push_ifconfig is a bit problematic - since IPv6 shares the 
1310
 
   * pool handling with IPv4, the combination "static IPv4, dynamic IPv6"
1311
 
   * will fail (because no pool will be allocated in this case).
1312
 
   * OTOH, this doesn't make too much sense in reality - and the other
1313
 
   * way round ("dynamic IPv4, static IPv6") or "both static" makes sense
1314
 
   * -> and so it's implemented right now
1315
 
   */
1316
 
  if ( mi->context.c1.tuntap->ipv6 &&
1317
 
       mi->context.options.push_ifconfig_ipv6_defined )
1318
 
    {
1319
 
      mi->context.c2.push_ifconfig_ipv6_local = 
1320
 
            mi->context.options.push_ifconfig_ipv6_local;
1321
 
      mi->context.c2.push_ifconfig_ipv6_remote = 
1322
 
            mi->context.options.push_ifconfig_ipv6_remote;
1323
 
      mi->context.c2.push_ifconfig_ipv6_netbits = 
1324
 
            mi->context.options.push_ifconfig_ipv6_netbits;
1325
 
      mi->context.c2.push_ifconfig_ipv6_defined = true;
1326
 
 
1327
 
      msg( M_INFO, "MULTI_sva: push_ifconfig_ipv6 %s/%d", 
1328
 
            print_in6_addr( mi->context.c2.push_ifconfig_ipv6_local, 0, &gc ),
1329
 
            mi->context.c2.push_ifconfig_ipv6_netbits );
1330
 
    }
1331
 
 
1332
 
  gc_free (&gc);
1333
 
}
1334
 
 
1335
 
/*
1336
 
 * Set virtual address environmental variables.
1337
 
 */
1338
 
static void
1339
 
multi_set_virtual_addr_env (struct multi_context *m, struct multi_instance *mi)
1340
 
{
1341
 
  setenv_del (mi->context.c2.es, "ifconfig_pool_local_ip");
1342
 
  setenv_del (mi->context.c2.es, "ifconfig_pool_remote_ip");
1343
 
  setenv_del (mi->context.c2.es, "ifconfig_pool_netmask");
1344
 
 
1345
 
  if (mi->context.c2.push_ifconfig_defined)
1346
 
    {
1347
 
      const int tunnel_type = TUNNEL_TYPE (mi->context.c1.tuntap);
1348
 
      const int tunnel_topology = TUNNEL_TOPOLOGY (mi->context.c1.tuntap);
1349
 
 
1350
 
      setenv_in_addr_t (mi->context.c2.es,
1351
 
                        "ifconfig_pool_remote_ip",
1352
 
                        mi->context.c2.push_ifconfig_local,
1353
 
                        SA_SET_IF_NONZERO);
1354
 
 
1355
 
      if (tunnel_type == DEV_TYPE_TAP || (tunnel_type == DEV_TYPE_TUN && tunnel_topology == TOP_SUBNET))
1356
 
        {
1357
 
          setenv_in_addr_t (mi->context.c2.es,
1358
 
                            "ifconfig_pool_netmask",
1359
 
                            mi->context.c2.push_ifconfig_remote_netmask,
1360
 
                            SA_SET_IF_NONZERO);
1361
 
        }
1362
 
      else if (tunnel_type == DEV_TYPE_TUN)
1363
 
        {
1364
 
          setenv_in_addr_t (mi->context.c2.es,
1365
 
                            "ifconfig_pool_local_ip",
1366
 
                            mi->context.c2.push_ifconfig_remote_netmask,
1367
 
                            SA_SET_IF_NONZERO);
1368
 
        }
1369
 
    }
1370
 
 
1371
 
    /* TODO: I'm not exactly sure what these environment variables are
1372
 
     *       used for, but if we have them for IPv4, we should also have
1373
 
     *       them for IPv6, no?
1374
 
     */
1375
 
}
1376
 
 
1377
 
/*
1378
 
 * Called after client-connect script is called
1379
 
 */
1380
 
static void
1381
 
multi_client_connect_post (struct multi_context *m,
1382
 
                           struct multi_instance *mi,
1383
 
                           const char *dc_file,
1384
 
                           unsigned int option_permissions_mask,
1385
 
                           unsigned int *option_types_found)
1386
 
{
1387
 
  /* Did script generate a dynamic config file? */
1388
 
  if (test_file (dc_file))
1389
 
    {
1390
 
      options_server_import (&mi->context.options,
1391
 
                             dc_file,
1392
 
                             D_IMPORT_ERRORS|M_OPTERR,
1393
 
                             option_permissions_mask,
1394
 
                             option_types_found,
1395
 
                             mi->context.c2.es);
1396
 
 
1397
 
      if (!delete_file (dc_file))
1398
 
        msg (D_MULTI_ERRORS, "MULTI: problem deleting temporary file: %s",
1399
 
             dc_file);
1400
 
 
1401
 
      /*
1402
 
       * If the --client-connect script generates a config file
1403
 
       * with an --ifconfig-push directive, it will override any
1404
 
       * --ifconfig-push directive from the --client-config-dir
1405
 
       * directory or any --ifconfig-pool dynamic address.
1406
 
       */
1407
 
      multi_select_virtual_addr (m, mi);
1408
 
      multi_set_virtual_addr_env (m, mi);
1409
 
    }
1410
 
}
1411
 
 
1412
 
#ifdef ENABLE_PLUGIN
1413
 
 
1414
 
/*
1415
 
 * Called after client-connect plug-in is called
1416
 
 */
1417
 
static void
1418
 
multi_client_connect_post_plugin (struct multi_context *m,
1419
 
                                  struct multi_instance *mi,
1420
 
                                  const struct plugin_return *pr,
1421
 
                                  unsigned int option_permissions_mask,
1422
 
                                  unsigned int *option_types_found)
1423
 
{
1424
 
  struct plugin_return config;
1425
 
 
1426
 
  plugin_return_get_column (pr, &config, "config");
1427
 
 
1428
 
  /* Did script generate a dynamic config file? */
1429
 
  if (plugin_return_defined (&config))
1430
 
    {
1431
 
      int i;
1432
 
      for (i = 0; i < config.n; ++i)
1433
 
        {
1434
 
          if (config.list[i] && config.list[i]->value)
1435
 
            options_string_import (&mi->context.options,
1436
 
                                   config.list[i]->value,
1437
 
                                   D_IMPORT_ERRORS|M_OPTERR,
1438
 
                                   option_permissions_mask,
1439
 
                                   option_types_found,
1440
 
                                   mi->context.c2.es);
1441
 
        }
1442
 
 
1443
 
      /*
1444
 
       * If the --client-connect script generates a config file
1445
 
       * with an --ifconfig-push directive, it will override any
1446
 
       * --ifconfig-push directive from the --client-config-dir
1447
 
       * directory or any --ifconfig-pool dynamic address.
1448
 
       */
1449
 
      multi_select_virtual_addr (m, mi);
1450
 
      multi_set_virtual_addr_env (m, mi);
1451
 
    }
1452
 
}
1453
 
 
1454
 
#endif
1455
 
 
1456
 
#ifdef MANAGEMENT_DEF_AUTH
1457
 
 
1458
 
/*
1459
 
 * Called to load management-derived client-connect config
1460
 
 */
1461
 
static void
1462
 
multi_client_connect_mda (struct multi_context *m,
1463
 
                          struct multi_instance *mi,
1464
 
                          const struct buffer_list *config,
1465
 
                          unsigned int option_permissions_mask,
1466
 
                          unsigned int *option_types_found)
1467
 
{
1468
 
  if (config)
1469
 
    {
1470
 
      struct buffer_entry *be;
1471
 
  
1472
 
      for (be = config->head; be != NULL; be = be->next)
1473
 
        {
1474
 
          const char *opt = BSTR(&be->buf);
1475
 
          options_string_import (&mi->context.options,
1476
 
                                 opt,
1477
 
                                 D_IMPORT_ERRORS|M_OPTERR,
1478
 
                                 option_permissions_mask,
1479
 
                                 option_types_found,
1480
 
                                 mi->context.c2.es);
1481
 
        }
1482
 
 
1483
 
      /*
1484
 
       * If the --client-connect script generates a config file
1485
 
       * with an --ifconfig-push directive, it will override any
1486
 
       * --ifconfig-push directive from the --client-config-dir
1487
 
       * directory or any --ifconfig-pool dynamic address.
1488
 
       */
1489
 
      multi_select_virtual_addr (m, mi);
1490
 
      multi_set_virtual_addr_env (m, mi);
1491
 
    }
1492
 
}
1493
 
 
1494
 
#endif
1495
 
 
1496
 
static void
1497
 
multi_client_connect_setenv (struct multi_context *m,
1498
 
                             struct multi_instance *mi)
1499
 
{
1500
 
  struct gc_arena gc = gc_new ();
1501
 
 
1502
 
  /* setenv incoming cert common name for script */
1503
 
  setenv_str (mi->context.c2.es, "common_name", tls_common_name (mi->context.c2.tls_multi, true));
1504
 
 
1505
 
  /* setenv client real IP address */
1506
 
  setenv_trusted (mi->context.c2.es, get_link_socket_info (&mi->context));
1507
 
 
1508
 
  /* setenv client virtual IP address */
1509
 
  multi_set_virtual_addr_env (m, mi);
1510
 
 
1511
 
  /* setenv connection time */
1512
 
  {
1513
 
    const char *created_ascii = time_string (mi->created, 0, false, &gc);
1514
 
    setenv_str (mi->context.c2.es, "time_ascii", created_ascii);
1515
 
    setenv_unsigned (mi->context.c2.es, "time_unix", (unsigned int)mi->created);
1516
 
  }
1517
 
 
1518
 
  gc_free (&gc);
1519
 
}
1520
 
 
1521
 
/*
1522
 
 * Called as soon as the SSL/TLS connection authenticates.
1523
 
 *
1524
 
 * Instance-specific directives to be processed:
1525
 
 *
1526
 
 *   iroute start-ip end-ip
1527
 
 *   ifconfig-push local remote-netmask
1528
 
 *   push
1529
 
 */
1530
 
static void
1531
 
multi_connection_established (struct multi_context *m, struct multi_instance *mi)
1532
 
{
1533
 
  if (tls_authentication_status (mi->context.c2.tls_multi, 0) == TLS_AUTHENTICATION_SUCCEEDED)
1534
 
    {
1535
 
      struct gc_arena gc = gc_new ();
1536
 
      unsigned int option_types_found = 0;
1537
 
 
1538
 
      const unsigned int option_permissions_mask =
1539
 
          OPT_P_INSTANCE
1540
 
        | OPT_P_INHERIT
1541
 
        | OPT_P_PUSH
1542
 
        | OPT_P_TIMER
1543
 
        | OPT_P_CONFIG
1544
 
        | OPT_P_ECHO
1545
 
        | OPT_P_COMP
1546
 
        | OPT_P_SOCKFLAGS;
1547
 
 
1548
 
      int cc_succeeded = true; /* client connect script status */
1549
 
      int cc_succeeded_count = 0;
1550
 
 
1551
 
      ASSERT (mi->context.c1.tuntap);
1552
 
 
1553
 
      /* lock down the common name and cert hashes so they can't change during future TLS renegotiations */
1554
 
      tls_lock_common_name (mi->context.c2.tls_multi);
1555
 
      tls_lock_cert_hash_set (mi->context.c2.tls_multi);
1556
 
 
1557
 
      /* generate a msg() prefix for this client instance */
1558
 
      generate_prefix (mi);
1559
 
 
1560
 
      /* delete instances of previous clients with same common-name */
1561
 
      if (!mi->context.options.duplicate_cn)
1562
 
        multi_delete_dup (m, mi);
1563
 
 
1564
 
      /* reset pool handle to null */
1565
 
      mi->vaddr_handle = -1;
1566
 
 
1567
 
      /*
1568
 
       * Try to source a dynamic config file from the
1569
 
       * --client-config-dir directory.
1570
 
       */
1571
 
      if (mi->context.options.client_config_dir)
1572
 
        {
1573
 
          const char *ccd_file;
1574
 
          
1575
 
          ccd_file = gen_path (mi->context.options.client_config_dir,
1576
 
                               tls_common_name (mi->context.c2.tls_multi, false),
1577
 
                               &gc);
1578
 
 
1579
 
          /* try common-name file */
1580
 
          if (test_file (ccd_file))
1581
 
            {
1582
 
              options_server_import (&mi->context.options,
1583
 
                                     ccd_file,
1584
 
                                     D_IMPORT_ERRORS|M_OPTERR,
1585
 
                                     option_permissions_mask,
1586
 
                                     &option_types_found,
1587
 
                                     mi->context.c2.es);
1588
 
            }
1589
 
          else /* try default file */
1590
 
            {
1591
 
              ccd_file = gen_path (mi->context.options.client_config_dir,
1592
 
                                   CCD_DEFAULT,
1593
 
                                   &gc);
1594
 
 
1595
 
              if (test_file (ccd_file))
1596
 
                {
1597
 
                  options_server_import (&mi->context.options,
1598
 
                                         ccd_file,
1599
 
                                         D_IMPORT_ERRORS|M_OPTERR,
1600
 
                                         option_permissions_mask,
1601
 
                                         &option_types_found,
1602
 
                                         mi->context.c2.es);
1603
 
                }
1604
 
            }
1605
 
        }
1606
 
 
1607
 
      /*
1608
 
       * Select a virtual address from either --ifconfig-push in --client-config-dir file
1609
 
       * or --ifconfig-pool.
1610
 
       */
1611
 
      multi_select_virtual_addr (m, mi);
1612
 
 
1613
 
      /* do --client-connect setenvs */
1614
 
      multi_client_connect_setenv (m, mi);
1615
 
 
1616
 
#ifdef ENABLE_PLUGIN
1617
 
      /*
1618
 
       * Call client-connect plug-in.
1619
 
       */
1620
 
 
1621
 
      /* deprecated callback, use a file for passing back return info */
1622
 
      if (plugin_defined (mi->context.plugins, OPENVPN_PLUGIN_CLIENT_CONNECT))
1623
 
        {
1624
 
          struct argv argv = argv_new ();
1625
 
          const char *dc_file = create_temp_file (mi->context.options.tmp_dir, "cc", &gc);
1626
 
 
1627
 
          if( !dc_file ) {
1628
 
            cc_succeeded = false;
1629
 
            goto script_depr_failed;
1630
 
          }
1631
 
 
1632
 
          argv_printf (&argv, "%s", dc_file);
1633
 
          if (plugin_call (mi->context.plugins, OPENVPN_PLUGIN_CLIENT_CONNECT, &argv, NULL, mi->context.c2.es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
1634
 
            {
1635
 
              msg (M_WARN, "WARNING: client-connect plugin call failed");
1636
 
              cc_succeeded = false;
1637
 
            }
1638
 
          else
1639
 
            {
1640
 
              multi_client_connect_post (m, mi, dc_file, option_permissions_mask, &option_types_found);
1641
 
              ++cc_succeeded_count;
1642
 
            }
1643
 
        script_depr_failed:
1644
 
          argv_reset (&argv);
1645
 
        }
1646
 
 
1647
 
      /* V2 callback, use a plugin_return struct for passing back return info */
1648
 
      if (plugin_defined (mi->context.plugins, OPENVPN_PLUGIN_CLIENT_CONNECT_V2))
1649
 
        {
1650
 
          struct plugin_return pr;
1651
 
 
1652
 
          plugin_return_init (&pr);
1653
 
 
1654
 
          if (plugin_call (mi->context.plugins, OPENVPN_PLUGIN_CLIENT_CONNECT_V2, NULL, &pr, mi->context.c2.es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
1655
 
            {
1656
 
              msg (M_WARN, "WARNING: client-connect-v2 plugin call failed");
1657
 
              cc_succeeded = false;
1658
 
            }
1659
 
          else
1660
 
            {
1661
 
              multi_client_connect_post_plugin (m, mi, &pr, option_permissions_mask, &option_types_found);
1662
 
              ++cc_succeeded_count;
1663
 
            }
1664
 
 
1665
 
          plugin_return_free (&pr);
1666
 
        }
1667
 
#endif
1668
 
 
1669
 
      /*
1670
 
       * Run --client-connect script.
1671
 
       */
1672
 
      if (mi->context.options.client_connect_script && cc_succeeded)
1673
 
        {
1674
 
          struct argv argv = argv_new ();
1675
 
          const char *dc_file = NULL;
1676
 
 
1677
 
          setenv_str (mi->context.c2.es, "script_type", "client-connect");
1678
 
 
1679
 
          dc_file = create_temp_file (mi->context.options.tmp_dir, "cc", &gc);
1680
 
          if( !dc_file ) {
1681
 
            cc_succeeded = false;
1682
 
            goto script_failed;
1683
 
          }
1684
 
 
1685
 
          argv_printf (&argv, "%sc %s",
1686
 
                       mi->context.options.client_connect_script,
1687
 
                       dc_file);
1688
 
 
1689
 
          if (openvpn_run_script (&argv, mi->context.c2.es, 0, "--client-connect"))
1690
 
            {
1691
 
              multi_client_connect_post (m, mi, dc_file, option_permissions_mask, &option_types_found);
1692
 
              ++cc_succeeded_count;
1693
 
            }
1694
 
          else
1695
 
            cc_succeeded = false;
1696
 
        script_failed:
1697
 
          argv_reset (&argv);
1698
 
        }
1699
 
 
1700
 
      /*
1701
 
       * Check for client-connect script left by management interface client
1702
 
       */
1703
 
#ifdef MANAGEMENT_DEF_AUTH
1704
 
      if (cc_succeeded && mi->cc_config)
1705
 
        {
1706
 
          multi_client_connect_mda (m, mi, mi->cc_config, option_permissions_mask, &option_types_found);
1707
 
          ++cc_succeeded_count;
1708
 
        }
1709
 
#endif
1710
 
 
1711
 
      /*
1712
 
       * Check for "disable" directive in client-config-dir file
1713
 
       * or config file generated by --client-connect script.
1714
 
       */
1715
 
      if (mi->context.options.disable)
1716
 
        {
1717
 
          msg (D_MULTI_ERRORS, "MULTI: client has been rejected due to 'disable' directive");
1718
 
          cc_succeeded = false;
1719
 
        }
1720
 
 
1721
 
      if (cc_succeeded)
1722
 
        {
1723
 
          /*
1724
 
           * Process sourced options.
1725
 
           */
1726
 
          do_deferred_options (&mi->context, option_types_found);
1727
 
 
1728
 
          /*
1729
 
           * make sure we got ifconfig settings from somewhere
1730
 
           */
1731
 
          if (!mi->context.c2.push_ifconfig_defined)
1732
 
            {
1733
 
              msg (D_MULTI_ERRORS, "MULTI: no dynamic or static remote --ifconfig address is available for %s",
1734
 
                   multi_instance_string (mi, false, &gc));
1735
 
            }
1736
 
 
1737
 
          /*
1738
 
           * make sure that ifconfig settings comply with constraints
1739
 
           */
1740
 
          if (!ifconfig_push_constraint_satisfied (&mi->context))
1741
 
            {
1742
 
              /* JYFIXME -- this should cause the connection to fail */
1743
 
              msg (D_MULTI_ERRORS, "MULTI ERROR: primary virtual IP for %s (%s) violates tunnel network/netmask constraint (%s/%s)",
1744
 
                   multi_instance_string (mi, false, &gc),
1745
 
                   print_in_addr_t (mi->context.c2.push_ifconfig_local, 0, &gc),
1746
 
                   print_in_addr_t (mi->context.options.push_ifconfig_constraint_network, 0, &gc),
1747
 
                   print_in_addr_t (mi->context.options.push_ifconfig_constraint_netmask, 0, &gc));
1748
 
            }
1749
 
 
1750
 
          /*
1751
 
           * For routed tunnels, set up internal route to endpoint
1752
 
           * plus add all iroute routes.
1753
 
           */
1754
 
          if (TUNNEL_TYPE (mi->context.c1.tuntap) == DEV_TYPE_TUN)
1755
 
            {
1756
 
              if (mi->context.c2.push_ifconfig_defined)
1757
 
                {
1758
 
                  multi_learn_in_addr_t (m, mi, mi->context.c2.push_ifconfig_local, -1, true);
1759
 
                  msg (D_MULTI_LOW, "MULTI: primary virtual IP for %s: %s",
1760
 
                       multi_instance_string (mi, false, &gc),
1761
 
                       print_in_addr_t (mi->context.c2.push_ifconfig_local, 0, &gc));
1762
 
                }
1763
 
 
1764
 
              if (mi->context.c2.push_ifconfig_ipv6_defined)
1765
 
                {
1766
 
                  multi_learn_in6_addr (m, mi, mi->context.c2.push_ifconfig_ipv6_local, -1, true);
1767
 
                  /* TODO: find out where addresses are "unlearned"!! */
1768
 
                  msg (D_MULTI_LOW, "MULTI: primary virtual IPv6 for %s: %s",
1769
 
                       multi_instance_string (mi, false, &gc),
1770
 
                       print_in6_addr (mi->context.c2.push_ifconfig_ipv6_local, 0, &gc));
1771
 
                }
1772
 
 
1773
 
              /* add routes locally, pointing to new client, if
1774
 
                 --iroute options have been specified */
1775
 
              multi_add_iroutes (m, mi);
1776
 
 
1777
 
              /*
1778
 
               * iroutes represent subnets which are "owned" by a particular
1779
 
               * client.  Therefore, do not actually push a route to a client
1780
 
               * if it matches one of the client's iroutes.
1781
 
               */
1782
 
              remove_iroutes_from_push_route_list (&mi->context.options);
1783
 
            }
1784
 
          else if (mi->context.options.iroutes)
1785
 
            {
1786
 
              msg (D_MULTI_ERRORS, "MULTI: --iroute options rejected for %s -- iroute only works with tun-style tunnels",
1787
 
                   multi_instance_string (mi, false, &gc));
1788
 
            }
1789
 
 
1790
 
          /* set our client's VPN endpoint for status reporting purposes */
1791
 
          mi->reporting_addr = mi->context.c2.push_ifconfig_local;
1792
 
 
1793
 
          /* set context-level authentication flag */
1794
 
          mi->context.c2.context_auth = CAS_SUCCEEDED;
1795
 
        }
1796
 
      else
1797
 
        {
1798
 
          /* set context-level authentication flag */
1799
 
          mi->context.c2.context_auth = cc_succeeded_count ? CAS_PARTIAL : CAS_FAILED;
1800
 
        }
1801
 
 
1802
 
      /* set flag so we don't get called again */
1803
 
      mi->connection_established_flag = true;
1804
 
 
1805
 
      /* increment number of current authenticated clients */
1806
 
      ++m->n_clients;
1807
 
      --mi->n_clients_delta;
1808
 
 
1809
 
#ifdef MANAGEMENT_DEF_AUTH
1810
 
      if (management)
1811
 
        management_connection_established (management, &mi->context.c2.mda_context, mi->context.c2.es);
1812
 
#endif
1813
 
 
1814
 
      gc_free (&gc);
1815
 
    }
1816
 
 
1817
 
  /*
1818
 
   * Reply now to client's PUSH_REQUEST query
1819
 
   */
1820
 
  mi->context.c2.push_reply_deferred = false;
1821
 
}
1822
 
 
1823
 
/*
1824
 
 * Add a mbuf buffer to a particular
1825
 
 * instance.
1826
 
 */
1827
 
void
1828
 
multi_add_mbuf (struct multi_context *m,
1829
 
                struct multi_instance *mi,
1830
 
                struct mbuf_buffer *mb)
1831
 
{
1832
 
  if (multi_output_queue_ready (m, mi))
1833
 
    {
1834
 
      struct mbuf_item item;
1835
 
      item.buffer = mb;
1836
 
      item.instance = mi;
1837
 
      mbuf_add_item (m->mbuf, &item);
1838
 
    }
1839
 
  else
1840
 
    {
1841
 
      msg (D_MULTI_DROPPED, "MULTI: packet dropped due to output saturation (multi_add_mbuf)");
1842
 
    }
1843
 
}
1844
 
 
1845
 
/*
1846
 
 * Add a packet to a client instance output queue.
1847
 
 */
1848
 
static inline void
1849
 
multi_unicast (struct multi_context *m,
1850
 
               const struct buffer *buf,
1851
 
               struct multi_instance *mi)
1852
 
{
1853
 
  struct mbuf_buffer *mb;
1854
 
 
1855
 
  if (BLEN (buf) > 0)
1856
 
    {
1857
 
      mb = mbuf_alloc_buf (buf);
1858
 
      mb->flags = MF_UNICAST;
1859
 
      multi_add_mbuf (m, mi, mb);
1860
 
      mbuf_free_buf (mb);
1861
 
    }
1862
 
}
1863
 
 
1864
 
/*
1865
 
 * Broadcast a packet to all clients.
1866
 
 */
1867
 
static void
1868
 
multi_bcast (struct multi_context *m,
1869
 
             const struct buffer *buf,
1870
 
             const struct multi_instance *sender_instance,
1871
 
             const struct mroute_addr *sender_addr)
1872
 
{
1873
 
  struct hash_iterator hi;
1874
 
  struct hash_element *he;
1875
 
  struct multi_instance *mi;
1876
 
  struct mbuf_buffer *mb;
1877
 
 
1878
 
  if (BLEN (buf) > 0)
1879
 
    {
1880
 
      perf_push (PERF_MULTI_BCAST);
1881
 
#ifdef MULTI_DEBUG_EVENT_LOOP
1882
 
      printf ("BCAST len=%d\n", BLEN (buf));
1883
 
#endif
1884
 
      mb = mbuf_alloc_buf (buf);
1885
 
      hash_iterator_init (m->iter, &hi);
1886
 
 
1887
 
      while ((he = hash_iterator_next (&hi)))
1888
 
        {
1889
 
          mi = (struct multi_instance *) he->value;
1890
 
          if (mi != sender_instance && !mi->halt)
1891
 
            {
1892
 
#ifdef ENABLE_PF
1893
 
              if (sender_instance)
1894
 
                {
1895
 
                  if (!pf_c2c_test (&sender_instance->context, &mi->context, "bcast_c2c"))
1896
 
                    {
1897
 
                      msg (D_PF_DROPPED_BCAST, "PF: client[%s] -> client[%s] packet dropped by BCAST packet filter",
1898
 
                           mi_prefix (sender_instance),
1899
 
                           mi_prefix (mi));
1900
 
                      continue;
1901
 
                    }
1902
 
                }
1903
 
              if (sender_addr)
1904
 
                {
1905
 
                  if (!pf_addr_test (&mi->context, sender_addr, "bcast_src_addr"))
1906
 
                    {
1907
 
                      struct gc_arena gc = gc_new ();
1908
 
                      msg (D_PF_DROPPED_BCAST, "PF: addr[%s] -> client[%s] packet dropped by BCAST packet filter",
1909
 
                           mroute_addr_print_ex (sender_addr, MAPF_SHOW_ARP, &gc),
1910
 
                           mi_prefix (mi));
1911
 
                      gc_free (&gc);
1912
 
                      continue;
1913
 
                    }
1914
 
                }
1915
 
#endif
1916
 
              multi_add_mbuf (m, mi, mb);
1917
 
            }
1918
 
        }
1919
 
 
1920
 
      hash_iterator_free (&hi);
1921
 
      mbuf_free_buf (mb);
1922
 
      perf_pop ();
1923
 
    }
1924
 
}
1925
 
 
1926
 
/*
1927
 
 * Given a time delta, indicating that we wish to be
1928
 
 * awoken by the scheduler at time now + delta, figure
1929
 
 * a sigma parameter (in microseconds) that represents
1930
 
 * a sort of fuzz factor around delta, so that we're
1931
 
 * really telling the scheduler to wake us up any time
1932
 
 * between now + delta - sigma and now + delta + sigma.
1933
 
 *
1934
 
 * The sigma parameter helps the scheduler to run more efficiently.
1935
 
 * Sigma should be no larger than TV_WITHIN_SIGMA_MAX_USEC
1936
 
 */
1937
 
static inline unsigned int
1938
 
compute_wakeup_sigma (const struct timeval *delta)
1939
 
{
1940
 
  if (delta->tv_sec < 1)
1941
 
    {
1942
 
      /* if < 1 sec, fuzz = # of microseconds / 8 */
1943
 
      return delta->tv_usec >> 3;
1944
 
    }
1945
 
  else
1946
 
    {
1947
 
      /* if < 10 minutes, fuzz = 13.1% of timeout */
1948
 
      if (delta->tv_sec < 600)
1949
 
        return delta->tv_sec << 17;
1950
 
      else
1951
 
        return 120000000; /* if >= 10 minutes, fuzz = 2 minutes */
1952
 
    }
1953
 
}
1954
 
 
1955
 
static void
1956
 
multi_schedule_context_wakeup (struct multi_context *m, struct multi_instance *mi)
1957
 
{
1958
 
  /* calculate an absolute wakeup time */
1959
 
  ASSERT (!openvpn_gettimeofday (&mi->wakeup, NULL));
1960
 
  tv_add (&mi->wakeup, &mi->context.c2.timeval);
1961
 
 
1962
 
  /* tell scheduler to wake us up at some point in the future */
1963
 
  schedule_add_entry (m->schedule,
1964
 
                      (struct schedule_entry *) mi,
1965
 
                      &mi->wakeup,
1966
 
                      compute_wakeup_sigma (&mi->context.c2.timeval));
1967
 
}
1968
 
 
1969
 
/*
1970
 
 * Figure instance-specific timers, convert
1971
 
 * earliest to absolute time in mi->wakeup,
1972
 
 * call scheduler with our future wakeup time.
1973
 
 *
1974
 
 * Also close context on signal.
1975
 
 */
1976
 
bool
1977
 
multi_process_post (struct multi_context *m, struct multi_instance *mi, const unsigned int flags)
1978
 
{
1979
 
  bool ret = true;
1980
 
 
1981
 
  if (!IS_SIG (&mi->context) && ((flags & MPP_PRE_SELECT) || ((flags & MPP_CONDITIONAL_PRE_SELECT) && !ANY_OUT (&mi->context))))
1982
 
    {
1983
 
      /* figure timeouts and fetch possible outgoing
1984
 
         to_link packets (such as ping or TLS control) */
1985
 
      pre_select (&mi->context);
1986
 
 
1987
 
      if (!IS_SIG (&mi->context))
1988
 
        {
1989
 
          /* tell scheduler to wake us up at some point in the future */
1990
 
          multi_schedule_context_wakeup(m, mi);
1991
 
 
1992
 
          /* connection is "established" when SSL/TLS key negotiation succeeds
1993
 
             and (if specified) auth user/pass succeeds */
1994
 
          if (!mi->connection_established_flag && CONNECTION_ESTABLISHED (&mi->context))
1995
 
            multi_connection_established (m, mi);
1996
 
        }
1997
 
    }
1998
 
 
1999
 
  if (IS_SIG (&mi->context))
2000
 
    {
2001
 
      if (flags & MPP_CLOSE_ON_SIGNAL)
2002
 
        {
2003
 
          multi_close_instance_on_signal (m, mi);
2004
 
          ret = false;
2005
 
        }
2006
 
    }
2007
 
  else
2008
 
    {
2009
 
      /* continue to pend on output? */
2010
 
      multi_set_pending (m, ANY_OUT (&mi->context) ? mi : NULL);
2011
 
 
2012
 
#ifdef MULTI_DEBUG_EVENT_LOOP
2013
 
      printf ("POST %s[%d] to=%d lo=%d/%d w=%d/%d\n",
2014
 
              id(mi),
2015
 
              (int) (mi == m->pending),
2016
 
              mi ? mi->context.c2.to_tun.len : -1,
2017
 
              mi ? mi->context.c2.to_link.len : -1,
2018
 
              (mi && mi->context.c2.fragment) ? mi->context.c2.fragment->outgoing.len : -1,
2019
 
              (int)mi->context.c2.timeval.tv_sec,
2020
 
              (int)mi->context.c2.timeval.tv_usec);
2021
 
#endif
2022
 
    }
2023
 
 
2024
 
  if ((flags & MPP_RECORD_TOUCH) && m->mpp_touched)
2025
 
    *m->mpp_touched = mi;
2026
 
 
2027
 
  return ret;
2028
 
}
2029
 
 
2030
 
/*
2031
 
 * Process packets in the TCP/UDP socket -> TUN/TAP interface direction,
2032
 
 * i.e. client -> server direction.
2033
 
 */
2034
 
bool
2035
 
multi_process_incoming_link (struct multi_context *m, struct multi_instance *instance, const unsigned int mpp_flags)
2036
 
{
2037
 
  struct gc_arena gc = gc_new ();
2038
 
 
2039
 
  struct context *c;
2040
 
  struct mroute_addr src, dest;
2041
 
  unsigned int mroute_flags;
2042
 
  struct multi_instance *mi;
2043
 
  bool ret = true;
2044
 
 
2045
 
  if (m->pending)
2046
 
    return true;
2047
 
 
2048
 
  if (!instance)
2049
 
    {
2050
 
#ifdef MULTI_DEBUG_EVENT_LOOP
2051
 
      printf ("TCP/UDP -> TUN [%d]\n", BLEN (&m->top.c2.buf));
2052
 
#endif
2053
 
      multi_set_pending (m, multi_get_create_instance_udp (m));
2054
 
    }
2055
 
  else
2056
 
    multi_set_pending (m, instance);
2057
 
 
2058
 
  if (m->pending)
2059
 
    {
2060
 
      set_prefix (m->pending);
2061
 
 
2062
 
      /* get instance context */
2063
 
      c = &m->pending->context;
2064
 
 
2065
 
      if (!instance)
2066
 
        {
2067
 
          /* transfer packet pointer from top-level context buffer to instance */
2068
 
          c->c2.buf = m->top.c2.buf;
2069
 
 
2070
 
          /* transfer from-addr from top-level context buffer to instance */
2071
 
          c->c2.from = m->top.c2.from;
2072
 
        }
2073
 
 
2074
 
      if (BLEN (&c->c2.buf) > 0)
2075
 
        {
2076
 
          /* decrypt in instance context */
2077
 
          process_incoming_link (c);
2078
 
 
2079
 
          if (TUNNEL_TYPE (m->top.c1.tuntap) == DEV_TYPE_TUN)
2080
 
            {
2081
 
              /* extract packet source and dest addresses */
2082
 
              mroute_flags = mroute_extract_addr_from_packet (&src,
2083
 
                                                              &dest,
2084
 
                                                              NULL,
2085
 
                                                              NULL,
2086
 
                                                              &c->c2.to_tun,
2087
 
                                                              DEV_TYPE_TUN);
2088
 
 
2089
 
              /* drop packet if extract failed */
2090
 
              if (!(mroute_flags & MROUTE_EXTRACT_SUCCEEDED))
2091
 
                {
2092
 
                  c->c2.to_tun.len = 0;
2093
 
                }
2094
 
              /* make sure that source address is associated with this client */
2095
 
              else if (multi_get_instance_by_virtual_addr (m, &src, true) != m->pending)
2096
 
                {
2097
 
                  msg (D_MULTI_DROPPED, "MULTI: bad source address from client [%s], packet dropped",
2098
 
                       mroute_addr_print (&src, &gc));
2099
 
                  c->c2.to_tun.len = 0;
2100
 
                }
2101
 
              /* client-to-client communication enabled? */
2102
 
              else if (m->enable_c2c)
2103
 
                {
2104
 
                  /* multicast? */
2105
 
                  if (mroute_flags & MROUTE_EXTRACT_MCAST)
2106
 
                    {
2107
 
                      /* for now, treat multicast as broadcast */
2108
 
                      multi_bcast (m, &c->c2.to_tun, m->pending, NULL);
2109
 
                    }
2110
 
                  else /* possible client to client routing */
2111
 
                    {
2112
 
                      ASSERT (!(mroute_flags & MROUTE_EXTRACT_BCAST));
2113
 
                      mi = multi_get_instance_by_virtual_addr (m, &dest, true);
2114
 
                  
2115
 
                      /* if dest addr is a known client, route to it */
2116
 
                      if (mi)
2117
 
                        {
2118
 
#ifdef ENABLE_PF
2119
 
                          if (!pf_c2c_test (c, &mi->context, "tun_c2c"))
2120
 
                            {
2121
 
                              msg (D_PF_DROPPED, "PF: client -> client[%s] packet dropped by TUN packet filter",
2122
 
                                   mi_prefix (mi));
2123
 
                            }
2124
 
                          else
2125
 
#endif
2126
 
                            {
2127
 
                              multi_unicast (m, &c->c2.to_tun, mi);
2128
 
                              register_activity (c, BLEN(&c->c2.to_tun));
2129
 
                            }
2130
 
                          c->c2.to_tun.len = 0;
2131
 
                        }
2132
 
                    }
2133
 
                }
2134
 
#ifdef ENABLE_PF
2135
 
              if (c->c2.to_tun.len && !pf_addr_test (c, &dest, "tun_dest_addr"))
2136
 
                {
2137
 
                  msg (D_PF_DROPPED, "PF: client -> addr[%s] packet dropped by TUN packet filter",
2138
 
                       mroute_addr_print_ex (&dest, MAPF_SHOW_ARP, &gc));
2139
 
                  c->c2.to_tun.len = 0;
2140
 
                }
2141
 
#endif
2142
 
            }
2143
 
          else if (TUNNEL_TYPE (m->top.c1.tuntap) == DEV_TYPE_TAP)
2144
 
            {
2145
 
#ifdef ENABLE_PF
2146
 
              struct mroute_addr edest;
2147
 
              mroute_addr_reset (&edest);
2148
 
#endif
2149
 
              /* extract packet source and dest addresses */
2150
 
              mroute_flags = mroute_extract_addr_from_packet (&src,
2151
 
                                                              &dest,
2152
 
                                                              NULL,
2153
 
#ifdef ENABLE_PF
2154
 
                                                              &edest,
2155
 
#else
2156
 
                                                              NULL,
2157
 
#endif
2158
 
                                                              &c->c2.to_tun,
2159
 
                                                              DEV_TYPE_TAP);
2160
 
 
2161
 
              if (mroute_flags & MROUTE_EXTRACT_SUCCEEDED)
2162
 
                {
2163
 
                  if (multi_learn_addr (m, m->pending, &src, 0) == m->pending)
2164
 
                    {
2165
 
                      /* check for broadcast */
2166
 
                      if (m->enable_c2c)
2167
 
                        {
2168
 
                          if (mroute_flags & (MROUTE_EXTRACT_BCAST|MROUTE_EXTRACT_MCAST))
2169
 
                            {
2170
 
                              multi_bcast (m, &c->c2.to_tun, m->pending, NULL);
2171
 
                            }
2172
 
                          else /* try client-to-client routing */
2173
 
                            {
2174
 
                              mi = multi_get_instance_by_virtual_addr (m, &dest, false);
2175
 
 
2176
 
                              /* if dest addr is a known client, route to it */
2177
 
                              if (mi)
2178
 
                                {
2179
 
#ifdef ENABLE_PF
2180
 
                                  if (!pf_c2c_test (c, &mi->context, "tap_c2c"))
2181
 
                                    {
2182
 
                                      msg (D_PF_DROPPED, "PF: client -> client[%s] packet dropped by TAP packet filter",
2183
 
                                           mi_prefix (mi));
2184
 
                                    }
2185
 
                                  else
2186
 
#endif
2187
 
                                    {
2188
 
                                      multi_unicast (m, &c->c2.to_tun, mi);
2189
 
                                      register_activity (c, BLEN(&c->c2.to_tun));
2190
 
                                    }
2191
 
                                  c->c2.to_tun.len = 0;
2192
 
                                }
2193
 
                            }
2194
 
                        }
2195
 
#ifdef ENABLE_PF
2196
 
                      if (c->c2.to_tun.len && !pf_addr_test (c, &edest, "tap_dest_addr"))
2197
 
                        {
2198
 
                          msg (D_PF_DROPPED, "PF: client -> addr[%s] packet dropped by TAP packet filter",
2199
 
                               mroute_addr_print_ex (&edest, MAPF_SHOW_ARP, &gc));
2200
 
                          c->c2.to_tun.len = 0;
2201
 
                        }
2202
 
#endif
2203
 
                    }
2204
 
                  else
2205
 
                    {
2206
 
                      msg (D_MULTI_DROPPED, "MULTI: bad source address from client [%s], packet dropped",
2207
 
                           mroute_addr_print (&src, &gc));
2208
 
                      c->c2.to_tun.len = 0;
2209
 
                    }
2210
 
                }
2211
 
              else
2212
 
                {
2213
 
                  c->c2.to_tun.len = 0;
2214
 
                }
2215
 
            }
2216
 
        }
2217
 
 
2218
 
      /* postprocess and set wakeup */
2219
 
      ret = multi_process_post (m, m->pending, mpp_flags);
2220
 
 
2221
 
      clear_prefix ();
2222
 
    }
2223
 
 
2224
 
  gc_free (&gc);
2225
 
  return ret;
2226
 
}
2227
 
 
2228
 
/*
2229
 
 * Process packets in the TUN/TAP interface -> TCP/UDP socket direction,
2230
 
 * i.e. server -> client direction.
2231
 
 */
2232
 
bool
2233
 
multi_process_incoming_tun (struct multi_context *m, const unsigned int mpp_flags)
2234
 
{
2235
 
  struct gc_arena gc = gc_new ();
2236
 
  bool ret = true;
2237
 
 
2238
 
  if (BLEN (&m->top.c2.buf) > 0)
2239
 
    {
2240
 
      unsigned int mroute_flags;
2241
 
      struct mroute_addr src, dest;
2242
 
      const int dev_type = TUNNEL_TYPE (m->top.c1.tuntap);
2243
 
 
2244
 
#ifdef ENABLE_PF
2245
 
      struct mroute_addr esrc, *e1, *e2;
2246
 
      if (dev_type == DEV_TYPE_TUN)
2247
 
        {
2248
 
          e1 = NULL;
2249
 
          e2 = &src;
2250
 
        }
2251
 
      else
2252
 
        {
2253
 
          e1 = e2 = &esrc;
2254
 
          mroute_addr_reset (&esrc);
2255
 
        }
2256
 
#endif
2257
 
 
2258
 
#ifdef MULTI_DEBUG_EVENT_LOOP
2259
 
      printf ("TUN -> TCP/UDP [%d]\n", BLEN (&m->top.c2.buf));
2260
 
#endif
2261
 
 
2262
 
      if (m->pending)
2263
 
        return true;
2264
 
 
2265
 
      /* 
2266
 
       * Route an incoming tun/tap packet to
2267
 
       * the appropriate multi_instance object.
2268
 
       */
2269
 
 
2270
 
      mroute_flags = mroute_extract_addr_from_packet (&src,
2271
 
                                                      &dest,
2272
 
#ifdef ENABLE_PF
2273
 
                                                      e1,
2274
 
#else
2275
 
                                                      NULL,
2276
 
#endif
2277
 
                                                      NULL,
2278
 
                                                      &m->top.c2.buf,
2279
 
                                                      dev_type);
2280
 
 
2281
 
      if (mroute_flags & MROUTE_EXTRACT_SUCCEEDED)
2282
 
        {
2283
 
          struct context *c;
2284
 
 
2285
 
          /* broadcast or multicast dest addr? */
2286
 
          if (mroute_flags & (MROUTE_EXTRACT_BCAST|MROUTE_EXTRACT_MCAST))
2287
 
            {
2288
 
              /* for now, treat multicast as broadcast */
2289
 
#ifdef ENABLE_PF
2290
 
              multi_bcast (m, &m->top.c2.buf, NULL, e2);
2291
 
#else
2292
 
              multi_bcast (m, &m->top.c2.buf, NULL, NULL);
2293
 
#endif
2294
 
            }
2295
 
          else
2296
 
            {
2297
 
              multi_set_pending (m, multi_get_instance_by_virtual_addr (m, &dest, dev_type == DEV_TYPE_TUN));
2298
 
 
2299
 
              if (m->pending)
2300
 
                {
2301
 
                  /* get instance context */
2302
 
                  c = &m->pending->context;
2303
 
                  
2304
 
                  set_prefix (m->pending);
2305
 
 
2306
 
#ifdef ENABLE_PF
2307
 
                  if (!pf_addr_test (c, e2, "tun_tap_src_addr"))
2308
 
                    {
2309
 
                      msg (D_PF_DROPPED, "PF: addr[%s] -> client packet dropped by packet filter",
2310
 
                           mroute_addr_print_ex (&src, MAPF_SHOW_ARP, &gc));
2311
 
                      buf_reset_len (&c->c2.buf);
2312
 
                    }
2313
 
                  else
2314
 
#endif
2315
 
                  {
2316
 
                    if (multi_output_queue_ready (m, m->pending))
2317
 
                      {
2318
 
                        /* transfer packet pointer from top-level context buffer to instance */
2319
 
                        c->c2.buf = m->top.c2.buf;
2320
 
                      }
2321
 
                    else
2322
 
                      {
2323
 
                        /* drop packet */
2324
 
                        msg (D_MULTI_DROPPED, "MULTI: packet dropped due to output saturation (multi_process_incoming_tun)");
2325
 
                        buf_reset_len (&c->c2.buf);
2326
 
                      }
2327
 
                  }
2328
 
              
2329
 
                  /* encrypt in instance context */
2330
 
                  process_incoming_tun (c);
2331
 
 
2332
 
                  /* postprocess and set wakeup */
2333
 
                  ret = multi_process_post (m, m->pending, mpp_flags);
2334
 
 
2335
 
                  clear_prefix ();
2336
 
                }
2337
 
            }
2338
 
        }
2339
 
    }
2340
 
  gc_free (&gc);
2341
 
  return ret;
2342
 
}
2343
 
 
2344
 
/*
2345
 
 * Process a possible client-to-client/bcast/mcast message in the
2346
 
 * queue.
2347
 
 */
2348
 
struct multi_instance *
2349
 
multi_get_queue (struct mbuf_set *ms)
2350
 
{
2351
 
  struct mbuf_item item;
2352
 
 
2353
 
  if (mbuf_extract_item (ms, &item)) /* cleartext IP packet */
2354
 
    {
2355
 
      unsigned int pipv4_flags = PIPV4_PASSTOS;
2356
 
 
2357
 
      set_prefix (item.instance);
2358
 
      item.instance->context.c2.buf = item.buffer->buf;
2359
 
      if (item.buffer->flags & MF_UNICAST) /* --mssfix doesn't make sense for broadcast or multicast */
2360
 
        pipv4_flags |= PIPV4_MSSFIX;
2361
 
      process_ipv4_header (&item.instance->context, pipv4_flags, &item.instance->context.c2.buf);
2362
 
      encrypt_sign (&item.instance->context, true);
2363
 
      mbuf_free_buf (item.buffer);
2364
 
 
2365
 
      dmsg (D_MULTI_DEBUG, "MULTI: C2C/MCAST/BCAST");
2366
 
 
2367
 
      clear_prefix ();
2368
 
      return item.instance;
2369
 
    }
2370
 
  else
2371
 
    {
2372
 
      return NULL;
2373
 
    }
2374
 
}
2375
 
 
2376
 
/*
2377
 
 * Called when an I/O wait times out.  Usually means that a particular
2378
 
 * client instance object needs timer-based service.
2379
 
 */
2380
 
bool
2381
 
multi_process_timeout (struct multi_context *m, const unsigned int mpp_flags)
2382
 
{
2383
 
  bool ret = true;
2384
 
 
2385
 
#ifdef MULTI_DEBUG_EVENT_LOOP
2386
 
  printf ("%s -> TIMEOUT\n", id(m->earliest_wakeup));
2387
 
#endif
2388
 
 
2389
 
  /* instance marked for wakeup? */
2390
 
  if (m->earliest_wakeup)
2391
 
    {
2392
 
      set_prefix (m->earliest_wakeup);
2393
 
      ret = multi_process_post (m, m->earliest_wakeup, mpp_flags);
2394
 
      m->earliest_wakeup = NULL;
2395
 
      clear_prefix ();
2396
 
    }
2397
 
  return ret;
2398
 
}
2399
 
 
2400
 
/*
2401
 
 * Drop a TUN/TAP outgoing packet..
2402
 
 */
2403
 
void
2404
 
multi_process_drop_outgoing_tun (struct multi_context *m, const unsigned int mpp_flags)
2405
 
{
2406
 
  struct multi_instance *mi = m->pending;
2407
 
 
2408
 
  ASSERT (mi);
2409
 
 
2410
 
  set_prefix (mi);
2411
 
 
2412
 
  msg (D_MULTI_ERRORS, "MULTI: Outgoing TUN queue full, dropped packet len=%d",
2413
 
       mi->context.c2.to_tun.len);
2414
 
 
2415
 
  buf_reset (&mi->context.c2.to_tun);
2416
 
 
2417
 
  multi_process_post (m, mi, mpp_flags);
2418
 
  clear_prefix ();
2419
 
}
2420
 
 
2421
 
/*
2422
 
 * Per-client route quota management
2423
 
 */
2424
 
 
2425
 
void
2426
 
route_quota_exceeded (const struct multi_context *m, const struct multi_instance *mi)
2427
 
{
2428
 
  struct gc_arena gc = gc_new ();
2429
 
  msg (D_ROUTE_QUOTA, "MULTI ROUTE: route quota (%d) exceeded for %s (see --max-routes-per-client option)",
2430
 
        mi->context.options.max_routes_per_client,
2431
 
        multi_instance_string (mi, false, &gc));
2432
 
  gc_free (&gc);
2433
 
}
2434
 
 
2435
 
#ifdef ENABLE_DEBUG
2436
 
/*
2437
 
 * Flood clients with random packets
2438
 
 */
2439
 
static void
2440
 
gremlin_flood_clients (struct multi_context *m)
2441
 
{
2442
 
  const int level = GREMLIN_PACKET_FLOOD_LEVEL (m->top.options.gremlin);
2443
 
  if (level)
2444
 
    {
2445
 
      struct gc_arena gc = gc_new ();
2446
 
      struct buffer buf = alloc_buf_gc (BUF_SIZE (&m->top.c2.frame), &gc);
2447
 
      struct packet_flood_parms parm = get_packet_flood_parms (level);
2448
 
      int i;
2449
 
 
2450
 
      ASSERT (buf_init (&buf, FRAME_HEADROOM (&m->top.c2.frame)));
2451
 
      parm.packet_size = min_int (parm.packet_size, MAX_RW_SIZE_TUN (&m->top.c2.frame));
2452
 
 
2453
 
      msg (D_GREMLIN, "GREMLIN_FLOOD_CLIENTS: flooding clients with %d packets of size %d",
2454
 
           parm.n_packets,
2455
 
           parm.packet_size);
2456
 
 
2457
 
      for (i = 0; i < parm.packet_size; ++i)
2458
 
        ASSERT (buf_write_u8 (&buf, get_random () & 0xFF));
2459
 
 
2460
 
      for (i = 0; i < parm.n_packets; ++i)
2461
 
        multi_bcast (m, &buf, NULL, NULL);
2462
 
 
2463
 
      gc_free (&gc);
2464
 
    }
2465
 
}
2466
 
#endif
2467
 
 
2468
 
/*
2469
 
 * Process timers in the top-level context
2470
 
 */
2471
 
void
2472
 
multi_process_per_second_timers_dowork (struct multi_context *m)
2473
 
{
2474
 
  /* possibly reap instances/routes in vhash */
2475
 
  multi_reap_process (m);
2476
 
 
2477
 
  /* possibly print to status log */
2478
 
  if (m->top.c1.status_output)
2479
 
    {
2480
 
      if (status_trigger (m->top.c1.status_output))
2481
 
        multi_print_status (m, m->top.c1.status_output, m->status_file_version);
2482
 
    }
2483
 
 
2484
 
  /* possibly flush ifconfig-pool file */
2485
 
  multi_ifconfig_pool_persist (m, false);
2486
 
 
2487
 
#ifdef ENABLE_DEBUG
2488
 
  gremlin_flood_clients (m);
2489
 
#endif
2490
 
}
2491
 
 
2492
 
void
2493
 
multi_top_init (struct multi_context *m, const struct context *top, const bool alloc_buffers)
2494
 
{
2495
 
  inherit_context_top (&m->top, top);
2496
 
  m->top.c2.buffers = NULL;
2497
 
  if (alloc_buffers)
2498
 
    m->top.c2.buffers = init_context_buffers (&top->c2.frame);
2499
 
}
2500
 
 
2501
 
void
2502
 
multi_top_free (struct multi_context *m)
2503
 
{
2504
 
  close_context (&m->top, -1, CC_GC_FREE);
2505
 
  free_context_buffers (m->top.c2.buffers);
2506
 
}
2507
 
 
2508
 
/*
2509
 
 * Return true if event loop should break,
2510
 
 * false if it should continue.
2511
 
 */
2512
 
bool
2513
 
multi_process_signal (struct multi_context *m)
2514
 
{
2515
 
  if (m->top.sig->signal_received == SIGUSR2)
2516
 
    {
2517
 
      struct status_output *so = status_open (NULL, 0, M_INFO, NULL, 0);
2518
 
      multi_print_status (m, so, m->status_file_version);
2519
 
      status_close (so);
2520
 
      m->top.sig->signal_received = 0;
2521
 
      return false;
2522
 
    }
2523
 
  return true;
2524
 
}
2525
 
 
2526
 
/*
2527
 
 * Called when an instance should be closed due to the
2528
 
 * reception of a soft signal.
2529
 
 */
2530
 
void
2531
 
multi_close_instance_on_signal (struct multi_context *m, struct multi_instance *mi)
2532
 
{
2533
 
  remap_signal (&mi->context);
2534
 
  set_prefix (mi);
2535
 
  print_signal (mi->context.sig, "client-instance", D_MULTI_LOW);
2536
 
  clear_prefix ();
2537
 
  multi_close_instance (m, mi, false);
2538
 
}
2539
 
 
2540
 
static void
2541
 
multi_signal_instance (struct multi_context *m, struct multi_instance *mi, const int sig)
2542
 
{
2543
 
  mi->context.sig->signal_received = sig;
2544
 
  multi_close_instance_on_signal (m, mi);
2545
 
}
2546
 
 
2547
 
/*
2548
 
 * Management subsystem callbacks
2549
 
 */
2550
 
 
2551
 
#ifdef ENABLE_MANAGEMENT
2552
 
 
2553
 
static void
2554
 
management_callback_status (void *arg, const int version, struct status_output *so)
2555
 
{
2556
 
  struct multi_context *m = (struct multi_context *) arg;
2557
 
 
2558
 
  if (!version)
2559
 
    multi_print_status (m, so, m->status_file_version);
2560
 
  else
2561
 
    multi_print_status (m, so, version);
2562
 
}
2563
 
 
2564
 
static int
2565
 
management_callback_n_clients (void *arg)
2566
 
{
2567
 
  struct multi_context *m = (struct multi_context *) arg;
2568
 
  return m->n_clients;
2569
 
}
2570
 
 
2571
 
static int
2572
 
management_callback_kill_by_cn (void *arg, const char *del_cn)
2573
 
{
2574
 
  struct multi_context *m = (struct multi_context *) arg;
2575
 
  struct hash_iterator hi;
2576
 
  struct hash_element *he;
2577
 
  int count = 0;
2578
 
 
2579
 
  hash_iterator_init (m->iter, &hi);
2580
 
  while ((he = hash_iterator_next (&hi)))
2581
 
    {
2582
 
      struct multi_instance *mi = (struct multi_instance *) he->value;
2583
 
      if (!mi->halt)
2584
 
        {
2585
 
          const char *cn = tls_common_name (mi->context.c2.tls_multi, false);
2586
 
          if (cn && !strcmp (cn, del_cn))
2587
 
            {
2588
 
              multi_signal_instance (m, mi, SIGTERM);
2589
 
              ++count;
2590
 
            }
2591
 
        }
2592
 
    }
2593
 
  hash_iterator_free (&hi);
2594
 
  return count;
2595
 
}
2596
 
 
2597
 
static int
2598
 
management_callback_kill_by_addr (void *arg, const in_addr_t addr, const int port)
2599
 
{
2600
 
  struct multi_context *m = (struct multi_context *) arg;
2601
 
  struct hash_iterator hi;
2602
 
  struct hash_element *he;
2603
 
  struct openvpn_sockaddr saddr;
2604
 
  struct mroute_addr maddr;
2605
 
  int count = 0;
2606
 
 
2607
 
  CLEAR (saddr);
2608
 
  saddr.addr.in4.sin_family = AF_INET;
2609
 
  saddr.addr.in4.sin_addr.s_addr = htonl (addr);
2610
 
  saddr.addr.in4.sin_port = htons (port);
2611
 
  if (mroute_extract_openvpn_sockaddr (&maddr, &saddr, true))
2612
 
    {
2613
 
      hash_iterator_init (m->iter, &hi);
2614
 
      while ((he = hash_iterator_next (&hi)))
2615
 
        {
2616
 
          struct multi_instance *mi = (struct multi_instance *) he->value;
2617
 
          if (!mi->halt && mroute_addr_equal (&maddr, &mi->real))
2618
 
            {
2619
 
              multi_signal_instance (m, mi, SIGTERM);
2620
 
              ++count;
2621
 
            }
2622
 
        }
2623
 
      hash_iterator_free (&hi);
2624
 
    }
2625
 
  return count;
2626
 
}
2627
 
 
2628
 
static void
2629
 
management_delete_event (void *arg, event_t event)
2630
 
{
2631
 
  struct multi_context *m = (struct multi_context *) arg;
2632
 
  if (m->mtcp)
2633
 
    multi_tcp_delete_event (m->mtcp, event);
2634
 
}
2635
 
 
2636
 
#endif
2637
 
 
2638
 
#ifdef MANAGEMENT_DEF_AUTH
2639
 
 
2640
 
static struct multi_instance *
2641
 
lookup_by_cid (struct multi_context *m, const unsigned long cid)
2642
 
{
2643
 
  if (m)
2644
 
    {
2645
 
      struct multi_instance *mi = (struct multi_instance *) hash_lookup (m->cid_hash, &cid);
2646
 
      if (mi && !mi->halt)
2647
 
        return mi;
2648
 
    }
2649
 
  return NULL;
2650
 
}
2651
 
 
2652
 
static bool
2653
 
management_kill_by_cid (void *arg, const unsigned long cid)
2654
 
{
2655
 
  struct multi_context *m = (struct multi_context *) arg;
2656
 
  struct multi_instance *mi = lookup_by_cid (m, cid);
2657
 
  if (mi)
2658
 
    {
2659
 
      send_restart (&mi->context); /* was: multi_signal_instance (m, mi, SIGTERM); */
2660
 
      return true;
2661
 
    }
2662
 
  else
2663
 
    return false;
2664
 
}
2665
 
 
2666
 
static bool
2667
 
management_client_auth (void *arg,
2668
 
                        const unsigned long cid,
2669
 
                        const unsigned int mda_key_id,
2670
 
                        const bool auth,
2671
 
                        const char *reason,
2672
 
                        const char *client_reason,
2673
 
                        struct buffer_list *cc_config) /* ownership transferred */
2674
 
{
2675
 
  struct multi_context *m = (struct multi_context *) arg;
2676
 
  struct multi_instance *mi = lookup_by_cid (m, cid);
2677
 
  bool cc_config_owned = true;
2678
 
  bool ret = false;
2679
 
 
2680
 
  if (mi)
2681
 
    {
2682
 
      ret = tls_authenticate_key (mi->context.c2.tls_multi, mda_key_id, auth, client_reason);
2683
 
      if (ret)
2684
 
        {
2685
 
          if (auth)
2686
 
            {
2687
 
              if (!mi->connection_established_flag)
2688
 
                {
2689
 
                  set_cc_config (mi, cc_config);
2690
 
                  cc_config_owned = false;
2691
 
                }
2692
 
            }
2693
 
          else
2694
 
            {
2695
 
              if (reason)
2696
 
                msg (D_MULTI_LOW, "MULTI: connection rejected: %s, CLI:%s", reason, np(client_reason));
2697
 
              if (mi->connection_established_flag)
2698
 
                {
2699
 
                  send_auth_failed (&mi->context, client_reason); /* mid-session reauth failed */
2700
 
                  multi_schedule_context_wakeup(m, mi);
2701
 
                }
2702
 
            }
2703
 
        }
2704
 
    }
2705
 
  if (cc_config_owned && cc_config)
2706
 
    buffer_list_free (cc_config);
2707
 
  return ret;
2708
 
}
2709
 
 
2710
 
static char *
2711
 
management_get_peer_info (void *arg, const unsigned long cid)
2712
 
{
2713
 
  struct multi_context *m = (struct multi_context *) arg;
2714
 
  struct multi_instance *mi = lookup_by_cid (m, cid);
2715
 
  char *ret = NULL;
2716
 
 
2717
 
  if (mi)
2718
 
      ret = tls_get_peer_info (mi->context.c2.tls_multi);
2719
 
 
2720
 
  return ret;
2721
 
}
2722
 
 
2723
 
#endif
2724
 
 
2725
 
#ifdef MANAGEMENT_PF
2726
 
static bool
2727
 
management_client_pf (void *arg,
2728
 
                      const unsigned long cid,
2729
 
                      struct buffer_list *pf_config) /* ownership transferred */
2730
 
{
2731
 
  struct multi_context *m = (struct multi_context *) arg;
2732
 
  struct multi_instance *mi = lookup_by_cid (m, cid);
2733
 
  bool ret = false;
2734
 
 
2735
 
  if (mi && pf_config)
2736
 
    ret = pf_load_from_buffer_list (&mi->context, pf_config);
2737
 
 
2738
 
  if (pf_config)
2739
 
    buffer_list_free (pf_config);
2740
 
  return ret;
2741
 
}
2742
 
#endif
2743
 
 
2744
 
void
2745
 
init_management_callback_multi (struct multi_context *m)
2746
 
{
2747
 
#ifdef ENABLE_MANAGEMENT
2748
 
  if (management)
2749
 
    {
2750
 
      struct management_callback cb;
2751
 
      CLEAR (cb);
2752
 
      cb.arg = m;
2753
 
      cb.flags = MCF_SERVER;
2754
 
      cb.status = management_callback_status;
2755
 
      cb.show_net = management_show_net_callback;
2756
 
      cb.kill_by_cn = management_callback_kill_by_cn;
2757
 
      cb.kill_by_addr = management_callback_kill_by_addr;
2758
 
      cb.delete_event = management_delete_event;
2759
 
      cb.n_clients = management_callback_n_clients;
2760
 
#ifdef MANAGEMENT_DEF_AUTH
2761
 
      cb.kill_by_cid = management_kill_by_cid;
2762
 
      cb.client_auth = management_client_auth;
2763
 
      cb.get_peer_info = management_get_peer_info;
2764
 
#endif
2765
 
#ifdef MANAGEMENT_PF
2766
 
      cb.client_pf = management_client_pf;
2767
 
#endif
2768
 
      management_set_callback (management, &cb);
2769
 
    }
2770
 
#endif
2771
 
}
2772
 
 
2773
 
void
2774
 
uninit_management_callback_multi (struct multi_context *m)
2775
 
{
2776
 
  uninit_management_callback ();
2777
 
}
2778
 
 
2779
 
/*
2780
 
 * Top level event loop.
2781
 
 */
2782
 
void
2783
 
tunnel_server (struct context *top)
2784
 
{
2785
 
  ASSERT (top->options.mode == MODE_SERVER);
2786
 
 
2787
 
#ifdef USE_PF_INET6
2788
 
  if (proto_is_dgram(top->options.ce.proto))
2789
 
    tunnel_server_udp(top);
2790
 
  else
2791
 
    tunnel_server_tcp(top);
2792
 
#else
2793
 
  switch (top->options.ce.proto)
2794
 
    {
2795
 
    case PROTO_UDPv4:
2796
 
      tunnel_server_udp (top);
2797
 
      break;
2798
 
    case PROTO_TCPv4_SERVER:
2799
 
      tunnel_server_tcp (top);
2800
 
      break;
2801
 
    default:
2802
 
      ASSERT (0);
2803
 
    }
2804
 
#endif
2805
 
}
2806
 
 
2807
 
#else
2808
 
static void dummy(void) {}
2809
 
#endif /* P2MP_SERVER */