3d5538c35bd3cb73b4a85173d9125b01247fb129
[strongswan.git] / src / libhydra / plugins / kernel_netlink / kernel_netlink_net.c
1 /*
2 * Copyright (C) 2008-2014 Tobias Brunner
3 * Copyright (C) 2005-2008 Martin Willi
4 * Hochschule fuer Technik Rapperswil
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 2 of the License, or (at your
9 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * for more details.
15 */
16
17 /*
18 * Copyright (C) 2010 secunet Security Networks AG
19 * Copyright (C) 2010 Thomas Egerer
20 *
21 * Permission is hereby granted, free of charge, to any person obtaining a copy
22 * of this software and associated documentation files (the "Software"), to deal
23 * in the Software without restriction, including without limitation the rights
24 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
25 * copies of the Software, and to permit persons to whom the Software is
26 * furnished to do so, subject to the following conditions:
27 *
28 * The above copyright notice and this permission notice shall be included in
29 * all copies or substantial portions of the Software.
30 *
31 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
32 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
33 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
34 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
35 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
36 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
37 * THE SOFTWARE.
38 */
39
40 #include <sys/socket.h>
41 #include <sys/utsname.h>
42 #include <linux/netlink.h>
43 #include <linux/rtnetlink.h>
44 #include <unistd.h>
45 #include <errno.h>
46 #include <net/if.h>
47 #ifdef HAVE_LINUX_FIB_RULES_H
48 #include <linux/fib_rules.h>
49 #endif
50
51 #include "kernel_netlink_net.h"
52 #include "kernel_netlink_shared.h"
53
54 #include <hydra.h>
55 #include <utils/debug.h>
56 #include <threading/mutex.h>
57 #include <threading/rwlock.h>
58 #include <threading/rwlock_condvar.h>
59 #include <threading/spinlock.h>
60 #include <collections/hashtable.h>
61 #include <collections/linked_list.h>
62 #include <processing/jobs/callback_job.h>
63
64 /** delay before firing roam events (ms) */
65 #define ROAM_DELAY 100
66
67 /** delay before reinstalling routes (ms) */
68 #define ROUTE_DELAY 100
69
70 /** maximum recursion when searching for addresses in get_route() */
71 #define MAX_ROUTE_RECURSION 2
72
73 #ifndef ROUTING_TABLE
74 #define ROUTING_TABLE 0
75 #endif
76
77 #ifndef ROUTING_TABLE_PRIO
78 #define ROUTING_TABLE_PRIO 0
79 #endif
80
81 typedef struct addr_entry_t addr_entry_t;
82
83 /**
84 * IP address in an iface_entry_t
85 */
86 struct addr_entry_t {
87
88 /** the ip address */
89 host_t *ip;
90
91 /** address flags */
92 u_char flags;
93
94 /** scope of the address */
95 u_char scope;
96
97 /** number of times this IP is used, if virtual (i.e. managed by us) */
98 u_int refcount;
99
100 /** TRUE once it is installed, if virtual */
101 bool installed;
102 };
103
104 /**
105 * destroy a addr_entry_t object
106 */
107 static void addr_entry_destroy(addr_entry_t *this)
108 {
109 this->ip->destroy(this->ip);
110 free(this);
111 }
112
113 typedef struct iface_entry_t iface_entry_t;
114
115 /**
116 * A network interface on this system, containing addr_entry_t's
117 */
118 struct iface_entry_t {
119
120 /** interface index */
121 int ifindex;
122
123 /** name of the interface */
124 char ifname[IFNAMSIZ];
125
126 /** interface flags, as in netdevice(7) SIOCGIFFLAGS */
127 u_int flags;
128
129 /** list of addresses as host_t */
130 linked_list_t *addrs;
131
132 /** TRUE if usable by config */
133 bool usable;
134 };
135
136 /**
137 * destroy an interface entry
138 */
139 static void iface_entry_destroy(iface_entry_t *this)
140 {
141 this->addrs->destroy_function(this->addrs, (void*)addr_entry_destroy);
142 free(this);
143 }
144
145 /**
146 * find an interface entry by index
147 */
148 static bool iface_entry_by_index(iface_entry_t *this, int *ifindex)
149 {
150 return this->ifindex == *ifindex;
151 }
152
153 /**
154 * find an interface entry by name
155 */
156 static bool iface_entry_by_name(iface_entry_t *this, char *ifname)
157 {
158 return streq(this->ifname, ifname);
159 }
160
161 /**
162 * check if an interface is up
163 */
164 static inline bool iface_entry_up(iface_entry_t *iface)
165 {
166 return (iface->flags & IFF_UP) == IFF_UP;
167 }
168
169 /**
170 * check if an interface is up and usable
171 */
172 static inline bool iface_entry_up_and_usable(iface_entry_t *iface)
173 {
174 return iface->usable && iface_entry_up(iface);
175 }
176
177 typedef struct addr_map_entry_t addr_map_entry_t;
178
179 /**
180 * Entry that maps an IP address to an interface entry
181 */
182 struct addr_map_entry_t {
183 /** The IP address */
184 host_t *ip;
185
186 /** The address entry for this IP address */
187 addr_entry_t *addr;
188
189 /** The interface this address is installed on */
190 iface_entry_t *iface;
191 };
192
193 /**
194 * Hash a addr_map_entry_t object, all entries with the same IP address
195 * are stored in the same bucket
196 */
197 static u_int addr_map_entry_hash(addr_map_entry_t *this)
198 {
199 return chunk_hash(this->ip->get_address(this->ip));
200 }
201
202 /**
203 * Compare two addr_map_entry_t objects, two entries are equal if they are
204 * installed on the same interface
205 */
206 static bool addr_map_entry_equals(addr_map_entry_t *a, addr_map_entry_t *b)
207 {
208 return a->iface->ifindex == b->iface->ifindex &&
209 a->ip->ip_equals(a->ip, b->ip);
210 }
211
212 /**
213 * Used with get_match this finds an address entry if it is installed on
214 * an up and usable interface
215 */
216 static bool addr_map_entry_match_up_and_usable(addr_map_entry_t *a,
217 addr_map_entry_t *b)
218 {
219 return iface_entry_up_and_usable(b->iface) &&
220 a->ip->ip_equals(a->ip, b->ip);
221 }
222
223 /**
224 * Used with get_match this finds an address entry if it is installed on
225 * any active local interface
226 */
227 static bool addr_map_entry_match_up(addr_map_entry_t *a, addr_map_entry_t *b)
228 {
229 return iface_entry_up(b->iface) && a->ip->ip_equals(a->ip, b->ip);
230 }
231
232 /**
233 * Used with get_match this finds an address entry if it is installed on
234 * any local interface
235 */
236 static bool addr_map_entry_match(addr_map_entry_t *a, addr_map_entry_t *b)
237 {
238 return a->ip->ip_equals(a->ip, b->ip);
239 }
240
241 typedef struct route_entry_t route_entry_t;
242
243 /**
244 * Installed routing entry
245 */
246 struct route_entry_t {
247 /** Name of the interface the route is bound to */
248 char *if_name;
249
250 /** Source ip of the route */
251 host_t *src_ip;
252
253 /** Gateway for this route */
254 host_t *gateway;
255
256 /** Destination net */
257 chunk_t dst_net;
258
259 /** Destination net prefixlen */
260 u_int8_t prefixlen;
261 };
262
263 /**
264 * Clone a route_entry_t object.
265 */
266 static route_entry_t *route_entry_clone(route_entry_t *this)
267 {
268 route_entry_t *route;
269
270 INIT(route,
271 .if_name = strdup(this->if_name),
272 .src_ip = this->src_ip->clone(this->src_ip),
273 .gateway = this->gateway ? this->gateway->clone(this->gateway) : NULL,
274 .dst_net = chunk_clone(this->dst_net),
275 .prefixlen = this->prefixlen,
276 );
277 return route;
278 }
279
280 /**
281 * Destroy a route_entry_t object
282 */
283 static void route_entry_destroy(route_entry_t *this)
284 {
285 free(this->if_name);
286 DESTROY_IF(this->src_ip);
287 DESTROY_IF(this->gateway);
288 chunk_free(&this->dst_net);
289 free(this);
290 }
291
292 /**
293 * Hash a route_entry_t object
294 */
295 static u_int route_entry_hash(route_entry_t *this)
296 {
297 return chunk_hash_inc(chunk_from_thing(this->prefixlen),
298 chunk_hash(this->dst_net));
299 }
300
301 /**
302 * Compare two route_entry_t objects
303 */
304 static bool route_entry_equals(route_entry_t *a, route_entry_t *b)
305 {
306 if (a->if_name && b->if_name && streq(a->if_name, b->if_name) &&
307 a->src_ip->ip_equals(a->src_ip, b->src_ip) &&
308 chunk_equals(a->dst_net, b->dst_net) && a->prefixlen == b->prefixlen)
309 {
310 return (!a->gateway && !b->gateway) || (a->gateway && b->gateway &&
311 a->gateway->ip_equals(a->gateway, b->gateway));
312 }
313 return FALSE;
314 }
315
316 typedef struct net_change_t net_change_t;
317
318 /**
319 * Queued network changes
320 */
321 struct net_change_t {
322 /** Name of the interface that got activated (or an IP appeared on) */
323 char *if_name;
324 };
325
326 /**
327 * Destroy a net_change_t object
328 */
329 static void net_change_destroy(net_change_t *this)
330 {
331 free(this->if_name);
332 free(this);
333 }
334
335 /**
336 * Hash a net_change_t object
337 */
338 static u_int net_change_hash(net_change_t *this)
339 {
340 return chunk_hash(chunk_create(this->if_name, strlen(this->if_name)));
341 }
342
343 /**
344 * Compare two net_change_t objects
345 */
346 static bool net_change_equals(net_change_t *a, net_change_t *b)
347 {
348 return streq(a->if_name, b->if_name);
349 }
350
351 typedef struct private_kernel_netlink_net_t private_kernel_netlink_net_t;
352
353 /**
354 * Private variables and functions of kernel_netlink_net class.
355 */
356 struct private_kernel_netlink_net_t {
357 /**
358 * Public part of the kernel_netlink_net_t object.
359 */
360 kernel_netlink_net_t public;
361
362 /**
363 * lock to access various lists and maps
364 */
365 rwlock_t *lock;
366
367 /**
368 * condition variable to signal virtual IP add/removal
369 */
370 rwlock_condvar_t *condvar;
371
372 /**
373 * Cached list of interfaces and its addresses (iface_entry_t)
374 */
375 linked_list_t *ifaces;
376
377 /**
378 * Map for IP addresses to iface_entry_t objects (addr_map_entry_t)
379 */
380 hashtable_t *addrs;
381
382 /**
383 * Map for virtual IP addresses to iface_entry_t objects (addr_map_entry_t)
384 */
385 hashtable_t *vips;
386
387 /**
388 * netlink rt socket (routing)
389 */
390 netlink_socket_t *socket;
391
392 /**
393 * Netlink rt socket to receive address change events
394 */
395 int socket_events;
396
397 /**
398 * earliest time of the next roam event
399 */
400 timeval_t next_roam;
401
402 /**
403 * roam event due to address change
404 */
405 bool roam_address;
406
407 /**
408 * lock to check and update roam event time
409 */
410 spinlock_t *roam_lock;
411
412 /**
413 * routing table to install routes
414 */
415 int routing_table;
416
417 /**
418 * priority of used routing table
419 */
420 int routing_table_prio;
421
422 /**
423 * installed routes
424 */
425 hashtable_t *routes;
426
427 /**
428 * mutex for routes
429 */
430 mutex_t *routes_lock;
431
432 /**
433 * interface changes which may trigger route reinstallation
434 */
435 hashtable_t *net_changes;
436
437 /**
438 * mutex for route reinstallation triggers
439 */
440 mutex_t *net_changes_lock;
441
442 /**
443 * time of last route reinstallation
444 */
445 timeval_t last_route_reinstall;
446
447 /**
448 * whether to react to RTM_NEWROUTE or RTM_DELROUTE events
449 */
450 bool process_route;
451
452 /**
453 * whether to trigger roam events
454 */
455 bool roam_events;
456
457 /**
458 * whether to actually install virtual IPs
459 */
460 bool install_virtual_ip;
461
462 /**
463 * the name of the interface virtual IP addresses are installed on
464 */
465 char *install_virtual_ip_on;
466
467 /**
468 * whether preferred source addresses can be specified for IPv6 routes
469 */
470 bool rta_prefsrc_for_ipv6;
471
472 /**
473 * whether to prefer temporary IPv6 addresses over public ones
474 */
475 bool prefer_temporary_addrs;
476
477 /**
478 * list with routing tables to be excluded from route lookup
479 */
480 linked_list_t *rt_exclude;
481
482 /**
483 * MTU to set on installed routes
484 */
485 u_int32_t mtu;
486
487 /**
488 * MSS to set on installed routes
489 */
490 u_int32_t mss;
491 };
492
493 /**
494 * Forward declaration
495 */
496 static status_t manage_srcroute(private_kernel_netlink_net_t *this,
497 int nlmsg_type, int flags, chunk_t dst_net,
498 u_int8_t prefixlen, host_t *gateway,
499 host_t *src_ip, char *if_name);
500
501 /**
502 * Clear the queued network changes.
503 */
504 static void net_changes_clear(private_kernel_netlink_net_t *this)
505 {
506 enumerator_t *enumerator;
507 net_change_t *change;
508
509 enumerator = this->net_changes->create_enumerator(this->net_changes);
510 while (enumerator->enumerate(enumerator, NULL, (void**)&change))
511 {
512 this->net_changes->remove_at(this->net_changes, enumerator);
513 net_change_destroy(change);
514 }
515 enumerator->destroy(enumerator);
516 }
517
518 /**
519 * Act upon queued network changes.
520 */
521 static job_requeue_t reinstall_routes(private_kernel_netlink_net_t *this)
522 {
523 enumerator_t *enumerator;
524 route_entry_t *route;
525
526 this->net_changes_lock->lock(this->net_changes_lock);
527 this->routes_lock->lock(this->routes_lock);
528
529 enumerator = this->routes->create_enumerator(this->routes);
530 while (enumerator->enumerate(enumerator, NULL, (void**)&route))
531 {
532 net_change_t *change, lookup = {
533 .if_name = route->if_name,
534 };
535 /* check if a change for the outgoing interface is queued */
536 change = this->net_changes->get(this->net_changes, &lookup);
537 if (!change)
538 { /* in case src_ip is not on the outgoing interface */
539 if (this->public.interface.get_interface(&this->public.interface,
540 route->src_ip, &lookup.if_name))
541 {
542 if (!streq(lookup.if_name, route->if_name))
543 {
544 change = this->net_changes->get(this->net_changes, &lookup);
545 }
546 free(lookup.if_name);
547 }
548 }
549 if (change)
550 {
551 manage_srcroute(this, RTM_NEWROUTE, NLM_F_CREATE | NLM_F_EXCL,
552 route->dst_net, route->prefixlen, route->gateway,
553 route->src_ip, route->if_name);
554 }
555 }
556 enumerator->destroy(enumerator);
557 this->routes_lock->unlock(this->routes_lock);
558
559 net_changes_clear(this);
560 this->net_changes_lock->unlock(this->net_changes_lock);
561 return JOB_REQUEUE_NONE;
562 }
563
564 /**
565 * Queue route reinstallation caused by network changes for a given interface.
566 *
567 * The route reinstallation is delayed for a while and only done once for
568 * several calls during this delay, in order to avoid doing it too often.
569 * The interface name is freed.
570 */
571 static void queue_route_reinstall(private_kernel_netlink_net_t *this,
572 char *if_name)
573 {
574 net_change_t *update, *found;
575 timeval_t now;
576 job_t *job;
577
578 INIT(update,
579 .if_name = if_name
580 );
581
582 this->net_changes_lock->lock(this->net_changes_lock);
583 found = this->net_changes->put(this->net_changes, update, update);
584 if (found)
585 {
586 net_change_destroy(found);
587 }
588 time_monotonic(&now);
589 if (timercmp(&now, &this->last_route_reinstall, >))
590 {
591 timeval_add_ms(&now, ROUTE_DELAY);
592 this->last_route_reinstall = now;
593
594 job = (job_t*)callback_job_create((callback_job_cb_t)reinstall_routes,
595 this, NULL, NULL);
596 lib->scheduler->schedule_job_ms(lib->scheduler, job, ROUTE_DELAY);
597 }
598 this->net_changes_lock->unlock(this->net_changes_lock);
599 }
600
601 /**
602 * check if the given IP is known as virtual IP and currently installed
603 *
604 * this function will also return TRUE if the virtual IP entry disappeared.
605 * in that case the returned entry will be NULL.
606 *
607 * this->lock must be held when calling this function
608 */
609 static bool is_vip_installed_or_gone(private_kernel_netlink_net_t *this,
610 host_t *ip, addr_map_entry_t **entry)
611 {
612 addr_map_entry_t lookup = {
613 .ip = ip,
614 };
615
616 *entry = this->vips->get_match(this->vips, &lookup,
617 (void*)addr_map_entry_match);
618 if (*entry == NULL)
619 { /* the virtual IP disappeared */
620 return TRUE;
621 }
622 return (*entry)->addr->installed;
623 }
624
625 /**
626 * check if the given IP is known as virtual IP
627 *
628 * this->lock must be held when calling this function
629 */
630 static bool is_known_vip(private_kernel_netlink_net_t *this, host_t *ip)
631 {
632 addr_map_entry_t lookup = {
633 .ip = ip,
634 };
635
636 return this->vips->get_match(this->vips, &lookup,
637 (void*)addr_map_entry_match) != NULL;
638 }
639
640 /**
641 * Add an address map entry
642 */
643 static void addr_map_entry_add(hashtable_t *map, addr_entry_t *addr,
644 iface_entry_t *iface)
645 {
646 addr_map_entry_t *entry;
647
648 INIT(entry,
649 .ip = addr->ip,
650 .addr = addr,
651 .iface = iface,
652 );
653 entry = map->put(map, entry, entry);
654 free(entry);
655 }
656
657 /**
658 * Remove an address map entry
659 */
660 static void addr_map_entry_remove(hashtable_t *map, addr_entry_t *addr,
661 iface_entry_t *iface)
662 {
663 addr_map_entry_t *entry, lookup = {
664 .ip = addr->ip,
665 .addr = addr,
666 .iface = iface,
667 };
668
669 entry = map->remove(map, &lookup);
670 free(entry);
671 }
672
673 /**
674 * Determine the type or scope of the given unicast IP address. This is not
675 * the same thing returned in rtm_scope/ifa_scope.
676 *
677 * We use return values as defined in RFC 6724 (referring to RFC 4291).
678 */
679 static u_char get_scope(host_t *ip)
680 {
681 chunk_t addr;
682
683 addr = ip->get_address(ip);
684 switch (addr.len)
685 {
686 case 4:
687 /* we use the mapping defined in RFC 6724, 3.2 */
688 if (addr.ptr[0] == 127)
689 { /* link-local, same as the IPv6 loopback address */
690 return 2;
691 }
692 if (addr.ptr[0] == 169 && addr.ptr[1] == 254)
693 { /* link-local */
694 return 2;
695 }
696 break;
697 case 16:
698 if (IN6_IS_ADDR_LOOPBACK((struct in6_addr*)addr.ptr))
699 { /* link-local, according to RFC 4291, 2.5.3 */
700 return 2;
701 }
702 if (IN6_IS_ADDR_LINKLOCAL((struct in6_addr*)addr.ptr))
703 {
704 return 2;
705 }
706 if (IN6_IS_ADDR_SITELOCAL((struct in6_addr*)addr.ptr))
707 { /* deprecated, according to RFC 4291, 2.5.7 */
708 return 5;
709 }
710 break;
711 default:
712 break;
713 }
714 /* global */
715 return 14;
716 }
717
718 /**
719 * Returns the length of the common prefix in bits up to the length of a's
720 * prefix, defined by RFC 6724 as the portion of the address not including the
721 * interface ID, which is 64-bit for most unicast addresses (see RFC 4291).
722 */
723 static u_char common_prefix(host_t *a, host_t *b)
724 {
725 chunk_t aa, ba;
726 u_char byte, bits = 0, match;
727
728 aa = a->get_address(a);
729 ba = b->get_address(b);
730 for (byte = 0; byte < 8; byte++)
731 {
732 if (aa.ptr[byte] != ba.ptr[byte])
733 {
734 match = aa.ptr[byte] ^ ba.ptr[byte];
735 for (bits = 8; match; match >>= 1)
736 {
737 bits--;
738 }
739 break;
740 }
741 }
742 return byte * 8 + bits;
743 }
744
745 /**
746 * Compare two IP addresses and return TRUE if the second address is the better
747 * choice of the two to reach the destination.
748 * For IPv6 we approximately follow RFC 6724.
749 */
750 static bool is_address_better(private_kernel_netlink_net_t *this,
751 addr_entry_t *a, addr_entry_t *b, host_t *d)
752 {
753 u_char sa, sb, sd, pa, pb;
754
755 /* rule 2: prefer appropriate scope */
756 if (d)
757 {
758 sa = get_scope(a->ip);
759 sb = get_scope(b->ip);
760 sd = get_scope(d);
761 if (sa < sb)
762 {
763 return sa < sd;
764 }
765 else if (sb < sa)
766 {
767 return sb >= sd;
768 }
769 }
770 if (a->ip->get_family(a->ip) == AF_INET)
771 { /* stop here for IPv4, default to addresses found earlier */
772 return FALSE;
773 }
774 /* rule 3: avoid deprecated addresses (RFC 4862) */
775 if ((a->flags & IFA_F_DEPRECATED) != (b->flags & IFA_F_DEPRECATED))
776 {
777 return a->flags & IFA_F_DEPRECATED;
778 }
779 /* rule 4 is not applicable as we don't know if an address is a home or
780 * care-of addresses.
781 * rule 5 does not apply as we only compare addresses from one interface
782 * rule 6 requires a policy table (optionally configurable) to match
783 * configurable labels
784 */
785 /* rule 7: prefer temporary addresses (WE REVERSE THIS BY DEFAULT!) */
786 if ((a->flags & IFA_F_TEMPORARY) != (b->flags & IFA_F_TEMPORARY))
787 {
788 if (this->prefer_temporary_addrs)
789 {
790 return b->flags & IFA_F_TEMPORARY;
791 }
792 return a->flags & IFA_F_TEMPORARY;
793 }
794 /* rule 8: use longest matching prefix */
795 if (d)
796 {
797 pa = common_prefix(a->ip, d);
798 pb = common_prefix(b->ip, d);
799 if (pa != pb)
800 {
801 return pb > pa;
802 }
803 }
804 /* default to addresses found earlier */
805 return FALSE;
806 }
807
808 /**
809 * Get a non-virtual IP address on the given interface.
810 *
811 * If a candidate address is given, we first search for that address and if not
812 * found return the address as above.
813 * Returned host is a clone, has to be freed by caller.
814 *
815 * this->lock must be held when calling this function.
816 */
817 static host_t *get_interface_address(private_kernel_netlink_net_t *this,
818 int ifindex, int family, host_t *dest,
819 host_t *candidate)
820 {
821 iface_entry_t *iface;
822 enumerator_t *addrs;
823 addr_entry_t *addr, *best = NULL;
824
825 if (this->ifaces->find_first(this->ifaces, (void*)iface_entry_by_index,
826 (void**)&iface, &ifindex) == SUCCESS)
827 {
828 if (iface->usable)
829 { /* only use interfaces not excluded by config */
830 addrs = iface->addrs->create_enumerator(iface->addrs);
831 while (addrs->enumerate(addrs, &addr))
832 {
833 if (addr->refcount ||
834 addr->ip->get_family(addr->ip) != family)
835 { /* ignore virtual IP addresses and ensure family matches */
836 continue;
837 }
838 if (candidate && candidate->ip_equals(candidate, addr->ip))
839 { /* stop if we find the candidate */
840 best = addr;
841 break;
842 }
843 else if (!best || is_address_better(this, best, addr, dest))
844 {
845 best = addr;
846 }
847 }
848 addrs->destroy(addrs);
849 }
850 }
851 return best ? best->ip->clone(best->ip) : NULL;
852 }
853
854 /**
855 * callback function that raises the delayed roam event
856 */
857 static job_requeue_t roam_event(private_kernel_netlink_net_t *this)
858 {
859 bool address;
860
861 this->roam_lock->lock(this->roam_lock);
862 address = this->roam_address;
863 this->roam_address = FALSE;
864 this->roam_lock->unlock(this->roam_lock);
865 hydra->kernel_interface->roam(hydra->kernel_interface, address);
866 return JOB_REQUEUE_NONE;
867 }
868
869 /**
870 * fire a roaming event. we delay it for a bit and fire only one event
871 * for multiple calls. otherwise we would create too many events.
872 */
873 static void fire_roam_event(private_kernel_netlink_net_t *this, bool address)
874 {
875 timeval_t now;
876 job_t *job;
877
878 if (!this->roam_events)
879 {
880 return;
881 }
882
883 time_monotonic(&now);
884 this->roam_lock->lock(this->roam_lock);
885 this->roam_address |= address;
886 if (!timercmp(&now, &this->next_roam, >))
887 {
888 this->roam_lock->unlock(this->roam_lock);
889 return;
890 }
891 timeval_add_ms(&now, ROAM_DELAY);
892 this->next_roam = now;
893 this->roam_lock->unlock(this->roam_lock);
894
895 job = (job_t*)callback_job_create((callback_job_cb_t)roam_event,
896 this, NULL, NULL);
897 lib->scheduler->schedule_job_ms(lib->scheduler, job, ROAM_DELAY);
898 }
899
900 /**
901 * check if an interface with a given index is up and usable
902 *
903 * this->lock must be locked when calling this function
904 */
905 static bool is_interface_up_and_usable(private_kernel_netlink_net_t *this,
906 int index)
907 {
908 iface_entry_t *iface;
909
910 if (this->ifaces->find_first(this->ifaces, (void*)iface_entry_by_index,
911 (void**)&iface, &index) == SUCCESS)
912 {
913 return iface_entry_up_and_usable(iface);
914 }
915 return FALSE;
916 }
917
918 /**
919 * unregister the current addr_entry_t from the hashtable it is stored in
920 *
921 * this->lock must be locked when calling this function
922 */
923 static void addr_entry_unregister(addr_entry_t *addr, iface_entry_t *iface,
924 private_kernel_netlink_net_t *this)
925 {
926 if (addr->refcount)
927 {
928 addr_map_entry_remove(this->vips, addr, iface);
929 this->condvar->broadcast(this->condvar);
930 return;
931 }
932 addr_map_entry_remove(this->addrs, addr, iface);
933 }
934
935 /**
936 * process RTM_NEWLINK/RTM_DELLINK from kernel
937 */
938 static void process_link(private_kernel_netlink_net_t *this,
939 struct nlmsghdr *hdr, bool event)
940 {
941 struct ifinfomsg* msg = NLMSG_DATA(hdr);
942 struct rtattr *rta = IFLA_RTA(msg);
943 size_t rtasize = IFLA_PAYLOAD (hdr);
944 enumerator_t *enumerator;
945 iface_entry_t *current, *entry = NULL;
946 char *name = NULL;
947 bool update = FALSE, update_routes = FALSE;
948
949 while (RTA_OK(rta, rtasize))
950 {
951 switch (rta->rta_type)
952 {
953 case IFLA_IFNAME:
954 name = RTA_DATA(rta);
955 break;
956 }
957 rta = RTA_NEXT(rta, rtasize);
958 }
959 if (!name)
960 {
961 name = "(unknown)";
962 }
963
964 this->lock->write_lock(this->lock);
965 switch (hdr->nlmsg_type)
966 {
967 case RTM_NEWLINK:
968 {
969 if (this->ifaces->find_first(this->ifaces,
970 (void*)iface_entry_by_index, (void**)&entry,
971 &msg->ifi_index) != SUCCESS)
972 {
973 INIT(entry,
974 .ifindex = msg->ifi_index,
975 .addrs = linked_list_create(),
976 .usable = hydra->kernel_interface->is_interface_usable(
977 hydra->kernel_interface, name),
978 );
979 this->ifaces->insert_last(this->ifaces, entry);
980 }
981 strncpy(entry->ifname, name, IFNAMSIZ);
982 entry->ifname[IFNAMSIZ-1] = '\0';
983 if (event && entry->usable)
984 {
985 if (!(entry->flags & IFF_UP) && (msg->ifi_flags & IFF_UP))
986 {
987 update = update_routes = TRUE;
988 DBG1(DBG_KNL, "interface %s activated", name);
989 }
990 if ((entry->flags & IFF_UP) && !(msg->ifi_flags & IFF_UP))
991 {
992 update = TRUE;
993 DBG1(DBG_KNL, "interface %s deactivated", name);
994 }
995 }
996 entry->flags = msg->ifi_flags;
997 break;
998 }
999 case RTM_DELLINK:
1000 {
1001 enumerator = this->ifaces->create_enumerator(this->ifaces);
1002 while (enumerator->enumerate(enumerator, &current))
1003 {
1004 if (current->ifindex == msg->ifi_index)
1005 {
1006 if (event && current->usable)
1007 {
1008 update = TRUE;
1009 DBG1(DBG_KNL, "interface %s deleted", current->ifname);
1010 }
1011 /* TODO: move virtual IPs installed on this interface to
1012 * another interface? */
1013 this->ifaces->remove_at(this->ifaces, enumerator);
1014 current->addrs->invoke_function(current->addrs,
1015 (void*)addr_entry_unregister, current, this);
1016 iface_entry_destroy(current);
1017 break;
1018 }
1019 }
1020 enumerator->destroy(enumerator);
1021 break;
1022 }
1023 }
1024 this->lock->unlock(this->lock);
1025
1026 if (update_routes && event)
1027 {
1028 queue_route_reinstall(this, strdup(name));
1029 }
1030
1031 if (update && event)
1032 {
1033 fire_roam_event(this, TRUE);
1034 }
1035 }
1036
1037 /**
1038 * process RTM_NEWADDR/RTM_DELADDR from kernel
1039 */
1040 static void process_addr(private_kernel_netlink_net_t *this,
1041 struct nlmsghdr *hdr, bool event)
1042 {
1043 struct ifaddrmsg* msg = NLMSG_DATA(hdr);
1044 struct rtattr *rta = IFA_RTA(msg);
1045 size_t rtasize = IFA_PAYLOAD (hdr);
1046 host_t *host = NULL;
1047 iface_entry_t *iface;
1048 chunk_t local = chunk_empty, address = chunk_empty;
1049 char *route_ifname = NULL;
1050 bool update = FALSE, found = FALSE, changed = FALSE;
1051
1052 while (RTA_OK(rta, rtasize))
1053 {
1054 switch (rta->rta_type)
1055 {
1056 case IFA_LOCAL:
1057 local.ptr = RTA_DATA(rta);
1058 local.len = RTA_PAYLOAD(rta);
1059 break;
1060 case IFA_ADDRESS:
1061 address.ptr = RTA_DATA(rta);
1062 address.len = RTA_PAYLOAD(rta);
1063 break;
1064 }
1065 rta = RTA_NEXT(rta, rtasize);
1066 }
1067
1068 /* For PPP interfaces, we need the IFA_LOCAL address,
1069 * IFA_ADDRESS is the peers address. But IFA_LOCAL is
1070 * not included in all cases (IPv6?), so fallback to IFA_ADDRESS. */
1071 if (local.ptr)
1072 {
1073 host = host_create_from_chunk(msg->ifa_family, local, 0);
1074 }
1075 else if (address.ptr)
1076 {
1077 host = host_create_from_chunk(msg->ifa_family, address, 0);
1078 }
1079
1080 if (host == NULL)
1081 { /* bad family? */
1082 return;
1083 }
1084
1085 this->lock->write_lock(this->lock);
1086 if (this->ifaces->find_first(this->ifaces, (void*)iface_entry_by_index,
1087 (void**)&iface, &msg->ifa_index) == SUCCESS)
1088 {
1089 addr_map_entry_t *entry, lookup = {
1090 .ip = host,
1091 .iface = iface,
1092 };
1093 addr_entry_t *addr;
1094
1095 entry = this->vips->get(this->vips, &lookup);
1096 if (entry)
1097 {
1098 if (hdr->nlmsg_type == RTM_NEWADDR)
1099 { /* mark as installed and signal waiting threads */
1100 entry->addr->installed = TRUE;
1101 }
1102 else
1103 { /* the address was already marked as uninstalled */
1104 addr = entry->addr;
1105 iface->addrs->remove(iface->addrs, addr, NULL);
1106 addr_map_entry_remove(this->vips, addr, iface);
1107 addr_entry_destroy(addr);
1108 }
1109 /* no roam events etc. for virtual IPs */
1110 this->condvar->broadcast(this->condvar);
1111 this->lock->unlock(this->lock);
1112 host->destroy(host);
1113 return;
1114 }
1115 entry = this->addrs->get(this->addrs, &lookup);
1116 if (entry)
1117 {
1118 if (hdr->nlmsg_type == RTM_DELADDR)
1119 {
1120 found = TRUE;
1121 addr = entry->addr;
1122 iface->addrs->remove(iface->addrs, addr, NULL);
1123 if (iface->usable)
1124 {
1125 changed = TRUE;
1126 DBG1(DBG_KNL, "%H disappeared from %s", host,
1127 iface->ifname);
1128 }
1129 addr_map_entry_remove(this->addrs, addr, iface);
1130 addr_entry_destroy(addr);
1131 }
1132 }
1133 else
1134 {
1135 if (hdr->nlmsg_type == RTM_NEWADDR)
1136 {
1137 found = TRUE;
1138 changed = TRUE;
1139 route_ifname = strdup(iface->ifname);
1140 INIT(addr,
1141 .ip = host->clone(host),
1142 .flags = msg->ifa_flags,
1143 .scope = msg->ifa_scope,
1144 );
1145 iface->addrs->insert_last(iface->addrs, addr);
1146 addr_map_entry_add(this->addrs, addr, iface);
1147 if (event && iface->usable)
1148 {
1149 DBG1(DBG_KNL, "%H appeared on %s", host, iface->ifname);
1150 }
1151 }
1152 }
1153 if (found && (iface->flags & IFF_UP))
1154 {
1155 update = TRUE;
1156 }
1157 if (!iface->usable)
1158 { /* ignore events for interfaces excluded by config */
1159 update = changed = FALSE;
1160 }
1161 }
1162 this->lock->unlock(this->lock);
1163
1164 if (update && event && route_ifname)
1165 {
1166 queue_route_reinstall(this, route_ifname);
1167 }
1168 else
1169 {
1170 free(route_ifname);
1171 }
1172 host->destroy(host);
1173
1174 /* send an update to all IKE_SAs */
1175 if (update && event && changed)
1176 {
1177 fire_roam_event(this, TRUE);
1178 }
1179 }
1180
1181 /**
1182 * process RTM_NEWROUTE and RTM_DELROUTE from kernel
1183 */
1184 static void process_route(private_kernel_netlink_net_t *this, struct nlmsghdr *hdr)
1185 {
1186 struct rtmsg* msg = NLMSG_DATA(hdr);
1187 struct rtattr *rta = RTM_RTA(msg);
1188 size_t rtasize = RTM_PAYLOAD(hdr);
1189 u_int32_t rta_oif = 0;
1190 host_t *host = NULL;
1191
1192 /* ignore routes added by us or in the local routing table (local addrs) */
1193 if (msg->rtm_table && (msg->rtm_table == this->routing_table ||
1194 msg->rtm_table == RT_TABLE_LOCAL))
1195 {
1196 return;
1197 }
1198 else if (msg->rtm_flags & RTM_F_CLONED)
1199 { /* ignore cached routes, seem to be created a lot for IPv6 */
1200 return;
1201 }
1202
1203 while (RTA_OK(rta, rtasize))
1204 {
1205 switch (rta->rta_type)
1206 {
1207 case RTA_PREFSRC:
1208 DESTROY_IF(host);
1209 host = host_create_from_chunk(msg->rtm_family,
1210 chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta)), 0);
1211 break;
1212 case RTA_OIF:
1213 if (RTA_PAYLOAD(rta) == sizeof(rta_oif))
1214 {
1215 rta_oif = *(u_int32_t*)RTA_DATA(rta);
1216 }
1217 break;
1218 }
1219 rta = RTA_NEXT(rta, rtasize);
1220 }
1221 this->lock->read_lock(this->lock);
1222 if (rta_oif && !is_interface_up_and_usable(this, rta_oif))
1223 { /* ignore route changes for interfaces that are ignored or down */
1224 this->lock->unlock(this->lock);
1225 DESTROY_IF(host);
1226 return;
1227 }
1228 if (!host && rta_oif)
1229 {
1230 host = get_interface_address(this, rta_oif, msg->rtm_family,
1231 NULL, NULL);
1232 }
1233 if (!host || is_known_vip(this, host))
1234 { /* ignore routes added for virtual IPs */
1235 this->lock->unlock(this->lock);
1236 DESTROY_IF(host);
1237 return;
1238 }
1239 this->lock->unlock(this->lock);
1240 fire_roam_event(this, FALSE);
1241 host->destroy(host);
1242 }
1243
1244 /**
1245 * Receives events from kernel
1246 */
1247 static bool receive_events(private_kernel_netlink_net_t *this, int fd,
1248 watcher_event_t event)
1249 {
1250 char response[1536];
1251 struct nlmsghdr *hdr = (struct nlmsghdr*)response;
1252 struct sockaddr_nl addr;
1253 socklen_t addr_len = sizeof(addr);
1254 int len;
1255
1256 len = recvfrom(this->socket_events, response, sizeof(response),
1257 MSG_DONTWAIT, (struct sockaddr*)&addr, &addr_len);
1258 if (len < 0)
1259 {
1260 switch (errno)
1261 {
1262 case EINTR:
1263 /* interrupted, try again */
1264 return TRUE;
1265 case EAGAIN:
1266 /* no data ready, select again */
1267 return TRUE;
1268 default:
1269 DBG1(DBG_KNL, "unable to receive from rt event socket");
1270 sleep(1);
1271 return TRUE;
1272 }
1273 }
1274
1275 if (addr.nl_pid != 0)
1276 { /* not from kernel. not interested, try another one */
1277 return TRUE;
1278 }
1279
1280 while (NLMSG_OK(hdr, len))
1281 {
1282 /* looks good so far, dispatch netlink message */
1283 switch (hdr->nlmsg_type)
1284 {
1285 case RTM_NEWADDR:
1286 case RTM_DELADDR:
1287 process_addr(this, hdr, TRUE);
1288 break;
1289 case RTM_NEWLINK:
1290 case RTM_DELLINK:
1291 process_link(this, hdr, TRUE);
1292 break;
1293 case RTM_NEWROUTE:
1294 case RTM_DELROUTE:
1295 if (this->process_route)
1296 {
1297 process_route(this, hdr);
1298 }
1299 break;
1300 default:
1301 break;
1302 }
1303 hdr = NLMSG_NEXT(hdr, len);
1304 }
1305 return TRUE;
1306 }
1307
1308 /** enumerator over addresses */
1309 typedef struct {
1310 private_kernel_netlink_net_t* this;
1311 /** which addresses to enumerate */
1312 kernel_address_type_t which;
1313 } address_enumerator_t;
1314
1315 /**
1316 * cleanup function for address enumerator
1317 */
1318 static void address_enumerator_destroy(address_enumerator_t *data)
1319 {
1320 data->this->lock->unlock(data->this->lock);
1321 free(data);
1322 }
1323
1324 /**
1325 * filter for addresses
1326 */
1327 static bool filter_addresses(address_enumerator_t *data,
1328 addr_entry_t** in, host_t** out)
1329 {
1330 if (!(data->which & ADDR_TYPE_VIRTUAL) && (*in)->refcount)
1331 { /* skip virtual interfaces added by us */
1332 return FALSE;
1333 }
1334 if (!(data->which & ADDR_TYPE_REGULAR) && !(*in)->refcount)
1335 { /* address is regular, but not requested */
1336 return FALSE;
1337 }
1338 if ((*in)->scope >= RT_SCOPE_LINK)
1339 { /* skip addresses with a unusable scope */
1340 return FALSE;
1341 }
1342 *out = (*in)->ip;
1343 return TRUE;
1344 }
1345
1346 /**
1347 * enumerator constructor for interfaces
1348 */
1349 static enumerator_t *create_iface_enumerator(iface_entry_t *iface,
1350 address_enumerator_t *data)
1351 {
1352 return enumerator_create_filter(
1353 iface->addrs->create_enumerator(iface->addrs),
1354 (void*)filter_addresses, data, NULL);
1355 }
1356
1357 /**
1358 * filter for interfaces
1359 */
1360 static bool filter_interfaces(address_enumerator_t *data, iface_entry_t** in,
1361 iface_entry_t** out)
1362 {
1363 if (!(data->which & ADDR_TYPE_IGNORED) && !(*in)->usable)
1364 { /* skip interfaces excluded by config */
1365 return FALSE;
1366 }
1367 if (!(data->which & ADDR_TYPE_LOOPBACK) && ((*in)->flags & IFF_LOOPBACK))
1368 { /* ignore loopback devices */
1369 return FALSE;
1370 }
1371 if (!(data->which & ADDR_TYPE_DOWN) && !((*in)->flags & IFF_UP))
1372 { /* skip interfaces not up */
1373 return FALSE;
1374 }
1375 *out = *in;
1376 return TRUE;
1377 }
1378
1379 METHOD(kernel_net_t, create_address_enumerator, enumerator_t*,
1380 private_kernel_netlink_net_t *this, kernel_address_type_t which)
1381 {
1382 address_enumerator_t *data;
1383
1384 INIT(data,
1385 .this = this,
1386 .which = which,
1387 );
1388
1389 this->lock->read_lock(this->lock);
1390 return enumerator_create_nested(
1391 enumerator_create_filter(
1392 this->ifaces->create_enumerator(this->ifaces),
1393 (void*)filter_interfaces, data, NULL),
1394 (void*)create_iface_enumerator, data,
1395 (void*)address_enumerator_destroy);
1396 }
1397
1398 METHOD(kernel_net_t, get_interface_name, bool,
1399 private_kernel_netlink_net_t *this, host_t* ip, char **name)
1400 {
1401 addr_map_entry_t *entry, lookup = {
1402 .ip = ip,
1403 };
1404
1405 if (ip->is_anyaddr(ip))
1406 {
1407 return FALSE;
1408 }
1409 this->lock->read_lock(this->lock);
1410 /* first try to find it on an up and usable interface */
1411 entry = this->addrs->get_match(this->addrs, &lookup,
1412 (void*)addr_map_entry_match_up_and_usable);
1413 if (entry)
1414 {
1415 if (name)
1416 {
1417 *name = strdup(entry->iface->ifname);
1418 DBG2(DBG_KNL, "%H is on interface %s", ip, *name);
1419 }
1420 this->lock->unlock(this->lock);
1421 return TRUE;
1422 }
1423 /* in a second step, consider virtual IPs installed by us */
1424 entry = this->vips->get_match(this->vips, &lookup,
1425 (void*)addr_map_entry_match_up_and_usable);
1426 if (entry)
1427 {
1428 if (name)
1429 {
1430 *name = strdup(entry->iface->ifname);
1431 DBG2(DBG_KNL, "virtual IP %H is on interface %s", ip, *name);
1432 }
1433 this->lock->unlock(this->lock);
1434 return TRUE;
1435 }
1436 /* maybe it is installed on an ignored interface */
1437 entry = this->addrs->get_match(this->addrs, &lookup,
1438 (void*)addr_map_entry_match_up);
1439 if (!entry)
1440 {
1441 DBG2(DBG_KNL, "%H is not a local address or the interface is down", ip);
1442 }
1443 this->lock->unlock(this->lock);
1444 return FALSE;
1445 }
1446
1447 /**
1448 * get the index of an interface by name
1449 */
1450 static int get_interface_index(private_kernel_netlink_net_t *this, char* name)
1451 {
1452 iface_entry_t *iface;
1453 int ifindex = 0;
1454
1455 DBG2(DBG_KNL, "getting iface index for %s", name);
1456
1457 this->lock->read_lock(this->lock);
1458 if (this->ifaces->find_first(this->ifaces, (void*)iface_entry_by_name,
1459 (void**)&iface, name) == SUCCESS)
1460 {
1461 ifindex = iface->ifindex;
1462 }
1463 this->lock->unlock(this->lock);
1464
1465 if (ifindex == 0)
1466 {
1467 DBG1(DBG_KNL, "unable to get interface index for %s", name);
1468 }
1469 return ifindex;
1470 }
1471
1472 /**
1473 * check if an address or net (addr with prefix net bits) is in
1474 * subnet (net with net_len net bits)
1475 */
1476 static bool addr_in_subnet(chunk_t addr, int prefix, chunk_t net, int net_len)
1477 {
1478 static const u_char mask[] = { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
1479 int byte = 0;
1480
1481 if (net_len == 0)
1482 { /* any address matches a /0 network */
1483 return TRUE;
1484 }
1485 if (addr.len != net.len || net_len > 8 * net.len || prefix < net_len)
1486 {
1487 return FALSE;
1488 }
1489 /* scan through all bytes in network order */
1490 while (net_len > 0)
1491 {
1492 if (net_len < 8)
1493 {
1494 return (mask[net_len] & addr.ptr[byte]) == (mask[net_len] & net.ptr[byte]);
1495 }
1496 else
1497 {
1498 if (addr.ptr[byte] != net.ptr[byte])
1499 {
1500 return FALSE;
1501 }
1502 byte++;
1503 net_len -= 8;
1504 }
1505 }
1506 return TRUE;
1507 }
1508
1509 /**
1510 * Store information about a route retrieved via RTNETLINK
1511 */
1512 typedef struct {
1513 chunk_t gtw;
1514 chunk_t src;
1515 chunk_t dst;
1516 host_t *src_host;
1517 u_int8_t dst_len;
1518 u_int32_t table;
1519 u_int32_t oif;
1520 } rt_entry_t;
1521
1522 /**
1523 * Free a route entry
1524 */
1525 static void rt_entry_destroy(rt_entry_t *this)
1526 {
1527 DESTROY_IF(this->src_host);
1528 free(this);
1529 }
1530
1531 /**
1532 * Parse route received with RTM_NEWROUTE. The given rt_entry_t object will be
1533 * reused if not NULL.
1534 *
1535 * Returned chunks point to internal data of the Netlink message.
1536 */
1537 static rt_entry_t *parse_route(struct nlmsghdr *hdr, rt_entry_t *route)
1538 {
1539 struct rtattr *rta;
1540 struct rtmsg *msg;
1541 size_t rtasize;
1542
1543 msg = NLMSG_DATA(hdr);
1544 rta = RTM_RTA(msg);
1545 rtasize = RTM_PAYLOAD(hdr);
1546
1547 if (route)
1548 {
1549 route->gtw = chunk_empty;
1550 route->src = chunk_empty;
1551 route->dst = chunk_empty;
1552 route->dst_len = msg->rtm_dst_len;
1553 route->table = msg->rtm_table;
1554 route->oif = 0;
1555 }
1556 else
1557 {
1558 INIT(route,
1559 .dst_len = msg->rtm_dst_len,
1560 .table = msg->rtm_table,
1561 );
1562 }
1563
1564 while (RTA_OK(rta, rtasize))
1565 {
1566 switch (rta->rta_type)
1567 {
1568 case RTA_PREFSRC:
1569 route->src = chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta));
1570 break;
1571 case RTA_GATEWAY:
1572 route->gtw = chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta));
1573 break;
1574 case RTA_DST:
1575 route->dst = chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta));
1576 break;
1577 case RTA_OIF:
1578 if (RTA_PAYLOAD(rta) == sizeof(route->oif))
1579 {
1580 route->oif = *(u_int32_t*)RTA_DATA(rta);
1581 }
1582 break;
1583 #ifdef HAVE_RTA_TABLE
1584 case RTA_TABLE:
1585 if (RTA_PAYLOAD(rta) == sizeof(route->table))
1586 {
1587 route->table = *(u_int32_t*)RTA_DATA(rta);
1588 }
1589 break;
1590 #endif /* HAVE_RTA_TABLE*/
1591 }
1592 rta = RTA_NEXT(rta, rtasize);
1593 }
1594 return route;
1595 }
1596
1597 /**
1598 * Get a route: If "nexthop", the nexthop is returned. source addr otherwise.
1599 */
1600 static host_t *get_route(private_kernel_netlink_net_t *this, host_t *dest,
1601 int prefix, bool nexthop, host_t *candidate,
1602 u_int recursion)
1603 {
1604 netlink_buf_t request;
1605 struct nlmsghdr *hdr, *out, *current;
1606 struct rtmsg *msg;
1607 chunk_t chunk;
1608 size_t len;
1609 linked_list_t *routes;
1610 rt_entry_t *route = NULL, *best = NULL;
1611 enumerator_t *enumerator;
1612 host_t *addr = NULL;
1613 bool match_net;
1614 int family;
1615
1616 if (recursion > MAX_ROUTE_RECURSION)
1617 {
1618 return NULL;
1619 }
1620 chunk = dest->get_address(dest);
1621 len = chunk.len * 8;
1622 prefix = prefix < 0 ? len : min(prefix, len);
1623 match_net = prefix != len;
1624
1625 memset(&request, 0, sizeof(request));
1626
1627 family = dest->get_family(dest);
1628 hdr = &request.hdr;
1629 hdr->nlmsg_flags = NLM_F_REQUEST;
1630 if (family == AF_INET || this->rta_prefsrc_for_ipv6 ||
1631 this->routing_table || match_net)
1632 { /* kernels prior to 3.0 do not support RTA_PREFSRC for IPv6 routes.
1633 * as we want to ignore routes with virtual IPs we cannot use DUMP
1634 * if these routes are not installed in a separate table */
1635 hdr->nlmsg_flags |= NLM_F_DUMP;
1636 }
1637 hdr->nlmsg_type = RTM_GETROUTE;
1638 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
1639
1640 msg = NLMSG_DATA(hdr);
1641 msg->rtm_family = family;
1642 if (candidate)
1643 {
1644 chunk = candidate->get_address(candidate);
1645 netlink_add_attribute(hdr, RTA_PREFSRC, chunk, sizeof(request));
1646 }
1647 if (!match_net)
1648 {
1649 chunk = dest->get_address(dest);
1650 netlink_add_attribute(hdr, RTA_DST, chunk, sizeof(request));
1651 }
1652
1653 if (this->socket->send(this->socket, hdr, &out, &len) != SUCCESS)
1654 {
1655 DBG2(DBG_KNL, "getting %s to reach %H/%d failed",
1656 nexthop ? "nexthop" : "address", dest, prefix);
1657 return NULL;
1658 }
1659 routes = linked_list_create();
1660 this->lock->read_lock(this->lock);
1661
1662 for (current = out; NLMSG_OK(current, len);
1663 current = NLMSG_NEXT(current, len))
1664 {
1665 switch (current->nlmsg_type)
1666 {
1667 case NLMSG_DONE:
1668 break;
1669 case RTM_NEWROUTE:
1670 {
1671 rt_entry_t *other;
1672 uintptr_t table;
1673
1674 route = parse_route(current, route);
1675
1676 table = (uintptr_t)route->table;
1677 if (this->rt_exclude->find_first(this->rt_exclude, NULL,
1678 (void**)&table) == SUCCESS)
1679 { /* route is from an excluded routing table */
1680 continue;
1681 }
1682 if (this->routing_table != 0 &&
1683 route->table == this->routing_table)
1684 { /* route is from our own ipsec routing table */
1685 continue;
1686 }
1687 if (route->oif && !is_interface_up_and_usable(this, route->oif))
1688 { /* interface is down */
1689 continue;
1690 }
1691 if (!addr_in_subnet(chunk, prefix, route->dst, route->dst_len))
1692 { /* route destination does not contain dest */
1693 continue;
1694 }
1695 if (route->src.ptr)
1696 { /* verify source address, if any */
1697 host_t *src = host_create_from_chunk(msg->rtm_family,
1698 route->src, 0);
1699 if (src && is_known_vip(this, src))
1700 { /* ignore routes installed by us */
1701 src->destroy(src);
1702 continue;
1703 }
1704 route->src_host = src;
1705 }
1706 /* insert route, sorted by decreasing network prefix */
1707 enumerator = routes->create_enumerator(routes);
1708 while (enumerator->enumerate(enumerator, &other))
1709 {
1710 if (route->dst_len > other->dst_len)
1711 {
1712 break;
1713 }
1714 }
1715 routes->insert_before(routes, enumerator, route);
1716 enumerator->destroy(enumerator);
1717 route = NULL;
1718 continue;
1719 }
1720 default:
1721 continue;
1722 }
1723 break;
1724 }
1725 if (route)
1726 {
1727 rt_entry_destroy(route);
1728 }
1729
1730 /* now we have a list of routes matching dest, sorted by net prefix.
1731 * we will look for source addresses for these routes and select the one
1732 * with the preferred source address, if possible */
1733 enumerator = routes->create_enumerator(routes);
1734 while (enumerator->enumerate(enumerator, &route))
1735 {
1736 if (route->src_host)
1737 { /* got a source address with the route, if no preferred source
1738 * is given or it matches we are done, as this is the best route */
1739 if (!candidate || candidate->ip_equals(candidate, route->src_host))
1740 {
1741 best = route;
1742 break;
1743 }
1744 else if (route->oif)
1745 { /* no match yet, maybe it is assigned to the same interface */
1746 host_t *src = get_interface_address(this, route->oif,
1747 msg->rtm_family, dest, candidate);
1748 if (src && src->ip_equals(src, candidate))
1749 {
1750 route->src_host->destroy(route->src_host);
1751 route->src_host = src;
1752 best = route;
1753 break;
1754 }
1755 DESTROY_IF(src);
1756 }
1757 /* no luck yet with the source address. if this is the best (first)
1758 * route we store it as fallback in case we don't find a route with
1759 * the preferred source */
1760 best = best ?: route;
1761 continue;
1762 }
1763 if (route->oif)
1764 { /* no src, but an interface - get address from it */
1765 route->src_host = get_interface_address(this, route->oif,
1766 msg->rtm_family, dest, candidate);
1767 if (route->src_host)
1768 { /* we handle this address the same as the one above */
1769 if (!candidate ||
1770 candidate->ip_equals(candidate, route->src_host))
1771 {
1772 best = route;
1773 break;
1774 }
1775 best = best ?: route;
1776 continue;
1777 }
1778 }
1779 if (route->gtw.ptr)
1780 { /* no src, no iface, but a gateway - lookup src to reach gtw */
1781 host_t *gtw;
1782
1783 gtw = host_create_from_chunk(msg->rtm_family, route->gtw, 0);
1784 if (gtw && !gtw->ip_equals(gtw, dest))
1785 {
1786 route->src_host = get_route(this, gtw, -1, FALSE, candidate,
1787 recursion + 1);
1788 }
1789 DESTROY_IF(gtw);
1790 if (route->src_host)
1791 { /* more of the same */
1792 if (!candidate ||
1793 candidate->ip_equals(candidate, route->src_host))
1794 {
1795 best = route;
1796 break;
1797 }
1798 best = best ?: route;
1799 }
1800 }
1801 }
1802 enumerator->destroy(enumerator);
1803
1804 if (nexthop)
1805 { /* nexthop lookup, return gateway if any */
1806 if (best || routes->get_first(routes, (void**)&best) == SUCCESS)
1807 {
1808 addr = host_create_from_chunk(msg->rtm_family, best->gtw, 0);
1809 }
1810 if (!addr && !match_net)
1811 { /* fallback to destination address */
1812 addr = dest->clone(dest);
1813 }
1814 }
1815 else
1816 {
1817 if (best)
1818 {
1819 addr = best->src_host->clone(best->src_host);
1820 }
1821 }
1822 this->lock->unlock(this->lock);
1823 routes->destroy_function(routes, (void*)rt_entry_destroy);
1824 free(out);
1825
1826 if (addr)
1827 {
1828 DBG2(DBG_KNL, "using %H as %s to reach %H/%d", addr,
1829 nexthop ? "nexthop" : "address", dest, prefix);
1830 }
1831 else if (!recursion)
1832 {
1833 DBG2(DBG_KNL, "no %s found to reach %H/%d",
1834 nexthop ? "nexthop" : "address", dest, prefix);
1835 }
1836 return addr;
1837 }
1838
1839 METHOD(kernel_net_t, get_source_addr, host_t*,
1840 private_kernel_netlink_net_t *this, host_t *dest, host_t *src)
1841 {
1842 return get_route(this, dest, -1, FALSE, src, 0);
1843 }
1844
1845 METHOD(kernel_net_t, get_nexthop, host_t*,
1846 private_kernel_netlink_net_t *this, host_t *dest, int prefix, host_t *src)
1847 {
1848 return get_route(this, dest, prefix, TRUE, src, 0);
1849 }
1850
1851 /**
1852 * Manages the creation and deletion of ip addresses on an interface.
1853 * By setting the appropriate nlmsg_type, the ip will be set or unset.
1854 */
1855 static status_t manage_ipaddr(private_kernel_netlink_net_t *this, int nlmsg_type,
1856 int flags, int if_index, host_t *ip, int prefix)
1857 {
1858 netlink_buf_t request;
1859 struct nlmsghdr *hdr;
1860 struct ifaddrmsg *msg;
1861 chunk_t chunk;
1862
1863 memset(&request, 0, sizeof(request));
1864
1865 chunk = ip->get_address(ip);
1866
1867 hdr = &request.hdr;
1868 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
1869 hdr->nlmsg_type = nlmsg_type;
1870 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg));
1871
1872 msg = NLMSG_DATA(hdr);
1873 msg->ifa_family = ip->get_family(ip);
1874 msg->ifa_flags = 0;
1875 msg->ifa_prefixlen = prefix < 0 ? chunk.len * 8 : prefix;
1876 msg->ifa_scope = RT_SCOPE_UNIVERSE;
1877 msg->ifa_index = if_index;
1878
1879 netlink_add_attribute(hdr, IFA_LOCAL, chunk, sizeof(request));
1880
1881 if (ip->get_family(ip) == AF_INET6 && this->rta_prefsrc_for_ipv6)
1882 { /* if source routes are possible we let the virtual IP get deprecated
1883 * immediately (but mark it as valid forever) so it gets only used if
1884 * forced by our route, and not by the default IPv6 address selection */
1885 struct ifa_cacheinfo cache = {
1886 .ifa_valid = 0xFFFFFFFF,
1887 .ifa_prefered = 0,
1888 };
1889 netlink_add_attribute(hdr, IFA_CACHEINFO, chunk_from_thing(cache),
1890 sizeof(request));
1891 }
1892 return this->socket->send_ack(this->socket, hdr);
1893 }
1894
1895 METHOD(kernel_net_t, add_ip, status_t,
1896 private_kernel_netlink_net_t *this, host_t *virtual_ip, int prefix,
1897 char *iface_name)
1898 {
1899 addr_map_entry_t *entry, lookup = {
1900 .ip = virtual_ip,
1901 };
1902 iface_entry_t *iface = NULL;
1903
1904 if (!this->install_virtual_ip)
1905 { /* disabled by config */
1906 return SUCCESS;
1907 }
1908
1909 this->lock->write_lock(this->lock);
1910 /* the virtual IP might actually be installed as regular IP, in which case
1911 * we don't track it as virtual IP */
1912 entry = this->addrs->get_match(this->addrs, &lookup,
1913 (void*)addr_map_entry_match);
1914 if (!entry)
1915 { /* otherwise it might already be installed as virtual IP */
1916 entry = this->vips->get_match(this->vips, &lookup,
1917 (void*)addr_map_entry_match);
1918 if (entry)
1919 { /* the vip we found can be in one of three states: 1) installed and
1920 * ready, 2) just added by another thread, but not yet confirmed to
1921 * be installed by the kernel, 3) just deleted, but not yet gone.
1922 * Then while we wait below, several things could happen (as we
1923 * release the lock). For instance, the interface could disappear,
1924 * or the IP is finally deleted, and it reappears on a different
1925 * interface. All these cases are handled by the call below. */
1926 while (!is_vip_installed_or_gone(this, virtual_ip, &entry))
1927 {
1928 this->condvar->wait(this->condvar, this->lock);
1929 }
1930 if (entry)
1931 {
1932 entry->addr->refcount++;
1933 }
1934 }
1935 }
1936 if (entry)
1937 {
1938 DBG2(DBG_KNL, "virtual IP %H is already installed on %s", virtual_ip,
1939 entry->iface->ifname);
1940 this->lock->unlock(this->lock);
1941 return SUCCESS;
1942 }
1943 /* try to find the target interface, either by config or via src ip */
1944 if (!this->install_virtual_ip_on ||
1945 this->ifaces->find_first(this->ifaces, (void*)iface_entry_by_name,
1946 (void**)&iface, this->install_virtual_ip_on) != SUCCESS)
1947 {
1948 if (this->ifaces->find_first(this->ifaces, (void*)iface_entry_by_name,
1949 (void**)&iface, iface_name) != SUCCESS)
1950 { /* if we don't find the requested interface we just use the first */
1951 this->ifaces->get_first(this->ifaces, (void**)&iface);
1952 }
1953 }
1954 if (iface)
1955 {
1956 addr_entry_t *addr;
1957
1958 INIT(addr,
1959 .ip = virtual_ip->clone(virtual_ip),
1960 .refcount = 1,
1961 .scope = RT_SCOPE_UNIVERSE,
1962 );
1963 iface->addrs->insert_last(iface->addrs, addr);
1964 addr_map_entry_add(this->vips, addr, iface);
1965 if (manage_ipaddr(this, RTM_NEWADDR, NLM_F_CREATE | NLM_F_EXCL,
1966 iface->ifindex, virtual_ip, prefix) == SUCCESS)
1967 {
1968 while (!is_vip_installed_or_gone(this, virtual_ip, &entry))
1969 { /* wait until address appears */
1970 this->condvar->wait(this->condvar, this->lock);
1971 }
1972 if (entry)
1973 { /* we fail if the interface got deleted in the meantime */
1974 DBG2(DBG_KNL, "virtual IP %H installed on %s", virtual_ip,
1975 entry->iface->ifname);
1976 this->lock->unlock(this->lock);
1977 /* during IKEv1 reauthentication, children get moved from
1978 * old the new SA before the virtual IP is available. This
1979 * kills the route for our virtual IP, reinstall. */
1980 queue_route_reinstall(this, strdup(entry->iface->ifname));
1981 return SUCCESS;
1982 }
1983 }
1984 this->lock->unlock(this->lock);
1985 DBG1(DBG_KNL, "adding virtual IP %H failed", virtual_ip);
1986 return FAILED;
1987 }
1988 this->lock->unlock(this->lock);
1989 DBG1(DBG_KNL, "no interface available, unable to install virtual IP %H",
1990 virtual_ip);
1991 return FAILED;
1992 }
1993
1994 METHOD(kernel_net_t, del_ip, status_t,
1995 private_kernel_netlink_net_t *this, host_t *virtual_ip, int prefix,
1996 bool wait)
1997 {
1998 addr_map_entry_t *entry, lookup = {
1999 .ip = virtual_ip,
2000 };
2001
2002 if (!this->install_virtual_ip)
2003 { /* disabled by config */
2004 return SUCCESS;
2005 }
2006
2007 DBG2(DBG_KNL, "deleting virtual IP %H", virtual_ip);
2008
2009 this->lock->write_lock(this->lock);
2010 entry = this->vips->get_match(this->vips, &lookup,
2011 (void*)addr_map_entry_match);
2012 if (!entry)
2013 { /* we didn't install this IP as virtual IP */
2014 entry = this->addrs->get_match(this->addrs, &lookup,
2015 (void*)addr_map_entry_match);
2016 if (entry)
2017 {
2018 DBG2(DBG_KNL, "not deleting existing IP %H on %s", virtual_ip,
2019 entry->iface->ifname);
2020 this->lock->unlock(this->lock);
2021 return SUCCESS;
2022 }
2023 DBG2(DBG_KNL, "virtual IP %H not cached, unable to delete", virtual_ip);
2024 this->lock->unlock(this->lock);
2025 return FAILED;
2026 }
2027 if (entry->addr->refcount == 1)
2028 {
2029 status_t status;
2030
2031 /* we set this flag so that threads calling add_ip will block and wait
2032 * until the entry is gone, also so we can wait below */
2033 entry->addr->installed = FALSE;
2034 status = manage_ipaddr(this, RTM_DELADDR, 0, entry->iface->ifindex,
2035 virtual_ip, prefix);
2036 if (status == SUCCESS && wait)
2037 { /* wait until the address is really gone */
2038 while (is_known_vip(this, virtual_ip))
2039 {
2040 this->condvar->wait(this->condvar, this->lock);
2041 }
2042 }
2043 this->lock->unlock(this->lock);
2044 return status;
2045 }
2046 else
2047 {
2048 entry->addr->refcount--;
2049 }
2050 DBG2(DBG_KNL, "virtual IP %H used by other SAs, not deleting",
2051 virtual_ip);
2052 this->lock->unlock(this->lock);
2053 return SUCCESS;
2054 }
2055
2056 /**
2057 * Manages source routes in the routing table.
2058 * By setting the appropriate nlmsg_type, the route gets added or removed.
2059 */
2060 static status_t manage_srcroute(private_kernel_netlink_net_t *this,
2061 int nlmsg_type, int flags, chunk_t dst_net,
2062 u_int8_t prefixlen, host_t *gateway,
2063 host_t *src_ip, char *if_name)
2064 {
2065 netlink_buf_t request;
2066 struct nlmsghdr *hdr;
2067 struct rtmsg *msg;
2068 struct rtattr *rta;
2069 int ifindex;
2070 chunk_t chunk;
2071
2072 /* if route is 0.0.0.0/0, we can't install it, as it would
2073 * overwrite the default route. Instead, we add two routes:
2074 * 0.0.0.0/1 and 128.0.0.0/1 */
2075 if (this->routing_table == 0 && prefixlen == 0)
2076 {
2077 chunk_t half_net;
2078 u_int8_t half_prefixlen;
2079 status_t status;
2080
2081 half_net = chunk_alloca(dst_net.len);
2082 memset(half_net.ptr, 0, half_net.len);
2083 half_prefixlen = 1;
2084
2085 status = manage_srcroute(this, nlmsg_type, flags, half_net, half_prefixlen,
2086 gateway, src_ip, if_name);
2087 half_net.ptr[0] |= 0x80;
2088 status = manage_srcroute(this, nlmsg_type, flags, half_net, half_prefixlen,
2089 gateway, src_ip, if_name);
2090 return status;
2091 }
2092
2093 memset(&request, 0, sizeof(request));
2094
2095 hdr = &request.hdr;
2096 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
2097 hdr->nlmsg_type = nlmsg_type;
2098 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
2099
2100 msg = NLMSG_DATA(hdr);
2101 msg->rtm_family = src_ip->get_family(src_ip);
2102 msg->rtm_dst_len = prefixlen;
2103 msg->rtm_table = this->routing_table;
2104 msg->rtm_protocol = RTPROT_STATIC;
2105 msg->rtm_type = RTN_UNICAST;
2106 msg->rtm_scope = RT_SCOPE_UNIVERSE;
2107
2108 netlink_add_attribute(hdr, RTA_DST, dst_net, sizeof(request));
2109 chunk = src_ip->get_address(src_ip);
2110 netlink_add_attribute(hdr, RTA_PREFSRC, chunk, sizeof(request));
2111 if (gateway && gateway->get_family(gateway) == src_ip->get_family(src_ip))
2112 {
2113 chunk = gateway->get_address(gateway);
2114 netlink_add_attribute(hdr, RTA_GATEWAY, chunk, sizeof(request));
2115 }
2116 ifindex = get_interface_index(this, if_name);
2117 chunk.ptr = (char*)&ifindex;
2118 chunk.len = sizeof(ifindex);
2119 netlink_add_attribute(hdr, RTA_OIF, chunk, sizeof(request));
2120
2121 if (this->mtu || this->mss)
2122 {
2123 chunk = chunk_alloca(RTA_LENGTH((sizeof(struct rtattr) +
2124 sizeof(u_int32_t)) * 2));
2125 chunk.len = 0;
2126 rta = (struct rtattr*)chunk.ptr;
2127 if (this->mtu)
2128 {
2129 rta->rta_type = RTAX_MTU;
2130 rta->rta_len = RTA_LENGTH(sizeof(u_int32_t));
2131 memcpy(RTA_DATA(rta), &this->mtu, sizeof(u_int32_t));
2132 chunk.len = rta->rta_len;
2133 }
2134 if (this->mss)
2135 {
2136 rta = (struct rtattr*)(chunk.ptr + RTA_ALIGN(chunk.len));
2137 rta->rta_type = RTAX_ADVMSS;
2138 rta->rta_len = RTA_LENGTH(sizeof(u_int32_t));
2139 memcpy(RTA_DATA(rta), &this->mss, sizeof(u_int32_t));
2140 chunk.len = RTA_ALIGN(chunk.len) + rta->rta_len;
2141 }
2142 netlink_add_attribute(hdr, RTA_METRICS, chunk, sizeof(request));
2143 }
2144
2145 return this->socket->send_ack(this->socket, hdr);
2146 }
2147
2148 METHOD(kernel_net_t, add_route, status_t,
2149 private_kernel_netlink_net_t *this, chunk_t dst_net, u_int8_t prefixlen,
2150 host_t *gateway, host_t *src_ip, char *if_name)
2151 {
2152 status_t status;
2153 route_entry_t *found, route = {
2154 .dst_net = dst_net,
2155 .prefixlen = prefixlen,
2156 .gateway = gateway,
2157 .src_ip = src_ip,
2158 .if_name = if_name,
2159 };
2160
2161 this->routes_lock->lock(this->routes_lock);
2162 found = this->routes->get(this->routes, &route);
2163 if (found)
2164 {
2165 this->routes_lock->unlock(this->routes_lock);
2166 return ALREADY_DONE;
2167 }
2168 status = manage_srcroute(this, RTM_NEWROUTE, NLM_F_CREATE | NLM_F_EXCL,
2169 dst_net, prefixlen, gateway, src_ip, if_name);
2170 if (status == SUCCESS)
2171 {
2172 found = route_entry_clone(&route);
2173 this->routes->put(this->routes, found, found);
2174 }
2175 this->routes_lock->unlock(this->routes_lock);
2176 return status;
2177 }
2178
2179 METHOD(kernel_net_t, del_route, status_t,
2180 private_kernel_netlink_net_t *this, chunk_t dst_net, u_int8_t prefixlen,
2181 host_t *gateway, host_t *src_ip, char *if_name)
2182 {
2183 status_t status;
2184 route_entry_t *found, route = {
2185 .dst_net = dst_net,
2186 .prefixlen = prefixlen,
2187 .gateway = gateway,
2188 .src_ip = src_ip,
2189 .if_name = if_name,
2190 };
2191
2192 this->routes_lock->lock(this->routes_lock);
2193 found = this->routes->get(this->routes, &route);
2194 if (!found)
2195 {
2196 this->routes_lock->unlock(this->routes_lock);
2197 return NOT_FOUND;
2198 }
2199 this->routes->remove(this->routes, found);
2200 route_entry_destroy(found);
2201 status = manage_srcroute(this, RTM_DELROUTE, 0, dst_net, prefixlen,
2202 gateway, src_ip, if_name);
2203 this->routes_lock->unlock(this->routes_lock);
2204 return status;
2205 }
2206
2207 /**
2208 * Initialize a list of local addresses.
2209 */
2210 static status_t init_address_list(private_kernel_netlink_net_t *this)
2211 {
2212 netlink_buf_t request;
2213 struct nlmsghdr *out, *current, *in;
2214 struct rtgenmsg *msg;
2215 size_t len;
2216 enumerator_t *ifaces, *addrs;
2217 iface_entry_t *iface;
2218 addr_entry_t *addr;
2219
2220 DBG2(DBG_KNL, "known interfaces and IP addresses:");
2221
2222 memset(&request, 0, sizeof(request));
2223
2224 in = &request.hdr;
2225 in->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg));
2226 in->nlmsg_flags = NLM_F_REQUEST | NLM_F_MATCH | NLM_F_ROOT;
2227 msg = NLMSG_DATA(in);
2228 msg->rtgen_family = AF_UNSPEC;
2229
2230 /* get all links */
2231 in->nlmsg_type = RTM_GETLINK;
2232 if (this->socket->send(this->socket, in, &out, &len) != SUCCESS)
2233 {
2234 return FAILED;
2235 }
2236 current = out;
2237 while (NLMSG_OK(current, len))
2238 {
2239 switch (current->nlmsg_type)
2240 {
2241 case NLMSG_DONE:
2242 break;
2243 case RTM_NEWLINK:
2244 process_link(this, current, FALSE);
2245 /* fall through */
2246 default:
2247 current = NLMSG_NEXT(current, len);
2248 continue;
2249 }
2250 break;
2251 }
2252 free(out);
2253
2254 /* get all interface addresses */
2255 in->nlmsg_type = RTM_GETADDR;
2256 if (this->socket->send(this->socket, in, &out, &len) != SUCCESS)
2257 {
2258 return FAILED;
2259 }
2260 current = out;
2261 while (NLMSG_OK(current, len))
2262 {
2263 switch (current->nlmsg_type)
2264 {
2265 case NLMSG_DONE:
2266 break;
2267 case RTM_NEWADDR:
2268 process_addr(this, current, FALSE);
2269 /* fall through */
2270 default:
2271 current = NLMSG_NEXT(current, len);
2272 continue;
2273 }
2274 break;
2275 }
2276 free(out);
2277
2278 this->lock->read_lock(this->lock);
2279 ifaces = this->ifaces->create_enumerator(this->ifaces);
2280 while (ifaces->enumerate(ifaces, &iface))
2281 {
2282 if (iface_entry_up_and_usable(iface))
2283 {
2284 DBG2(DBG_KNL, " %s", iface->ifname);
2285 addrs = iface->addrs->create_enumerator(iface->addrs);
2286 while (addrs->enumerate(addrs, (void**)&addr))
2287 {
2288 DBG2(DBG_KNL, " %H", addr->ip);
2289 }
2290 addrs->destroy(addrs);
2291 }
2292 }
2293 ifaces->destroy(ifaces);
2294 this->lock->unlock(this->lock);
2295 return SUCCESS;
2296 }
2297
2298 /**
2299 * create or delete a rule to use our routing table
2300 */
2301 static status_t manage_rule(private_kernel_netlink_net_t *this, int nlmsg_type,
2302 int family, u_int32_t table, u_int32_t prio)
2303 {
2304 netlink_buf_t request;
2305 struct nlmsghdr *hdr;
2306 struct rtmsg *msg;
2307 chunk_t chunk;
2308 char *fwmark;
2309
2310 memset(&request, 0, sizeof(request));
2311 hdr = &request.hdr;
2312 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2313 hdr->nlmsg_type = nlmsg_type;
2314 if (nlmsg_type == RTM_NEWRULE)
2315 {
2316 hdr->nlmsg_flags |= NLM_F_CREATE | NLM_F_EXCL;
2317 }
2318 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
2319
2320 msg = NLMSG_DATA(hdr);
2321 msg->rtm_table = table;
2322 msg->rtm_family = family;
2323 msg->rtm_protocol = RTPROT_BOOT;
2324 msg->rtm_scope = RT_SCOPE_UNIVERSE;
2325 msg->rtm_type = RTN_UNICAST;
2326
2327 chunk = chunk_from_thing(prio);
2328 netlink_add_attribute(hdr, RTA_PRIORITY, chunk, sizeof(request));
2329
2330 fwmark = lib->settings->get_str(lib->settings,
2331 "%s.plugins.kernel-netlink.fwmark", NULL, lib->ns);
2332 if (fwmark)
2333 {
2334 #ifdef HAVE_LINUX_FIB_RULES_H
2335 mark_t mark;
2336
2337 if (fwmark[0] == '!')
2338 {
2339 msg->rtm_flags |= FIB_RULE_INVERT;
2340 fwmark++;
2341 }
2342 if (mark_from_string(fwmark, &mark))
2343 {
2344 chunk = chunk_from_thing(mark.value);
2345 netlink_add_attribute(hdr, FRA_FWMARK, chunk, sizeof(request));
2346 chunk = chunk_from_thing(mark.mask);
2347 netlink_add_attribute(hdr, FRA_FWMASK, chunk, sizeof(request));
2348 }
2349 #else
2350 DBG1(DBG_KNL, "setting firewall mark on routing rule is not supported");
2351 #endif
2352 }
2353 return this->socket->send_ack(this->socket, hdr);
2354 }
2355
2356 /**
2357 * check for kernel features (currently only via version number)
2358 */
2359 static void check_kernel_features(private_kernel_netlink_net_t *this)
2360 {
2361 struct utsname utsname;
2362 int a, b, c;
2363
2364 if (uname(&utsname) == 0)
2365 {
2366 switch(sscanf(utsname.release, "%d.%d.%d", &a, &b, &c))
2367 {
2368 case 3:
2369 if (a == 2)
2370 {
2371 DBG2(DBG_KNL, "detected Linux %d.%d.%d, no support for "
2372 "RTA_PREFSRC for IPv6 routes", a, b, c);
2373 break;
2374 }
2375 /* fall-through */
2376 case 2:
2377 /* only 3.x+ uses two part version numbers */
2378 this->rta_prefsrc_for_ipv6 = TRUE;
2379 break;
2380 default:
2381 break;
2382 }
2383 }
2384 }
2385
2386 /**
2387 * Destroy an address to iface map
2388 */
2389 static void addr_map_destroy(hashtable_t *map)
2390 {
2391 enumerator_t *enumerator;
2392 addr_map_entry_t *addr;
2393
2394 enumerator = map->create_enumerator(map);
2395 while (enumerator->enumerate(enumerator, NULL, (void**)&addr))
2396 {
2397 free(addr);
2398 }
2399 enumerator->destroy(enumerator);
2400 map->destroy(map);
2401 }
2402
2403 METHOD(kernel_net_t, destroy, void,
2404 private_kernel_netlink_net_t *this)
2405 {
2406 enumerator_t *enumerator;
2407 route_entry_t *route;
2408
2409 if (this->routing_table)
2410 {
2411 manage_rule(this, RTM_DELRULE, AF_INET, this->routing_table,
2412 this->routing_table_prio);
2413 manage_rule(this, RTM_DELRULE, AF_INET6, this->routing_table,
2414 this->routing_table_prio);
2415 }
2416 if (this->socket_events > 0)
2417 {
2418 lib->watcher->remove(lib->watcher, this->socket_events);
2419 close(this->socket_events);
2420 }
2421 enumerator = this->routes->create_enumerator(this->routes);
2422 while (enumerator->enumerate(enumerator, NULL, (void**)&route))
2423 {
2424 manage_srcroute(this, RTM_DELROUTE, 0, route->dst_net, route->prefixlen,
2425 route->gateway, route->src_ip, route->if_name);
2426 route_entry_destroy(route);
2427 }
2428 enumerator->destroy(enumerator);
2429 this->routes->destroy(this->routes);
2430 this->routes_lock->destroy(this->routes_lock);
2431 DESTROY_IF(this->socket);
2432
2433 net_changes_clear(this);
2434 this->net_changes->destroy(this->net_changes);
2435 this->net_changes_lock->destroy(this->net_changes_lock);
2436
2437 addr_map_destroy(this->addrs);
2438 addr_map_destroy(this->vips);
2439
2440 this->ifaces->destroy_function(this->ifaces, (void*)iface_entry_destroy);
2441 this->rt_exclude->destroy(this->rt_exclude);
2442 this->roam_lock->destroy(this->roam_lock);
2443 this->condvar->destroy(this->condvar);
2444 this->lock->destroy(this->lock);
2445 free(this);
2446 }
2447
2448 /*
2449 * Described in header.
2450 */
2451 kernel_netlink_net_t *kernel_netlink_net_create()
2452 {
2453 private_kernel_netlink_net_t *this;
2454 enumerator_t *enumerator;
2455 bool register_for_events = TRUE;
2456 char *exclude;
2457
2458 INIT(this,
2459 .public = {
2460 .interface = {
2461 .get_interface = _get_interface_name,
2462 .create_address_enumerator = _create_address_enumerator,
2463 .get_source_addr = _get_source_addr,
2464 .get_nexthop = _get_nexthop,
2465 .add_ip = _add_ip,
2466 .del_ip = _del_ip,
2467 .add_route = _add_route,
2468 .del_route = _del_route,
2469 .destroy = _destroy,
2470 },
2471 },
2472 .socket = netlink_socket_create(NETLINK_ROUTE),
2473 .rt_exclude = linked_list_create(),
2474 .routes = hashtable_create((hashtable_hash_t)route_entry_hash,
2475 (hashtable_equals_t)route_entry_equals, 16),
2476 .net_changes = hashtable_create(
2477 (hashtable_hash_t)net_change_hash,
2478 (hashtable_equals_t)net_change_equals, 16),
2479 .addrs = hashtable_create(
2480 (hashtable_hash_t)addr_map_entry_hash,
2481 (hashtable_equals_t)addr_map_entry_equals, 16),
2482 .vips = hashtable_create((hashtable_hash_t)addr_map_entry_hash,
2483 (hashtable_equals_t)addr_map_entry_equals, 16),
2484 .routes_lock = mutex_create(MUTEX_TYPE_DEFAULT),
2485 .net_changes_lock = mutex_create(MUTEX_TYPE_DEFAULT),
2486 .ifaces = linked_list_create(),
2487 .lock = rwlock_create(RWLOCK_TYPE_DEFAULT),
2488 .condvar = rwlock_condvar_create(),
2489 .roam_lock = spinlock_create(),
2490 .routing_table = lib->settings->get_int(lib->settings,
2491 "%s.routing_table", ROUTING_TABLE, lib->ns),
2492 .routing_table_prio = lib->settings->get_int(lib->settings,
2493 "%s.routing_table_prio", ROUTING_TABLE_PRIO, lib->ns),
2494 .process_route = lib->settings->get_bool(lib->settings,
2495 "%s.process_route", TRUE, lib->ns),
2496 .install_virtual_ip = lib->settings->get_bool(lib->settings,
2497 "%s.install_virtual_ip", TRUE, lib->ns),
2498 .install_virtual_ip_on = lib->settings->get_str(lib->settings,
2499 "%s.install_virtual_ip_on", NULL, lib->ns),
2500 .prefer_temporary_addrs = lib->settings->get_bool(lib->settings,
2501 "%s.prefer_temporary_addrs", FALSE, lib->ns),
2502 .roam_events = lib->settings->get_bool(lib->settings,
2503 "%s.plugins.kernel-netlink.roam_events", TRUE, lib->ns),
2504 .mtu = lib->settings->get_int(lib->settings,
2505 "%s.plugins.kernel-netlink.mtu", 0, lib->ns),
2506 .mss = lib->settings->get_int(lib->settings,
2507 "%s.plugins.kernel-netlink.mss", 0, lib->ns),
2508 );
2509 timerclear(&this->last_route_reinstall);
2510 timerclear(&this->next_roam);
2511
2512 check_kernel_features(this);
2513
2514 if (streq(lib->ns, "starter"))
2515 { /* starter has no threads, so we do not register for kernel events */
2516 register_for_events = FALSE;
2517 }
2518
2519 exclude = lib->settings->get_str(lib->settings,
2520 "%s.ignore_routing_tables", NULL, lib->ns);
2521 if (exclude)
2522 {
2523 char *token;
2524 uintptr_t table;
2525
2526 enumerator = enumerator_create_token(exclude, " ", " ");
2527 while (enumerator->enumerate(enumerator, &token))
2528 {
2529 errno = 0;
2530 table = strtoul(token, NULL, 10);
2531
2532 if (errno == 0)
2533 {
2534 this->rt_exclude->insert_last(this->rt_exclude, (void*)table);
2535 }
2536 }
2537 enumerator->destroy(enumerator);
2538 }
2539
2540 if (register_for_events)
2541 {
2542 struct sockaddr_nl addr;
2543
2544 memset(&addr, 0, sizeof(addr));
2545 addr.nl_family = AF_NETLINK;
2546
2547 /* create and bind RT socket for events (address/interface/route changes) */
2548 this->socket_events = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
2549 if (this->socket_events < 0)
2550 {
2551 DBG1(DBG_KNL, "unable to create RT event socket");
2552 destroy(this);
2553 return NULL;
2554 }
2555 addr.nl_groups = RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR |
2556 RTMGRP_IPV4_ROUTE | RTMGRP_IPV6_ROUTE | RTMGRP_LINK;
2557 if (bind(this->socket_events, (struct sockaddr*)&addr, sizeof(addr)))
2558 {
2559 DBG1(DBG_KNL, "unable to bind RT event socket");
2560 destroy(this);
2561 return NULL;
2562 }
2563
2564 lib->watcher->add(lib->watcher, this->socket_events, WATCHER_READ,
2565 (watcher_cb_t)receive_events, this);
2566 }
2567
2568 if (init_address_list(this) != SUCCESS)
2569 {
2570 DBG1(DBG_KNL, "unable to get interface list");
2571 destroy(this);
2572 return NULL;
2573 }
2574
2575 if (this->routing_table)
2576 {
2577 if (manage_rule(this, RTM_NEWRULE, AF_INET, this->routing_table,
2578 this->routing_table_prio) != SUCCESS)
2579 {
2580 DBG1(DBG_KNL, "unable to create IPv4 routing table rule");
2581 }
2582 if (manage_rule(this, RTM_NEWRULE, AF_INET6, this->routing_table,
2583 this->routing_table_prio) != SUCCESS)
2584 {
2585 DBG1(DBG_KNL, "unable to create IPv6 routing table rule");
2586 }
2587 }
2588
2589 return &this->public;
2590 }