big svn cleanup
[anytun.git] / src / openvpn / multi.c
blob22ea6776b54e302793d1973e456f00c8f2c9d37f
1 /*
2 * OpenVPN -- An application to securely tunnel IP networks
3 * over a single TCP/UDP port, with support for SSL/TLS-based
4 * session authentication and key exchange,
5 * packet encryption, packet authentication, and
6 * packet compression.
8 * Copyright (C) 2002-2005 OpenVPN Solutions LLC <info@openvpn.net>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2
12 * as published by the Free Software Foundation.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program (see the file COPYING included with this
21 * distribution); if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #ifdef WIN32
26 #include "config-win32.h"
27 #else
28 #include "config.h"
29 #endif
31 #include "syshead.h"
33 #if P2MP_SERVER
35 #include "multi.h"
36 #include "push.h"
37 #include "misc.h"
38 #include "otime.h"
39 #include "gremlin.h"
41 #include "memdbg.h"
43 #include "forward-inline.h"
45 /*#define MULTI_DEBUG_EVENT_LOOP*/
47 #ifdef MULTI_DEBUG_EVENT_LOOP
48 static const char *
49 id (struct multi_instance *mi)
51 if (mi)
52 return tls_common_name (mi->context.c2.tls_multi, false);
53 else
54 return "NULL";
56 #endif
58 static bool
59 learn_address_script (const struct multi_context *m,
60 const struct multi_instance *mi,
61 const char *op,
62 const struct mroute_addr *addr)
64 struct gc_arena gc = gc_new ();
65 struct env_set *es;
66 bool ret = true;
68 /* get environmental variable source */
69 if (mi && mi->context.c2.es)
70 es = mi->context.c2.es;
71 else
72 es = env_set_create (&gc);
74 if (plugin_defined (m->top.c1.plugins, OPENVPN_PLUGIN_LEARN_ADDRESS))
76 struct buffer cmd = alloc_buf_gc (256, &gc);
78 buf_printf (&cmd, "\"%s\" \"%s\"",
79 op,
80 mroute_addr_print (addr, &gc));
81 if (mi)
82 buf_printf (&cmd, " \"%s\"", tls_common_name (mi->context.c2.tls_multi, false));
84 if (plugin_call (m->top.c1.plugins, OPENVPN_PLUGIN_LEARN_ADDRESS, BSTR (&cmd), es))
86 msg (M_WARN, "WARNING: learn-address plugin call failed");
87 ret = false;
91 if (m->top.options.learn_address_script)
93 struct buffer cmd = alloc_buf_gc (256, &gc);
95 setenv_str (es, "script_type", "learn-address");
97 buf_printf (&cmd, "%s \"%s\" \"%s\"",
98 m->top.options.learn_address_script,
99 op,
100 mroute_addr_print (addr, &gc));
101 if (mi)
102 buf_printf (&cmd, " \"%s\"", tls_common_name (mi->context.c2.tls_multi, false));
104 if (!system_check (BSTR (&cmd), es, S_SCRIPT, "WARNING: learn-address command failed"))
105 ret = false;
108 gc_free (&gc);
109 return ret;
112 void
113 multi_ifconfig_pool_persist (struct multi_context *m, bool force)
115 /* write pool data to file */
116 if (m->ifconfig_pool
117 && m->top.c1.ifconfig_pool_persist
118 && (force || ifconfig_pool_write_trigger (m->top.c1.ifconfig_pool_persist)))
120 ifconfig_pool_write (m->top.c1.ifconfig_pool_persist, m->ifconfig_pool);
124 static void
125 multi_reap_range (const struct multi_context *m,
126 int start_bucket,
127 int end_bucket)
129 struct gc_arena gc = gc_new ();
130 struct hash_iterator hi;
131 struct hash_element *he;
133 if (start_bucket < 0)
135 start_bucket = 0;
136 end_bucket = hash_n_buckets (m->vhash);
139 dmsg (D_MULTI_DEBUG, "MULTI: REAP range %d -> %d", start_bucket, end_bucket);
140 hash_iterator_init_range (m->vhash, &hi, true, start_bucket, end_bucket);
141 while ((he = hash_iterator_next (&hi)) != NULL)
143 struct multi_route *r = (struct multi_route *) he->value;
144 if (!multi_route_defined (m, r))
146 dmsg (D_MULTI_DEBUG, "MULTI: REAP DEL %s",
147 mroute_addr_print (&r->addr, &gc));
148 learn_address_script (m, NULL, "delete", &r->addr);
149 multi_route_del (r);
150 hash_iterator_delete_element (&hi);
153 hash_iterator_free (&hi);
154 gc_free (&gc);
157 static void
158 multi_reap_all (const struct multi_context *m)
160 multi_reap_range (m, -1, 0);
163 static struct multi_reap *
164 multi_reap_new (int buckets_per_pass)
166 struct multi_reap *mr;
167 ALLOC_OBJ (mr, struct multi_reap);
168 mr->bucket_base = 0;
169 mr->buckets_per_pass = buckets_per_pass;
170 mr->last_call = now;
171 return mr;
174 void
175 multi_reap_process_dowork (const struct multi_context *m)
177 struct multi_reap *mr = m->reaper;
178 if (mr->bucket_base >= hash_n_buckets (m->vhash))
179 mr->bucket_base = 0;
180 multi_reap_range (m, mr->bucket_base, mr->bucket_base + mr->buckets_per_pass);
181 mr->bucket_base += mr->buckets_per_pass;
182 mr->last_call = now;
185 static void
186 multi_reap_free (struct multi_reap *mr)
188 free (mr);
192 * How many buckets in vhash to reap per pass.
194 static int
195 reap_buckets_per_pass (int n_buckets)
197 return constrain_int (n_buckets / REAP_DIVISOR, REAP_MIN, REAP_MAX);
201 * Main initialization function, init multi_context object.
203 void
204 multi_init (struct multi_context *m, struct context *t, bool tcp_mode, int thread_mode)
206 int dev = DEV_TYPE_UNDEF;
208 msg (D_MULTI_LOW, "MULTI: multi_init called, r=%d v=%d",
209 t->options.real_hash_size,
210 t->options.virtual_hash_size);
213 * Get tun/tap/null device type
215 dev = dev_type_enum (t->options.dev, t->options.dev_type);
218 * Init our multi_context object.
220 CLEAR (*m);
222 m->thread_mode = thread_mode;
225 * Real address hash table (source port number is
226 * considered to be part of the address). Used
227 * to determine which client sent an incoming packet
228 * which is seen on the TCP/UDP socket.
230 m->hash = hash_init (t->options.real_hash_size,
231 mroute_addr_hash_function,
232 mroute_addr_compare_function);
235 * Virtual address hash table. Used to determine
236 * which client to route a packet to.
238 m->vhash = hash_init (t->options.virtual_hash_size,
239 mroute_addr_hash_function,
240 mroute_addr_compare_function);
243 * This hash table is a clone of m->hash but with a
244 * bucket size of one so that it can be used
245 * for fast iteration through the list.
247 m->iter = hash_init (1,
248 mroute_addr_hash_function,
249 mroute_addr_compare_function);
252 * This is our scheduler, for time-based wakeup
253 * events.
255 m->schedule = schedule_init ();
258 * Limit frequency of incoming connections to control
259 * DoS.
261 m->new_connection_limiter = frequency_limit_init (t->options.cf_max,
262 t->options.cf_per);
265 * Allocate broadcast/multicast buffer list
267 m->mbuf = mbuf_init (t->options.n_bcast_buf);
270 * Different status file format options are available
272 m->status_file_version = t->options.status_file_version;
275 * Possibly allocate an ifconfig pool, do it
276 * differently based on whether a tun or tap style
277 * tunnel.
279 if (t->options.ifconfig_pool_defined)
281 if (dev == DEV_TYPE_TAP || t->options.ifconfig_pool_linear)
283 m->ifconfig_pool = ifconfig_pool_init (IFCONFIG_POOL_INDIV,
284 t->options.ifconfig_pool_start,
285 t->options.ifconfig_pool_end,
286 t->options.duplicate_cn);
288 else if (dev == DEV_TYPE_TUN)
290 m->ifconfig_pool = ifconfig_pool_init (IFCONFIG_POOL_30NET,
291 t->options.ifconfig_pool_start,
292 t->options.ifconfig_pool_end,
293 t->options.duplicate_cn);
295 else
297 ASSERT (0);
300 /* reload pool data from file */
301 if (t->c1.ifconfig_pool_persist)
302 ifconfig_pool_read (t->c1.ifconfig_pool_persist, m->ifconfig_pool);
306 * Help us keep track of routing table.
308 m->route_helper = mroute_helper_init (MULTI_CACHE_ROUTE_TTL);
311 * Initialize route and instance reaper.
313 m->reaper = multi_reap_new (reap_buckets_per_pass (t->options.virtual_hash_size));
316 * Get local ifconfig address
318 CLEAR (m->local);
319 ASSERT (t->c1.tuntap);
320 mroute_extract_in_addr_t (&m->local, t->c1.tuntap->local);
323 * Per-client limits
325 m->max_clients = t->options.max_clients;
328 * Initialize multi-socket TCP I/O wait object
330 if (tcp_mode)
331 m->mtcp = multi_tcp_init (t->options.max_clients, &m->max_clients);
332 m->tcp_queue_limit = t->options.tcp_queue_limit;
335 * Allow client <-> client communication, without going through
336 * tun/tap interface and network stack?
338 m->enable_c2c = t->options.enable_c2c;
341 const char *
342 multi_instance_string (const struct multi_instance *mi, bool null, struct gc_arena *gc)
344 if (mi)
346 struct buffer out = alloc_buf_gc (256, gc);
347 const char *cn = tls_common_name (mi->context.c2.tls_multi, true);
349 if (cn)
350 buf_printf (&out, "%s/", cn);
351 buf_printf (&out, "%s", mroute_addr_print (&mi->real, gc));
352 return BSTR (&out);
354 else if (null)
355 return NULL;
356 else
357 return "UNDEF";
360 void
361 generate_prefix (struct multi_instance *mi)
363 mi->msg_prefix = multi_instance_string (mi, true, &mi->gc);
364 set_prefix (mi);
367 void
368 ungenerate_prefix (struct multi_instance *mi)
370 mi->msg_prefix = NULL;
371 set_prefix (mi);
375 * Tell the route helper about deleted iroutes so
376 * that it can update its mask of currently used
377 * CIDR netlengths.
379 static void
380 multi_del_iroutes (struct multi_context *m,
381 struct multi_instance *mi)
383 const struct iroute *ir;
384 if (TUNNEL_TYPE (mi->context.c1.tuntap) == DEV_TYPE_TUN)
386 for (ir = mi->context.options.iroutes; ir != NULL; ir = ir->next)
387 mroute_helper_del_iroute (m->route_helper, ir);
391 static void
392 multi_client_disconnect_setenv (struct multi_context *m,
393 struct multi_instance *mi)
395 /* setenv client real IP address */
396 setenv_trusted (mi->context.c2.es, get_link_socket_info (&mi->context));
398 /* setenv stats */
399 setenv_counter (mi->context.c2.es, "bytes_received", mi->context.c2.link_read_bytes);
400 setenv_counter (mi->context.c2.es, "bytes_sent", mi->context.c2.link_write_bytes);
404 static void
405 multi_client_disconnect_script (struct multi_context *m,
406 struct multi_instance *mi)
408 if ((mi->context.c2.context_auth == CAS_SUCCEEDED && mi->connection_established_flag)
409 || mi->context.c2.context_auth == CAS_PARTIAL)
411 multi_client_disconnect_setenv (m, mi);
413 if (plugin_defined (m->top.c1.plugins, OPENVPN_PLUGIN_CLIENT_DISCONNECT))
415 if (plugin_call (m->top.c1.plugins, OPENVPN_PLUGIN_CLIENT_DISCONNECT, NULL, mi->context.c2.es))
416 msg (M_WARN, "WARNING: client-disconnect plugin call failed");
419 if (mi->context.options.client_disconnect_script)
421 struct gc_arena gc = gc_new ();
422 struct buffer cmd = alloc_buf_gc (256, &gc);
424 setenv_str (mi->context.c2.es, "script_type", "client-disconnect");
426 buf_printf (&cmd, "%s", mi->context.options.client_disconnect_script);
428 system_check (BSTR (&cmd), mi->context.c2.es, S_SCRIPT, "client-disconnect command failed");
430 gc_free (&gc);
435 void
436 multi_close_instance (struct multi_context *m,
437 struct multi_instance *mi,
438 bool shutdown)
440 perf_push (PERF_MULTI_CLOSE_INSTANCE);
442 ASSERT (!mi->halt);
443 mi->halt = true;
445 dmsg (D_MULTI_DEBUG, "MULTI: multi_close_instance called");
447 /* prevent dangling pointers */
448 if (m->pending == mi)
449 multi_set_pending (m, NULL);
450 if (m->earliest_wakeup == mi)
451 m->earliest_wakeup = NULL;
453 if (!shutdown)
455 if (mi->did_real_hash)
457 ASSERT (hash_remove (m->hash, &mi->real));
459 if (mi->did_iter)
461 ASSERT (hash_remove (m->iter, &mi->real));
464 schedule_remove_entry (m->schedule, (struct schedule_entry *) mi);
466 ifconfig_pool_release (m->ifconfig_pool, mi->vaddr_handle, false);
468 if (mi->did_iroutes)
470 multi_del_iroutes (m, mi);
471 mi->did_iroutes = false;
474 if (m->mtcp)
475 multi_tcp_dereference_instance (m->mtcp, mi);
477 mbuf_dereference_instance (m->mbuf, mi);
480 multi_client_disconnect_script (m, mi);
482 if (mi->did_open_context)
483 close_context (&mi->context, SIGTERM, CC_GC_FREE);
485 multi_tcp_instance_specific_free (mi);
487 ungenerate_prefix (mi);
490 * Don't actually delete the instance memory allocation yet,
491 * because virtual routes may still point to it. Let the
492 * vhash reaper deal with it.
494 multi_instance_dec_refcount (mi);
496 perf_pop ();
500 * Called on shutdown or restart.
502 void
503 multi_uninit (struct multi_context *m)
505 if (m->thread_mode & MC_WORK_THREAD)
507 multi_top_free (m);
508 m->thread_mode = MC_UNDEF;
510 else if (m->thread_mode)
512 if (m->hash)
514 struct hash_iterator hi;
515 struct hash_element *he;
517 hash_iterator_init (m->iter, &hi, true);
518 while ((he = hash_iterator_next (&hi)))
520 struct multi_instance *mi = (struct multi_instance *) he->value;
521 mi->did_iter = false;
522 multi_close_instance (m, mi, true);
524 hash_iterator_free (&hi);
526 multi_reap_all (m);
528 hash_free (m->hash);
529 hash_free (m->vhash);
530 hash_free (m->iter);
531 m->hash = NULL;
533 schedule_free (m->schedule);
534 mbuf_free (m->mbuf);
535 ifconfig_pool_free (m->ifconfig_pool);
536 frequency_limit_free (m->new_connection_limiter);
537 multi_reap_free (m->reaper);
538 mroute_helper_free (m->route_helper);
539 multi_tcp_free (m->mtcp);
540 m->thread_mode = MC_UNDEF;
546 * Create a client instance object for a newly connected client.
548 struct multi_instance *
549 multi_create_instance (struct multi_context *m, const struct mroute_addr *real)
551 struct gc_arena gc = gc_new ();
552 struct multi_instance *mi;
554 perf_push (PERF_MULTI_CREATE_INSTANCE);
556 msg (D_MULTI_LOW, "MULTI: multi_create_instance called");
558 ALLOC_OBJ_CLEAR (mi, struct multi_instance);
560 mutex_init (&mi->mutex);
561 mi->gc = gc_new ();
562 multi_instance_inc_refcount (mi);
563 mi->vaddr_handle = -1;
564 mi->created = now;
565 mroute_addr_init (&mi->real);
567 if (real)
569 mi->real = *real;
570 generate_prefix (mi);
573 mi->did_open_context = true;
574 inherit_context_child (&mi->context, &m->top);
575 if (IS_SIG (&mi->context))
576 goto err;
578 mi->context.c2.context_auth = CAS_PENDING;
580 if (hash_n_elements (m->hash) >= m->max_clients)
582 msg (D_MULTI_ERRORS, "MULTI: new incoming connection would exceed maximum number of clients (%d)", m->max_clients);
583 goto err;
586 if (!real) /* TCP mode? */
588 if (!multi_tcp_instance_specific_init (m, mi))
589 goto err;
590 generate_prefix (mi);
593 if (!hash_add (m->iter, &mi->real, mi, false))
595 msg (D_MULTI_LOW, "MULTI: unable to add real address [%s] to iterator hash table",
596 mroute_addr_print (&mi->real, &gc));
597 goto err;
599 mi->did_iter = true;
601 mi->context.c2.push_reply_deferred = true;
603 if (!multi_process_post (m, mi, MPP_PRE_SELECT))
605 msg (D_MULTI_ERRORS, "MULTI: signal occurred during client instance initialization");
606 goto err;
609 perf_pop ();
610 gc_free (&gc);
611 return mi;
613 err:
614 multi_close_instance (m, mi, false);
615 perf_pop ();
616 gc_free (&gc);
617 return NULL;
621 * Dump tables -- triggered by SIGUSR2.
622 * If status file is defined, write to file.
623 * If status file is NULL, write to syslog.
625 void
626 multi_print_status (struct multi_context *m, struct status_output *so, const int version)
628 if (m->hash)
630 struct gc_arena gc_top = gc_new ();
631 struct hash_iterator hi;
632 const struct hash_element *he;
634 status_reset (so);
636 if (version == 1) /* WAS: m->status_file_version */
639 * Status file version 1
641 status_printf (so, PACKAGE_NAME " CLIENT LIST");
642 status_printf (so, "Updated,%s", time_string (0, 0, false, &gc_top));
643 status_printf (so, "Common Name,Real Address,Bytes Received,Bytes Sent,Connected Since");
644 hash_iterator_init (m->hash, &hi, true);
645 while ((he = hash_iterator_next (&hi)))
647 struct gc_arena gc = gc_new ();
648 const struct multi_instance *mi = (struct multi_instance *) he->value;
650 if (!mi->halt)
652 status_printf (so, "%s,%s," counter_format "," counter_format ",%s",
653 tls_common_name (mi->context.c2.tls_multi, false),
654 mroute_addr_print (&mi->real, &gc),
655 mi->context.c2.link_read_bytes,
656 mi->context.c2.link_write_bytes,
657 time_string (mi->created, 0, false, &gc));
659 gc_free (&gc);
661 hash_iterator_free (&hi);
663 status_printf (so, "ROUTING TABLE");
664 status_printf (so, "Virtual Address,Common Name,Real Address,Last Ref");
665 hash_iterator_init (m->vhash, &hi, true);
666 while ((he = hash_iterator_next (&hi)))
668 struct gc_arena gc = gc_new ();
669 const struct multi_route *route = (struct multi_route *) he->value;
671 if (multi_route_defined (m, route))
673 const struct multi_instance *mi = route->instance;
674 const struct mroute_addr *ma = &route->addr;
675 char flags[2] = {0, 0};
677 if (route->flags & MULTI_ROUTE_CACHE)
678 flags[0] = 'C';
679 status_printf (so, "%s%s,%s,%s,%s",
680 mroute_addr_print (ma, &gc),
681 flags,
682 tls_common_name (mi->context.c2.tls_multi, false),
683 mroute_addr_print (&mi->real, &gc),
684 time_string (route->last_reference, 0, false, &gc));
686 gc_free (&gc);
688 hash_iterator_free (&hi);
690 status_printf (so, "GLOBAL STATS");
691 if (m->mbuf)
692 status_printf (so, "Max bcast/mcast queue length,%d",
693 mbuf_maximum_queued (m->mbuf));
695 status_printf (so, "END");
697 else if (version == 2)
700 * Status file version 2
702 status_printf (so, "TITLE,%s", title_string);
703 status_printf (so, "TIME,%s,%u", time_string (now, 0, false, &gc_top), (unsigned int)now);
704 status_printf (so, "HEADER,CLIENT_LIST,Common Name,Real Address,Virtual Address,Bytes Received,Bytes Sent,Connected Since,Connected Since (time_t)");
705 hash_iterator_init (m->hash, &hi, true);
706 while ((he = hash_iterator_next (&hi)))
708 struct gc_arena gc = gc_new ();
709 const struct multi_instance *mi = (struct multi_instance *) he->value;
711 if (!mi->halt)
713 status_printf (so, "CLIENT_LIST,%s,%s,%s," counter_format "," counter_format ",%s,%u",
714 tls_common_name (mi->context.c2.tls_multi, false),
715 mroute_addr_print (&mi->real, &gc),
716 print_in_addr_t (mi->reporting_addr, IA_EMPTY_IF_UNDEF, &gc),
717 mi->context.c2.link_read_bytes,
718 mi->context.c2.link_write_bytes,
719 time_string (mi->created, 0, false, &gc),
720 (unsigned int)mi->created);
722 gc_free (&gc);
724 hash_iterator_free (&hi);
726 status_printf (so, "HEADER,ROUTING_TABLE,Virtual Address,Common Name,Real Address,Last Ref,Last Ref (time_t)");
727 hash_iterator_init (m->vhash, &hi, true);
728 while ((he = hash_iterator_next (&hi)))
730 struct gc_arena gc = gc_new ();
731 const struct multi_route *route = (struct multi_route *) he->value;
733 if (multi_route_defined (m, route))
735 const struct multi_instance *mi = route->instance;
736 const struct mroute_addr *ma = &route->addr;
737 char flags[2] = {0, 0};
739 if (route->flags & MULTI_ROUTE_CACHE)
740 flags[0] = 'C';
741 status_printf (so, "ROUTING_TABLE,%s%s,%s,%s,%s,%u",
742 mroute_addr_print (ma, &gc),
743 flags,
744 tls_common_name (mi->context.c2.tls_multi, false),
745 mroute_addr_print (&mi->real, &gc),
746 time_string (route->last_reference, 0, false, &gc),
747 (unsigned int)route->last_reference);
749 gc_free (&gc);
751 hash_iterator_free (&hi);
753 if (m->mbuf)
754 status_printf (so, "GLOBAL_STATS,Max bcast/mcast queue length,%d",
755 mbuf_maximum_queued (m->mbuf));
757 status_printf (so, "END");
759 else
761 status_printf (so, "ERROR: bad status format version number");
763 status_flush (so);
764 gc_free (&gc_top);
769 * Learn a virtual address or route.
770 * The learn will fail if the learn address
771 * script/plugin fails. In this case the
772 * return value may be != mi.
773 * Return the instance which owns this route,
774 * or NULL if none.
776 static struct multi_instance *
777 multi_learn_addr (struct multi_context *m,
778 struct multi_instance *mi,
779 const struct mroute_addr *addr,
780 const unsigned int flags)
782 struct hash_element *he;
783 const uint32_t hv = hash_value (m->vhash, addr);
784 struct hash_bucket *bucket = hash_bucket (m->vhash, hv);
785 struct multi_route *oldroute = NULL;
786 struct multi_instance *owner = NULL;
788 hash_bucket_lock (bucket);
790 /* if route currently exists, get the instance which owns it */
791 he = hash_lookup_fast (m->vhash, bucket, addr, hv);
792 if (he)
793 oldroute = (struct multi_route *) he->value;
794 if (oldroute && multi_route_defined (m, oldroute))
795 owner = oldroute->instance;
797 /* do we need to add address to hash table? */
798 if ((!owner || owner != mi)
799 && mroute_learnable_address (addr)
800 && !mroute_addr_equal (addr, &m->local))
802 struct gc_arena gc = gc_new ();
803 struct multi_route *newroute;
804 bool learn_succeeded = false;
806 ALLOC_OBJ (newroute, struct multi_route);
807 newroute->addr = *addr;
808 newroute->instance = mi;
809 newroute->flags = flags;
810 newroute->last_reference = now;
811 newroute->cache_generation = 0;
813 /* The cache is invalidated when cache_generation is incremented */
814 if (flags & MULTI_ROUTE_CACHE)
815 newroute->cache_generation = m->route_helper->cache_generation;
817 if (oldroute) /* route already exists? */
819 if (route_quota_test (m, mi) && learn_address_script (m, mi, "update", &newroute->addr))
821 learn_succeeded = true;
822 owner = mi;
823 multi_instance_inc_refcount (mi);
824 route_quota_inc (mi);
826 /* delete old route */
827 multi_route_del (oldroute);
829 /* modify hash table entry, replacing old route */
830 he->key = &newroute->addr;
831 he->value = newroute;
834 else
836 if (route_quota_test (m, mi) && learn_address_script (m, mi, "add", &newroute->addr))
838 learn_succeeded = true;
839 owner = mi;
840 multi_instance_inc_refcount (mi);
841 route_quota_inc (mi);
843 /* add new route */
844 hash_add_fast (m->vhash, bucket, &newroute->addr, hv, newroute);
848 msg (D_MULTI_LOW, "MULTI: Learn%s: %s -> %s",
849 learn_succeeded ? "" : " FAILED",
850 mroute_addr_print (&newroute->addr, &gc),
851 multi_instance_string (mi, false, &gc));
853 if (!learn_succeeded)
854 free (newroute);
856 gc_free (&gc);
859 hash_bucket_unlock (bucket);
860 return owner;
864 * Get client instance based on virtual address.
866 static struct multi_instance *
867 multi_get_instance_by_virtual_addr (struct multi_context *m,
868 const struct mroute_addr *addr,
869 bool cidr_routing)
871 struct multi_route *route;
872 struct multi_instance *ret = NULL;
874 /* check for local address */
875 if (mroute_addr_equal (addr, &m->local))
876 return NULL;
878 route = (struct multi_route *) hash_lookup (m->vhash, addr);
880 /* does host route (possible cached) exist? */
881 if (route && multi_route_defined (m, route))
883 struct multi_instance *mi = route->instance;
884 route->last_reference = now;
885 ret = mi;
887 else if (cidr_routing) /* do we need to regenerate a host route cache entry? */
889 struct mroute_helper *rh = m->route_helper;
890 struct mroute_addr tryaddr;
891 int i;
893 mroute_helper_lock (rh);
895 /* cycle through each CIDR length */
896 for (i = 0; i < rh->n_net_len; ++i)
898 tryaddr = *addr;
899 tryaddr.type |= MR_WITH_NETBITS;
900 tryaddr.netbits = rh->net_len[i];
901 mroute_addr_mask_host_bits (&tryaddr);
903 /* look up a possible route with netbits netmask */
904 route = (struct multi_route *) hash_lookup (m->vhash, &tryaddr);
906 if (route && multi_route_defined (m, route))
908 /* found an applicable route, cache host route */
909 struct multi_instance *mi = route->instance;
910 multi_learn_addr (m, mi, addr, MULTI_ROUTE_CACHE|MULTI_ROUTE_AGEABLE);
911 ret = mi;
912 break;
916 mroute_helper_unlock (rh);
919 #ifdef ENABLE_DEBUG
920 if (check_debug_level (D_MULTI_DEBUG))
922 struct gc_arena gc = gc_new ();
923 const char *addr_text = mroute_addr_print (addr, &gc);
924 if (ret)
926 dmsg (D_MULTI_DEBUG, "GET INST BY VIRT: %s -> %s via %s",
927 addr_text,
928 multi_instance_string (ret, false, &gc),
929 mroute_addr_print (&route->addr, &gc));
931 else
933 dmsg (D_MULTI_DEBUG, "GET INST BY VIRT: %s [failed]",
934 addr_text);
936 gc_free (&gc);
938 #endif
940 ASSERT (!(ret && ret->halt));
941 return ret;
945 * Helper function to multi_learn_addr().
947 static struct multi_instance *
948 multi_learn_in_addr_t (struct multi_context *m,
949 struct multi_instance *mi,
950 in_addr_t a,
951 int netbits) /* -1 if host route, otherwise # of network bits in address */
953 struct sockaddr_in remote_si;
954 struct mroute_addr addr;
956 CLEAR (remote_si);
957 remote_si.sin_family = AF_INET;
958 remote_si.sin_addr.s_addr = htonl (a);
959 ASSERT (mroute_extract_sockaddr_in (&addr, &remote_si, false));
961 if (netbits >= 0)
963 addr.type |= MR_WITH_NETBITS;
964 addr.netbits = (uint8_t) netbits;
966 return multi_learn_addr (m, mi, &addr, 0);
970 * A new client has connected, add routes (server -> client)
971 * to internal routing table.
973 static void
974 multi_add_iroutes (struct multi_context *m,
975 struct multi_instance *mi)
977 struct gc_arena gc = gc_new ();
978 const struct iroute *ir;
979 if (TUNNEL_TYPE (mi->context.c1.tuntap) == DEV_TYPE_TUN)
981 mi->did_iroutes = true;
982 for (ir = mi->context.options.iroutes; ir != NULL; ir = ir->next)
984 if (ir->netbits >= 0)
985 msg (D_MULTI_LOW, "MULTI: internal route %s/%d -> %s",
986 print_in_addr_t (ir->network, 0, &gc),
987 ir->netbits,
988 multi_instance_string (mi, false, &gc));
989 else
990 msg (D_MULTI_LOW, "MULTI: internal route %s -> %s",
991 print_in_addr_t (ir->network, 0, &gc),
992 multi_instance_string (mi, false, &gc));
994 mroute_helper_add_iroute (m->route_helper, ir);
996 multi_learn_in_addr_t (m, mi, ir->network, ir->netbits);
999 gc_free (&gc);
1003 * Given an instance (new_mi), delete all other instances which use the
1004 * same common name.
1006 static void
1007 multi_delete_dup (struct multi_context *m, struct multi_instance *new_mi)
1009 if (new_mi)
1011 const char *new_cn = tls_common_name (new_mi->context.c2.tls_multi, true);
1012 if (new_cn)
1014 struct hash_iterator hi;
1015 struct hash_element *he;
1016 int count = 0;
1018 hash_iterator_init (m->iter, &hi, true);
1019 while ((he = hash_iterator_next (&hi)))
1021 struct multi_instance *mi = (struct multi_instance *) he->value;
1022 if (mi != new_mi && !mi->halt)
1024 const char *cn = tls_common_name (mi->context.c2.tls_multi, true);
1025 if (cn && !strcmp (cn, new_cn))
1027 mi->did_iter = false;
1028 multi_close_instance (m, mi, false);
1029 hash_iterator_delete_element (&hi);
1030 ++count;
1034 hash_iterator_free (&hi);
1036 if (count)
1037 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);
1043 * Select a virtual address for a new client instance.
1044 * Use an --ifconfig-push directive, if given (static IP).
1045 * Otherwise use an --ifconfig-pool address (dynamic IP).
1047 static void
1048 multi_select_virtual_addr (struct multi_context *m, struct multi_instance *mi)
1050 struct gc_arena gc = gc_new ();
1053 * If ifconfig addresses were set by dynamic config file,
1054 * release pool addresses, otherwise keep them.
1056 if (mi->context.options.push_ifconfig_defined)
1058 /* ifconfig addresses were set statically,
1059 release dynamic allocation */
1060 if (mi->vaddr_handle >= 0)
1062 ifconfig_pool_release (m->ifconfig_pool, mi->vaddr_handle, true);
1063 mi->vaddr_handle = -1;
1066 mi->context.c2.push_ifconfig_defined = true;
1067 mi->context.c2.push_ifconfig_local = mi->context.options.push_ifconfig_local;
1068 mi->context.c2.push_ifconfig_remote_netmask = mi->context.options.push_ifconfig_remote_netmask;
1070 else if (m->ifconfig_pool && mi->vaddr_handle < 0) /* otherwise, choose a pool address */
1072 in_addr_t local=0, remote=0;
1073 const char *cn = NULL;
1075 if (!mi->context.options.duplicate_cn)
1076 cn = tls_common_name (mi->context.c2.tls_multi, true);
1078 mi->vaddr_handle = ifconfig_pool_acquire (m->ifconfig_pool, &local, &remote, cn);
1079 if (mi->vaddr_handle >= 0)
1081 /* use pool ifconfig address(es) */
1082 mi->context.c2.push_ifconfig_local = remote;
1083 if (TUNNEL_TYPE (mi->context.c1.tuntap) == DEV_TYPE_TUN)
1085 if (mi->context.options.ifconfig_pool_linear)
1086 mi->context.c2.push_ifconfig_remote_netmask = mi->context.c1.tuntap->local;
1087 else
1088 mi->context.c2.push_ifconfig_remote_netmask = local;
1089 mi->context.c2.push_ifconfig_defined = true;
1091 else if (TUNNEL_TYPE (mi->context.c1.tuntap) == DEV_TYPE_TAP)
1093 mi->context.c2.push_ifconfig_remote_netmask = mi->context.options.ifconfig_pool_netmask;
1094 if (!mi->context.c2.push_ifconfig_remote_netmask)
1095 mi->context.c2.push_ifconfig_remote_netmask = mi->context.c1.tuntap->remote_netmask;
1096 if (mi->context.c2.push_ifconfig_remote_netmask)
1097 mi->context.c2.push_ifconfig_defined = true;
1098 else
1099 msg (D_MULTI_ERRORS, "MULTI: no --ifconfig-pool netmask parameter is available to push to %s",
1100 multi_instance_string (mi, false, &gc));
1103 else
1105 msg (D_MULTI_ERRORS, "MULTI: no free --ifconfig-pool addresses are available");
1108 gc_free (&gc);
1112 * Set virtual address environmental variables.
1114 static void
1115 multi_set_virtual_addr_env (struct multi_context *m, struct multi_instance *mi)
1117 setenv_del (mi->context.c2.es, "ifconfig_pool_local_ip");
1118 setenv_del (mi->context.c2.es, "ifconfig_pool_remote_ip");
1119 setenv_del (mi->context.c2.es, "ifconfig_pool_netmask");
1121 if (mi->context.c2.push_ifconfig_defined)
1123 setenv_in_addr_t (mi->context.c2.es,
1124 "ifconfig_pool_remote_ip",
1125 mi->context.c2.push_ifconfig_local,
1126 SA_SET_IF_NONZERO);
1128 if (TUNNEL_TYPE (mi->context.c1.tuntap) == DEV_TYPE_TUN)
1130 setenv_in_addr_t (mi->context.c2.es,
1131 "ifconfig_pool_local_ip",
1132 mi->context.c2.push_ifconfig_remote_netmask,
1133 SA_SET_IF_NONZERO);
1135 else if (TUNNEL_TYPE (mi->context.c1.tuntap) == DEV_TYPE_TAP)
1137 setenv_in_addr_t (mi->context.c2.es,
1138 "ifconfig_pool_netmask",
1139 mi->context.c2.push_ifconfig_remote_netmask,
1140 SA_SET_IF_NONZERO);
1146 * Called after client-connect script or plug-in is called
1148 static void
1149 multi_client_connect_post (struct multi_context *m,
1150 struct multi_instance *mi,
1151 const char *dc_file,
1152 unsigned int option_permissions_mask,
1153 unsigned int *option_types_found)
1155 /* Did script generate a dynamic config file? */
1156 if (test_file (dc_file))
1158 options_server_import (&mi->context.options,
1159 dc_file,
1160 D_IMPORT_ERRORS|M_OPTERR,
1161 option_permissions_mask,
1162 option_types_found,
1163 mi->context.c2.es);
1165 if (!delete_file (dc_file))
1166 msg (D_MULTI_ERRORS, "MULTI: problem deleting temporary file: %s",
1167 dc_file);
1170 * If the --client-connect script generates a config file
1171 * with an --ifconfig-push directive, it will override any
1172 * --ifconfig-push directive from the --client-config-dir
1173 * directory or any --ifconfig-pool dynamic address.
1175 multi_select_virtual_addr (m, mi);
1176 multi_set_virtual_addr_env (m, mi);
1181 * Called as soon as the SSL/TLS connection authenticates.
1183 * Instance-specific directives to be processed:
1185 * iroute start-ip end-ip
1186 * ifconfig-push local remote-netmask
1187 * push
1189 static void
1190 multi_connection_established (struct multi_context *m, struct multi_instance *mi)
1192 if (tls_authenticated (mi->context.c2.tls_multi))
1194 struct gc_arena gc = gc_new ();
1195 unsigned int option_types_found = 0;
1196 const unsigned int option_permissions_mask = OPT_P_INSTANCE|OPT_P_INHERIT|OPT_P_PUSH|OPT_P_TIMER|OPT_P_CONFIG|OPT_P_ECHO;
1197 int cc_succeeded = true; /* client connect script status */
1198 int cc_succeeded_count = 0;
1200 ASSERT (mi->context.c1.tuntap);
1202 /* lock down the common name so it can't change during future TLS renegotiations */
1203 tls_lock_common_name (mi->context.c2.tls_multi);
1205 /* generate a msg() prefix for this client instance */
1206 generate_prefix (mi);
1208 /* delete instances of previous clients with same common-name */
1209 if (!mi->context.options.duplicate_cn)
1210 multi_delete_dup (m, mi);
1212 /* reset pool handle to null */
1213 mi->vaddr_handle = -1;
1216 * Try to source a dynamic config file from the
1217 * --client-config-dir directory.
1219 if (mi->context.options.client_config_dir)
1221 const char *ccd_file;
1223 ccd_file = gen_path (mi->context.options.client_config_dir,
1224 tls_common_name (mi->context.c2.tls_multi, false),
1225 &gc);
1227 /* try common-name file */
1228 if (test_file (ccd_file))
1230 options_server_import (&mi->context.options,
1231 ccd_file,
1232 D_IMPORT_ERRORS|M_OPTERR,
1233 option_permissions_mask,
1234 &option_types_found,
1235 mi->context.c2.es);
1237 else /* try default file */
1239 ccd_file = gen_path (mi->context.options.client_config_dir,
1240 CCD_DEFAULT,
1241 &gc);
1243 if (test_file (ccd_file))
1245 options_server_import (&mi->context.options,
1246 ccd_file,
1247 D_IMPORT_ERRORS|M_OPTERR,
1248 option_permissions_mask,
1249 &option_types_found,
1250 mi->context.c2.es);
1256 * Select a virtual address from either --ifconfig-push in --client-config-dir file
1257 * or --ifconfig-pool.
1259 multi_select_virtual_addr (m, mi);
1261 /* setenv incoming cert common name for script */
1262 setenv_str (mi->context.c2.es, "common_name", tls_common_name (mi->context.c2.tls_multi, true));
1264 /* setenv client real IP address */
1265 setenv_trusted (mi->context.c2.es, get_link_socket_info (&mi->context));
1267 /* setenv client virtual IP address */
1268 multi_set_virtual_addr_env (m, mi);
1271 * Call client-connect plug-in.
1273 if (plugin_defined (m->top.c1.plugins, OPENVPN_PLUGIN_CLIENT_CONNECT))
1275 const char *dc_file = create_temp_filename (mi->context.options.tmp_dir, &gc);
1277 delete_file (dc_file);
1279 if (plugin_call (m->top.c1.plugins, OPENVPN_PLUGIN_CLIENT_CONNECT, dc_file, mi->context.c2.es))
1281 msg (M_WARN, "WARNING: client-connect plugin call failed");
1282 cc_succeeded = false;
1284 else
1286 multi_client_connect_post (m, mi, dc_file, option_permissions_mask, &option_types_found);
1287 ++cc_succeeded_count;
1292 * Run --client-connect script.
1294 if (mi->context.options.client_connect_script && cc_succeeded)
1296 struct buffer cmd = alloc_buf_gc (256, &gc);
1297 const char *dc_file = NULL;
1299 setenv_str (mi->context.c2.es, "script_type", "client-connect");
1301 dc_file = create_temp_filename (mi->context.options.tmp_dir, &gc);
1303 delete_file (dc_file);
1305 buf_printf (&cmd, "%s %s",
1306 mi->context.options.client_connect_script,
1307 dc_file);
1309 if (system_check (BSTR (&cmd), mi->context.c2.es, S_SCRIPT, "client-connect command failed"))
1311 multi_client_connect_post (m, mi, dc_file, option_permissions_mask, &option_types_found);
1312 ++cc_succeeded_count;
1314 else
1315 cc_succeeded = false;
1319 * Check for "disable" directive in client-config-dir file
1320 * or config file generated by --client-connect script.
1322 if (mi->context.options.disable)
1324 msg (D_MULTI_ERRORS, "MULTI: client has been rejected due to 'disable' directive");
1325 cc_succeeded = false;
1328 if (cc_succeeded)
1331 * Process sourced options.
1333 do_deferred_options (&mi->context, option_types_found);
1336 * make sure we got ifconfig settings from somewhere
1338 if (!mi->context.c2.push_ifconfig_defined)
1340 msg (D_MULTI_ERRORS, "MULTI: no dynamic or static remote --ifconfig address is available for %s",
1341 multi_instance_string (mi, false, &gc));
1345 * For routed tunnels, set up internal route to endpoint
1346 * plus add all iroute routes.
1348 if (TUNNEL_TYPE (mi->context.c1.tuntap) == DEV_TYPE_TUN)
1350 if (mi->context.c2.push_ifconfig_defined)
1352 multi_learn_in_addr_t (m, mi, mi->context.c2.push_ifconfig_local, -1);
1353 msg (D_MULTI_LOW, "MULTI: primary virtual IP for %s: %s",
1354 multi_instance_string (mi, false, &gc),
1355 print_in_addr_t (mi->context.c2.push_ifconfig_local, 0, &gc));
1358 /* add routes locally, pointing to new client, if
1359 --iroute options have been specified */
1360 multi_add_iroutes (m, mi);
1363 * iroutes represent subnets which are "owned" by a particular
1364 * client. Therefore, do not actually push a route to a client
1365 * if it matches one of the client's iroutes.
1367 remove_iroutes_from_push_route_list (&mi->context.options);
1369 else if (mi->context.options.iroutes)
1371 msg (D_MULTI_ERRORS, "MULTI: --iroute options rejected for %s -- iroute only works with tun-style tunnels",
1372 multi_instance_string (mi, false, &gc));
1375 /* set our client's VPN endpoint for status reporting purposes */
1376 mi->reporting_addr = mi->context.c2.push_ifconfig_local;
1378 /* set context-level authentication flag */
1379 mi->context.c2.context_auth = CAS_SUCCEEDED;
1381 else
1383 /* set context-level authentication flag */
1384 mi->context.c2.context_auth = cc_succeeded_count ? CAS_PARTIAL : CAS_FAILED;
1387 /* set flag so we don't get called again */
1388 mi->connection_established_flag = true;
1390 gc_free (&gc);
1394 * Reply now to client's PUSH_REQUEST query
1396 mi->context.c2.push_reply_deferred = false;
1400 * Add a mbuf buffer to a particular
1401 * instance.
1403 void
1404 multi_add_mbuf (struct multi_context *m,
1405 struct multi_instance *mi,
1406 struct mbuf_buffer *mb)
1408 if (multi_output_queue_ready (m, mi))
1410 struct mbuf_item item;
1411 item.buffer = mb;
1412 item.instance = mi;
1413 mbuf_add_item (m->mbuf, &item);
1415 else
1417 msg (D_MULTI_DROPPED, "MULTI: packet dropped due to output saturation (multi_add_mbuf)");
1422 * Add a packet to a client instance output queue.
1424 static inline void
1425 multi_unicast (struct multi_context *m,
1426 const struct buffer *buf,
1427 struct multi_instance *mi)
1429 struct mbuf_buffer *mb;
1431 if (BLEN (buf) > 0)
1433 mb = mbuf_alloc_buf (buf);
1434 mb->flags = MF_UNICAST;
1435 multi_add_mbuf (m, mi, mb);
1436 mbuf_free_buf (mb);
1441 * Broadcast a packet to all clients.
1443 void
1444 multi_bcast (struct multi_context *m,
1445 const struct buffer *buf,
1446 struct multi_instance *omit)
1448 struct hash_iterator hi;
1449 struct hash_element *he;
1450 struct multi_instance *mi;
1451 struct mbuf_buffer *mb;
1453 if (BLEN (buf) > 0)
1455 perf_push (PERF_MULTI_BCAST);
1456 #ifdef MULTI_DEBUG_EVENT_LOOP
1457 printf ("BCAST len=%d\n", BLEN (buf));
1458 #endif
1459 mb = mbuf_alloc_buf (buf);
1460 hash_iterator_init (m->iter, &hi, true);
1462 while ((he = hash_iterator_next (&hi)))
1464 mi = (struct multi_instance *) he->value;
1465 if (mi != omit && !mi->halt)
1466 multi_add_mbuf (m, mi, mb);
1469 hash_iterator_free (&hi);
1470 mbuf_free_buf (mb);
1471 perf_pop ();
1476 * Given a time delta, indicating that we wish to be
1477 * awoken by the scheduler at time now + delta, figure
1478 * a sigma parameter (in microseconds) that represents
1479 * a sort of fuzz factor around delta, so that we're
1480 * really telling the scheduler to wake us up any time
1481 * between now + delta - sigma and now + delta + sigma.
1483 * The sigma parameter helps the scheduler to run more efficiently.
1484 * Sigma should be no larger than TV_WITHIN_SIGMA_MAX_USEC
1486 static inline unsigned int
1487 compute_wakeup_sigma (const struct timeval *delta)
1489 if (delta->tv_sec < 1)
1491 /* if < 1 sec, fuzz = # of microseconds / 8 */
1492 return delta->tv_usec >> 3;
1494 else
1496 /* if < 10 minutes, fuzz = 13.1% of timeout */
1497 if (delta->tv_sec < 600)
1498 return delta->tv_sec << 17;
1499 else
1500 return 120000000; /* if >= 10 minutes, fuzz = 2 minutes */
1505 * Figure instance-specific timers, convert
1506 * earliest to absolute time in mi->wakeup,
1507 * call scheduler with our future wakeup time.
1509 * Also close context on signal.
1511 bool
1512 multi_process_post (struct multi_context *m, struct multi_instance *mi, const unsigned int flags)
1514 bool ret = true;
1516 if (!IS_SIG (&mi->context) && ((flags & MPP_PRE_SELECT) || ((flags & MPP_CONDITIONAL_PRE_SELECT) && !ANY_OUT (&mi->context))))
1518 /* figure timeouts and fetch possible outgoing
1519 to_link packets (such as ping or TLS control) */
1520 pre_select (&mi->context);
1522 if (!IS_SIG (&mi->context))
1524 /* calculate an absolute wakeup time */
1525 ASSERT (!gettimeofday (&mi->wakeup, NULL));
1526 tv_add (&mi->wakeup, &mi->context.c2.timeval);
1528 /* tell scheduler to wake us up at some point in the future */
1529 schedule_add_entry (m->schedule,
1530 (struct schedule_entry *) mi,
1531 &mi->wakeup,
1532 compute_wakeup_sigma (&mi->context.c2.timeval));
1534 /* connection is "established" when SSL/TLS key negotiation succeeds
1535 and (if specified) auth user/pass succeeds */
1536 if (!mi->connection_established_flag && CONNECTION_ESTABLISHED (&mi->context))
1537 multi_connection_established (m, mi);
1541 if (IS_SIG (&mi->context))
1543 if (flags & MPP_CLOSE_ON_SIGNAL)
1545 multi_close_instance_on_signal (m, mi);
1546 ret = false;
1549 else
1551 /* continue to pend on output? */
1552 multi_set_pending (m, ANY_OUT (&mi->context) ? mi : NULL);
1554 #ifdef MULTI_DEBUG_EVENT_LOOP
1555 printf ("POST %s[%d] to=%d lo=%d/%d w=%d/%d\n",
1556 id(mi),
1557 (int) (mi == m->pending),
1558 mi ? mi->context.c2.to_tun.len : -1,
1559 mi ? mi->context.c2.to_link.len : -1,
1560 (mi && mi->context.c2.fragment) ? mi->context.c2.fragment->outgoing.len : -1,
1561 (int)mi->context.c2.timeval.tv_sec,
1562 (int)mi->context.c2.timeval.tv_usec);
1563 #endif
1566 if ((flags & MPP_RECORD_TOUCH) && m->mpp_touched)
1567 *m->mpp_touched = mi;
1569 return ret;
1573 * Process packets in the TCP/UDP socket -> TUN/TAP interface direction,
1574 * i.e. client -> server direction.
1576 bool
1577 multi_process_incoming_link (struct multi_context *m, struct multi_instance *instance, const unsigned int mpp_flags)
1579 struct gc_arena gc = gc_new ();
1581 struct context *c;
1582 struct mroute_addr src, dest;
1583 unsigned int mroute_flags;
1584 struct multi_instance *mi;
1585 bool ret = true;
1587 if (m->pending)
1588 return true;
1590 if (!instance)
1592 #ifdef MULTI_DEBUG_EVENT_LOOP
1593 printf ("TCP/UDP -> TUN [%d]\n", BLEN (&m->top.c2.buf));
1594 #endif
1595 multi_set_pending (m, multi_get_create_instance_udp (m));
1597 else
1598 multi_set_pending (m, instance);
1600 if (m->pending)
1602 set_prefix (m->pending);
1604 /* get instance context */
1605 c = &m->pending->context;
1607 if (!instance)
1609 /* transfer packet pointer from top-level context buffer to instance */
1610 c->c2.buf = m->top.c2.buf;
1612 /* transfer from-addr from top-level context buffer to instance */
1613 c->c2.from = m->top.c2.from;
1616 if (BLEN (&c->c2.buf) > 0)
1618 /* decrypt in instance context */
1619 process_incoming_link (c);
1621 if (TUNNEL_TYPE (m->top.c1.tuntap) == DEV_TYPE_TUN)
1623 /* extract packet source and dest addresses */
1624 mroute_flags = mroute_extract_addr_from_packet (&src,
1625 &dest,
1626 &c->c2.to_tun,
1627 DEV_TYPE_TUN);
1629 /* drop packet if extract failed */
1630 if (!(mroute_flags & MROUTE_EXTRACT_SUCCEEDED))
1632 c->c2.to_tun.len = 0;
1634 /* make sure that source address is associated with this client */
1635 else if (multi_get_instance_by_virtual_addr (m, &src, true) != m->pending)
1637 msg (D_MULTI_DROPPED, "MULTI: bad source address from client [%s], packet dropped",
1638 mroute_addr_print (&src, &gc));
1639 c->c2.to_tun.len = 0;
1641 /* client-to-client communication enabled? */
1642 else if (m->enable_c2c)
1644 /* multicast? */
1645 if (mroute_flags & MROUTE_EXTRACT_MCAST)
1647 /* for now, treat multicast as broadcast */
1648 multi_bcast (m, &c->c2.to_tun, m->pending);
1650 else /* possible client to client routing */
1652 ASSERT (!(mroute_flags & MROUTE_EXTRACT_BCAST));
1653 mi = multi_get_instance_by_virtual_addr (m, &dest, true);
1655 /* if dest addr is a known client, route to it */
1656 if (mi)
1658 multi_unicast (m, &c->c2.to_tun, mi);
1659 register_activity (c);
1660 c->c2.to_tun.len = 0;
1665 else if (TUNNEL_TYPE (m->top.c1.tuntap) == DEV_TYPE_TAP)
1667 /* extract packet source and dest addresses */
1668 mroute_flags = mroute_extract_addr_from_packet (&src,
1669 &dest,
1670 &c->c2.to_tun,
1671 DEV_TYPE_TAP);
1673 if (mroute_flags & MROUTE_EXTRACT_SUCCEEDED)
1675 if (multi_learn_addr (m, m->pending, &src, 0) == m->pending)
1677 /* check for broadcast */
1678 if (m->enable_c2c)
1680 if (mroute_flags & (MROUTE_EXTRACT_BCAST|MROUTE_EXTRACT_MCAST))
1682 multi_bcast (m, &c->c2.to_tun, m->pending);
1684 else /* try client-to-client routing */
1686 mi = multi_get_instance_by_virtual_addr (m, &dest, false);
1688 /* if dest addr is a known client, route to it */
1689 if (mi)
1691 multi_unicast (m, &c->c2.to_tun, mi);
1692 register_activity (c);
1693 c->c2.to_tun.len = 0;
1698 else
1700 msg (D_MULTI_DROPPED, "MULTI: bad source address from client [%s], packet dropped",
1701 mroute_addr_print (&src, &gc));
1702 c->c2.to_tun.len = 0;
1705 else
1707 c->c2.to_tun.len = 0;
1712 /* postprocess and set wakeup */
1713 ret = multi_process_post (m, m->pending, mpp_flags);
1715 clear_prefix ();
1718 gc_free (&gc);
1719 return ret;
1723 * Process packets in the TUN/TAP interface -> TCP/UDP socket direction,
1724 * i.e. server -> client direction.
1726 bool
1727 multi_process_incoming_tun (struct multi_context *m, const unsigned int mpp_flags)
1729 struct gc_arena gc = gc_new ();
1730 bool ret = true;
1732 if (BLEN (&m->top.c2.buf) > 0)
1734 unsigned int mroute_flags;
1735 struct mroute_addr src, dest;
1736 const int dev_type = TUNNEL_TYPE (m->top.c1.tuntap);
1738 #ifdef MULTI_DEBUG_EVENT_LOOP
1739 printf ("TUN -> TCP/UDP [%d]\n", BLEN (&m->top.c2.buf));
1740 #endif
1742 if (m->pending)
1743 return true;
1746 * Route an incoming tun/tap packet to
1747 * the appropriate multi_instance object.
1750 mroute_flags = mroute_extract_addr_from_packet (&src,
1751 &dest,
1752 &m->top.c2.buf,
1753 dev_type);
1755 if (mroute_flags & MROUTE_EXTRACT_SUCCEEDED)
1757 struct context *c;
1759 /* broadcast or multicast dest addr? */
1760 if (mroute_flags & (MROUTE_EXTRACT_BCAST|MROUTE_EXTRACT_MCAST))
1762 /* for now, treat multicast as broadcast */
1763 multi_bcast (m, &m->top.c2.buf, NULL);
1765 else
1767 multi_set_pending (m, multi_get_instance_by_virtual_addr (m, &dest, dev_type == DEV_TYPE_TUN));
1769 if (m->pending)
1771 /* get instance context */
1772 c = &m->pending->context;
1774 set_prefix (m->pending);
1776 if (multi_output_queue_ready (m, m->pending))
1778 /* transfer packet pointer from top-level context buffer to instance */
1779 c->c2.buf = m->top.c2.buf;
1781 else
1783 /* drop packet */
1784 msg (D_MULTI_DROPPED, "MULTI: packet dropped due to output saturation (multi_process_incoming_tun)");
1785 buf_clear (&c->c2.buf);
1788 /* encrypt in instance context */
1789 process_incoming_tun (c);
1791 /* postprocess and set wakeup */
1792 ret = multi_process_post (m, m->pending, mpp_flags);
1794 clear_prefix ();
1799 gc_free (&gc);
1800 return ret;
1804 * Process a possible client-to-client/bcast/mcast message in the
1805 * queue.
1807 struct multi_instance *
1808 multi_get_queue (struct mbuf_set *ms)
1810 struct mbuf_item item;
1812 if (mbuf_extract_item (ms, &item, true)) /* cleartext IP packet */
1814 unsigned int pipv4_flags = PIPV4_PASSTOS;
1816 set_prefix (item.instance);
1817 item.instance->context.c2.buf = item.buffer->buf;
1818 if (item.buffer->flags & MF_UNICAST) /* --mssfix doesn't make sense for broadcast or multicast */
1819 pipv4_flags |= PIPV4_MSSFIX;
1820 process_ipv4_header (&item.instance->context, pipv4_flags, &item.instance->context.c2.buf);
1821 encrypt_sign (&item.instance->context, true);
1822 mbuf_free_buf (item.buffer);
1824 dmsg (D_MULTI_DEBUG, "MULTI: C2C/MCAST/BCAST");
1826 clear_prefix ();
1827 return item.instance;
1829 else
1831 return NULL;
1836 * Called when an I/O wait times out. Usually means that a particular
1837 * client instance object needs timer-based service.
1839 bool
1840 multi_process_timeout (struct multi_context *m, const unsigned int mpp_flags)
1842 bool ret = true;
1844 #ifdef MULTI_DEBUG_EVENT_LOOP
1845 printf ("%s -> TIMEOUT\n", id(m->earliest_wakeup));
1846 #endif
1848 /* instance marked for wakeup? */
1849 if (m->earliest_wakeup)
1851 set_prefix (m->earliest_wakeup);
1852 ret = multi_process_post (m, m->earliest_wakeup, mpp_flags);
1853 m->earliest_wakeup = NULL;
1854 clear_prefix ();
1856 return ret;
1860 * Drop a TUN/TAP outgoing packet..
1862 void
1863 multi_process_drop_outgoing_tun (struct multi_context *m, const unsigned int mpp_flags)
1865 struct multi_instance *mi = m->pending;
1867 ASSERT (mi);
1869 set_prefix (mi);
1871 msg (D_MULTI_ERRORS, "MULTI: Outgoing TUN queue full, dropped packet len=%d",
1872 mi->context.c2.to_tun.len);
1874 buf_reset (&mi->context.c2.to_tun);
1876 multi_process_post (m, mi, mpp_flags);
1877 clear_prefix ();
1881 * Per-client route quota management
1884 void
1885 route_quota_exceeded (const struct multi_context *m, const struct multi_instance *mi)
1887 struct gc_arena gc = gc_new ();
1888 msg (D_ROUTE_QUOTA, "MULTI ROUTE: route quota (%d) exceeded for %s (see --max-routes-per-client option)",
1889 mi->context.options.max_routes_per_client,
1890 multi_instance_string (mi, false, &gc));
1891 gc_free (&gc);
1894 #ifdef ENABLE_DEBUG
1896 * Flood clients with random packets
1898 static void
1899 gremlin_flood_clients (struct multi_context *m)
1901 const int level = GREMLIN_PACKET_FLOOD_LEVEL (m->top.options.gremlin);
1902 if (level)
1904 struct gc_arena gc = gc_new ();
1905 struct buffer buf = alloc_buf_gc (BUF_SIZE (&m->top.c2.frame), &gc);
1906 struct packet_flood_parms parm = get_packet_flood_parms (level);
1907 int i;
1909 ASSERT (buf_init (&buf, FRAME_HEADROOM (&m->top.c2.frame)));
1910 parm.packet_size = min_int (parm.packet_size, MAX_RW_SIZE_TUN (&m->top.c2.frame));
1912 msg (D_GREMLIN, "GREMLIN_FLOOD_CLIENTS: flooding clients with %d packets of size %d",
1913 parm.n_packets,
1914 parm.packet_size);
1916 for (i = 0; i < parm.packet_size; ++i)
1917 ASSERT (buf_write_u8 (&buf, get_random () & 0xFF));
1919 for (i = 0; i < parm.n_packets; ++i)
1920 multi_bcast (m, &buf, NULL);
1922 gc_free (&gc);
1925 #endif
1928 * Process timers in the top-level context
1930 void
1931 multi_process_per_second_timers_dowork (struct multi_context *m)
1933 /* possibly reap instances/routes in vhash */
1934 multi_reap_process (m);
1936 /* possibly print to status log */
1937 if (m->top.c1.status_output)
1939 if (status_trigger (m->top.c1.status_output))
1940 multi_print_status (m, m->top.c1.status_output, m->status_file_version);
1943 /* possibly flush ifconfig-pool file */
1944 multi_ifconfig_pool_persist (m, false);
1946 #ifdef ENABLE_DEBUG
1947 gremlin_flood_clients (m);
1948 #endif
1951 void
1952 multi_top_init (struct multi_context *m, const struct context *top, const bool alloc_buffers)
1954 inherit_context_top (&m->top, top);
1955 m->top.c2.buffers = NULL;
1956 if (alloc_buffers)
1957 m->top.c2.buffers = init_context_buffers (&top->c2.frame);
1960 void
1961 multi_top_free (struct multi_context *m)
1963 close_context (&m->top, -1, CC_GC_FREE);
1964 free_context_buffers (m->top.c2.buffers);
1968 * Return true if event loop should break,
1969 * false if it should continue.
1971 bool
1972 multi_process_signal (struct multi_context *m)
1974 if (m->top.sig->signal_received == SIGUSR2)
1976 struct status_output *so = status_open (NULL, 0, M_INFO, NULL, 0);
1977 multi_print_status (m, so, m->status_file_version);
1978 status_close (so);
1979 m->top.sig->signal_received = 0;
1980 return false;
1982 return true;
1986 * Called when an instance should be closed due to the
1987 * reception of a soft signal.
1989 void
1990 multi_close_instance_on_signal (struct multi_context *m, struct multi_instance *mi)
1992 remap_signal (&mi->context);
1993 set_prefix (mi);
1994 print_signal (mi->context.sig, "client-instance", D_MULTI_LOW);
1995 clear_prefix ();
1996 multi_close_instance (m, mi, false);
1999 static void
2000 multi_signal_instance (struct multi_context *m, struct multi_instance *mi, const int sig)
2002 mi->context.sig->signal_received = sig;
2003 multi_close_instance_on_signal (m, mi);
2007 * Management subsystem callbacks
2010 #ifdef ENABLE_MANAGEMENT
2012 static void
2013 management_callback_status (void *arg, const int version, struct status_output *so)
2015 struct multi_context *m = (struct multi_context *) arg;
2017 if (!version)
2018 multi_print_status (m, so, m->status_file_version);
2019 else
2020 multi_print_status (m, so, version);
2023 static int
2024 management_callback_kill_by_cn (void *arg, const char *del_cn)
2026 struct multi_context *m = (struct multi_context *) arg;
2027 struct hash_iterator hi;
2028 struct hash_element *he;
2029 int count = 0;
2031 hash_iterator_init (m->iter, &hi, true);
2032 while ((he = hash_iterator_next (&hi)))
2034 struct multi_instance *mi = (struct multi_instance *) he->value;
2035 if (!mi->halt)
2037 const char *cn = tls_common_name (mi->context.c2.tls_multi, false);
2038 if (cn && !strcmp (cn, del_cn))
2040 multi_signal_instance (m, mi, SIGTERM);
2041 ++count;
2045 hash_iterator_free (&hi);
2046 return count;
2049 static int
2050 management_callback_kill_by_addr (void *arg, const in_addr_t addr, const int port)
2052 struct multi_context *m = (struct multi_context *) arg;
2053 struct hash_iterator hi;
2054 struct hash_element *he;
2055 struct sockaddr_in saddr;
2056 struct mroute_addr maddr;
2057 int count = 0;
2059 CLEAR (saddr);
2060 saddr.sin_family = AF_INET;
2061 saddr.sin_addr.s_addr = htonl (addr);
2062 saddr.sin_port = htons (port);
2063 if (mroute_extract_sockaddr_in (&maddr, &saddr, true))
2065 hash_iterator_init (m->iter, &hi, true);
2066 while ((he = hash_iterator_next (&hi)))
2068 struct multi_instance *mi = (struct multi_instance *) he->value;
2069 if (!mi->halt && mroute_addr_equal (&maddr, &mi->real))
2071 multi_signal_instance (m, mi, SIGTERM);
2072 ++count;
2075 hash_iterator_free (&hi);
2077 return count;
2080 static void
2081 management_delete_event (void *arg, event_t event)
2083 struct multi_context *m = (struct multi_context *) arg;
2084 if (m->mtcp)
2085 multi_tcp_delete_event (m->mtcp, event);
2088 #endif
2090 void
2091 init_management_callback_multi (struct multi_context *m)
2093 #ifdef ENABLE_MANAGEMENT
2094 if (management)
2096 struct management_callback cb;
2097 CLEAR (cb);
2098 cb.arg = m;
2099 cb.status = management_callback_status;
2100 cb.show_net = management_show_net_callback;
2101 cb.kill_by_cn = management_callback_kill_by_cn;
2102 cb.kill_by_addr = management_callback_kill_by_addr;
2103 cb.delete_event = management_delete_event;
2104 management_set_callback (management, &cb);
2106 #endif
2109 void
2110 uninit_management_callback_multi (struct multi_context *m)
2112 uninit_management_callback ();
2116 * Top level event loop.
2118 void
2119 tunnel_server (struct context *top)
2121 ASSERT (top->options.mode == MODE_SERVER);
2123 switch (top->options.proto) {
2124 case PROTO_UDPv4:
2125 tunnel_server_udp (top);
2126 break;
2127 case PROTO_TCPv4_SERVER:
2128 tunnel_server_tcp (top);
2129 break;
2130 default:
2131 ASSERT (0);
2135 #else
2136 static void dummy(void) {}
2137 #endif /* P2MP_SERVER */