760a875ca56f24c1802c77305f88af64b575800c
[strongswan.git] / src / libcharon / plugins / kernel_netlink / kernel_netlink_net.c
1 /*
2 * Copyright (C) 2008-2018 Tobias Brunner
3 * Copyright (C) 2005-2008 Martin Willi
4 * HSR 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 <daemon.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 /** multicast groups (for groups > 31 setsockopt has to be used) */
82 #define nl_group(group) (1 << (group - 1))
83
84 ENUM(rt_msg_names, RTM_NEWLINK, RTM_GETRULE,
85 "RTM_NEWLINK",
86 "RTM_DELLINK",
87 "RTM_GETLINK",
88 "RTM_SETLINK",
89 "RTM_NEWADDR",
90 "RTM_DELADDR",
91 "RTM_GETADDR",
92 "31",
93 "RTM_NEWROUTE",
94 "RTM_DELROUTE",
95 "RTM_GETROUTE",
96 "35",
97 "RTM_NEWNEIGH",
98 "RTM_DELNEIGH",
99 "RTM_GETNEIGH",
100 "RTM_NEWRULE",
101 "RTM_DELRULE",
102 "RTM_GETRULE",
103 );
104
105 typedef struct addr_entry_t addr_entry_t;
106
107 /**
108 * IP address in an iface_entry_t
109 */
110 struct addr_entry_t {
111
112 /** the ip address */
113 host_t *ip;
114
115 /** address flags */
116 u_char flags;
117
118 /** scope of the address */
119 u_char scope;
120
121 /** number of times this IP is used, if virtual (i.e. managed by us) */
122 u_int refcount;
123
124 /** TRUE once it is installed, if virtual */
125 bool installed;
126 };
127
128 /**
129 * destroy a addr_entry_t object
130 */
131 static void addr_entry_destroy(addr_entry_t *this)
132 {
133 this->ip->destroy(this->ip);
134 free(this);
135 }
136
137 typedef struct iface_entry_t iface_entry_t;
138
139 /**
140 * A network interface on this system, containing addr_entry_t's
141 */
142 struct iface_entry_t {
143
144 /** interface index */
145 int ifindex;
146
147 /** name of the interface */
148 char ifname[IFNAMSIZ];
149
150 /** interface flags, as in netdevice(7) SIOCGIFFLAGS */
151 u_int flags;
152
153 /** list of addresses as host_t */
154 linked_list_t *addrs;
155
156 /** TRUE if usable by config */
157 bool usable;
158 };
159
160 /**
161 * destroy an interface entry
162 */
163 static void iface_entry_destroy(iface_entry_t *this)
164 {
165 this->addrs->destroy_function(this->addrs, (void*)addr_entry_destroy);
166 free(this);
167 }
168
169 CALLBACK(iface_entry_by_index, bool,
170 iface_entry_t *this, va_list args)
171 {
172 int ifindex;
173
174 VA_ARGS_VGET(args, ifindex);
175 return this->ifindex == ifindex;
176 }
177
178 CALLBACK(iface_entry_by_name, bool,
179 iface_entry_t *this, va_list args)
180 {
181 char *ifname;
182
183 VA_ARGS_VGET(args, ifname);
184 return streq(this->ifname, ifname);
185 }
186
187 /**
188 * check if an interface is up
189 */
190 static inline bool iface_entry_up(iface_entry_t *iface)
191 {
192 return (iface->flags & IFF_UP) == IFF_UP;
193 }
194
195 /**
196 * check if an interface is up and usable
197 */
198 static inline bool iface_entry_up_and_usable(iface_entry_t *iface)
199 {
200 return iface->usable && iface_entry_up(iface);
201 }
202
203 typedef struct addr_map_entry_t addr_map_entry_t;
204
205 /**
206 * Entry that maps an IP address to an interface entry
207 */
208 struct addr_map_entry_t {
209 /** The IP address */
210 host_t *ip;
211
212 /** The address entry for this IP address */
213 addr_entry_t *addr;
214
215 /** The interface this address is installed on */
216 iface_entry_t *iface;
217 };
218
219 /**
220 * Hash a addr_map_entry_t object, all entries with the same IP address
221 * are stored in the same bucket
222 */
223 static u_int addr_map_entry_hash(addr_map_entry_t *this)
224 {
225 return chunk_hash(this->ip->get_address(this->ip));
226 }
227
228 /**
229 * Compare two addr_map_entry_t objects, two entries are equal if they are
230 * installed on the same interface
231 */
232 static bool addr_map_entry_equals(addr_map_entry_t *a, addr_map_entry_t *b)
233 {
234 return a->iface->ifindex == b->iface->ifindex &&
235 a->ip->ip_equals(a->ip, b->ip);
236 }
237
238 /**
239 * Used with get_match this finds an address entry if it is installed on
240 * an up and usable interface
241 */
242 static bool addr_map_entry_match_up_and_usable(addr_map_entry_t *a,
243 addr_map_entry_t *b)
244 {
245 return iface_entry_up_and_usable(b->iface) &&
246 a->ip->ip_equals(a->ip, b->ip);
247 }
248
249 /**
250 * Used with get_match this finds an address entry if it is installed on
251 * any active local interface
252 */
253 static bool addr_map_entry_match_up(addr_map_entry_t *a, addr_map_entry_t *b)
254 {
255 return iface_entry_up(b->iface) && a->ip->ip_equals(a->ip, b->ip);
256 }
257
258 /**
259 * Used with get_match this finds an address entry if it is installed on
260 * any local interface
261 */
262 static bool addr_map_entry_match(addr_map_entry_t *a, addr_map_entry_t *b)
263 {
264 return a->ip->ip_equals(a->ip, b->ip);
265 }
266
267 typedef struct route_entry_t route_entry_t;
268
269 /**
270 * Installed routing entry
271 */
272 struct route_entry_t {
273 /** Name of the interface the route is bound to */
274 char *if_name;
275
276 /** Source ip of the route */
277 host_t *src_ip;
278
279 /** Gateway for this route */
280 host_t *gateway;
281
282 /** Destination net */
283 chunk_t dst_net;
284
285 /** Destination net prefixlen */
286 uint8_t prefixlen;
287 };
288
289 /**
290 * Clone a route_entry_t object.
291 */
292 static route_entry_t *route_entry_clone(route_entry_t *this)
293 {
294 route_entry_t *route;
295
296 INIT(route,
297 .if_name = strdup(this->if_name),
298 .src_ip = this->src_ip->clone(this->src_ip),
299 .gateway = this->gateway ? this->gateway->clone(this->gateway) : NULL,
300 .dst_net = chunk_clone(this->dst_net),
301 .prefixlen = this->prefixlen,
302 );
303 return route;
304 }
305
306 /**
307 * Destroy a route_entry_t object
308 */
309 static void route_entry_destroy(route_entry_t *this)
310 {
311 free(this->if_name);
312 DESTROY_IF(this->src_ip);
313 DESTROY_IF(this->gateway);
314 chunk_free(&this->dst_net);
315 free(this);
316 }
317
318 /**
319 * Hash a route_entry_t object
320 */
321 static u_int route_entry_hash(route_entry_t *this)
322 {
323 return chunk_hash_inc(chunk_from_thing(this->prefixlen),
324 chunk_hash(this->dst_net));
325 }
326
327 /**
328 * Compare two route_entry_t objects
329 */
330 static bool route_entry_equals(route_entry_t *a, route_entry_t *b)
331 {
332 if (a->if_name && b->if_name && streq(a->if_name, b->if_name) &&
333 a->src_ip->ip_equals(a->src_ip, b->src_ip) &&
334 chunk_equals(a->dst_net, b->dst_net) && a->prefixlen == b->prefixlen)
335 {
336 return (!a->gateway && !b->gateway) || (a->gateway && b->gateway &&
337 a->gateway->ip_equals(a->gateway, b->gateway));
338 }
339 return FALSE;
340 }
341
342 typedef struct net_change_t net_change_t;
343
344 /**
345 * Queued network changes
346 */
347 struct net_change_t {
348 /** Name of the interface that got activated (or an IP appeared on) */
349 char *if_name;
350 };
351
352 /**
353 * Destroy a net_change_t object
354 */
355 static void net_change_destroy(net_change_t *this)
356 {
357 free(this->if_name);
358 free(this);
359 }
360
361 /**
362 * Hash a net_change_t object
363 */
364 static u_int net_change_hash(net_change_t *this)
365 {
366 return chunk_hash(chunk_create(this->if_name, strlen(this->if_name)));
367 }
368
369 /**
370 * Compare two net_change_t objects
371 */
372 static bool net_change_equals(net_change_t *a, net_change_t *b)
373 {
374 return streq(a->if_name, b->if_name);
375 }
376
377 typedef struct private_kernel_netlink_net_t private_kernel_netlink_net_t;
378
379 /**
380 * Private variables and functions of kernel_netlink_net class.
381 */
382 struct private_kernel_netlink_net_t {
383 /**
384 * Public part of the kernel_netlink_net_t object.
385 */
386 kernel_netlink_net_t public;
387
388 /**
389 * lock to access various lists and maps
390 */
391 rwlock_t *lock;
392
393 /**
394 * condition variable to signal virtual IP add/removal
395 */
396 rwlock_condvar_t *condvar;
397
398 /**
399 * Cached list of interfaces and its addresses (iface_entry_t)
400 */
401 linked_list_t *ifaces;
402
403 /**
404 * Map for IP addresses to iface_entry_t objects (addr_map_entry_t)
405 */
406 hashtable_t *addrs;
407
408 /**
409 * Map for virtual IP addresses to iface_entry_t objects (addr_map_entry_t)
410 */
411 hashtable_t *vips;
412
413 /**
414 * netlink rt socket (routing)
415 */
416 netlink_socket_t *socket;
417
418 /**
419 * Netlink rt socket to receive address change events
420 */
421 int socket_events;
422
423 /**
424 * earliest time of the next roam event
425 */
426 timeval_t next_roam;
427
428 /**
429 * roam event due to address change
430 */
431 bool roam_address;
432
433 /**
434 * lock to check and update roam event time
435 */
436 spinlock_t *roam_lock;
437
438 /**
439 * routing table to install routes
440 */
441 int routing_table;
442
443 /**
444 * priority of used routing table
445 */
446 int routing_table_prio;
447
448 /**
449 * installed routes
450 */
451 hashtable_t *routes;
452
453 /**
454 * mutex for routes
455 */
456 mutex_t *routes_lock;
457
458 /**
459 * interface changes which may trigger route reinstallation
460 */
461 hashtable_t *net_changes;
462
463 /**
464 * mutex for route reinstallation triggers
465 */
466 mutex_t *net_changes_lock;
467
468 /**
469 * time of last route reinstallation
470 */
471 timeval_t last_route_reinstall;
472
473 /**
474 * whether to react to RTM_NEWROUTE or RTM_DELROUTE events
475 */
476 bool process_route;
477
478 /**
479 * whether to react to RTM_NEWRULE or RTM_DELRULE events
480 */
481 bool process_rules;
482
483 /**
484 * whether to trigger roam events
485 */
486 bool roam_events;
487
488 /**
489 * whether to install IPsec policy routes
490 */
491 bool install_routes;
492
493 /**
494 * whether to actually install virtual IPs
495 */
496 bool install_virtual_ip;
497
498 /**
499 * the name of the interface virtual IP addresses are installed on
500 */
501 char *install_virtual_ip_on;
502
503 /**
504 * whether preferred source addresses can be specified for IPv6 routes
505 */
506 bool rta_prefsrc_for_ipv6;
507
508 /**
509 * whether marks can be used in route lookups
510 */
511 bool rta_mark;
512
513 /**
514 * the mark excluded from the routing rule used for virtual IPs
515 */
516 mark_t routing_mark;
517
518 /**
519 * whether to prefer temporary IPv6 addresses over public ones
520 */
521 bool prefer_temporary_addrs;
522
523 /**
524 * list with routing tables to be excluded from route lookup
525 */
526 linked_list_t *rt_exclude;
527
528 /**
529 * MTU to set on installed routes
530 */
531 uint32_t mtu;
532
533 /**
534 * MSS to set on installed routes
535 */
536 uint32_t mss;
537 };
538
539 /**
540 * Forward declaration
541 */
542 static status_t manage_srcroute(private_kernel_netlink_net_t *this,
543 int nlmsg_type, int flags, chunk_t dst_net,
544 uint8_t prefixlen, host_t *gateway,
545 host_t *src_ip, char *if_name);
546
547 /**
548 * Clear the queued network changes.
549 */
550 static void net_changes_clear(private_kernel_netlink_net_t *this)
551 {
552 enumerator_t *enumerator;
553 net_change_t *change;
554
555 enumerator = this->net_changes->create_enumerator(this->net_changes);
556 while (enumerator->enumerate(enumerator, NULL, (void**)&change))
557 {
558 this->net_changes->remove_at(this->net_changes, enumerator);
559 net_change_destroy(change);
560 }
561 enumerator->destroy(enumerator);
562 }
563
564 /**
565 * Act upon queued network changes.
566 */
567 static job_requeue_t reinstall_routes(private_kernel_netlink_net_t *this)
568 {
569 enumerator_t *enumerator;
570 route_entry_t *route;
571
572 this->net_changes_lock->lock(this->net_changes_lock);
573 this->routes_lock->lock(this->routes_lock);
574
575 enumerator = this->routes->create_enumerator(this->routes);
576 while (enumerator->enumerate(enumerator, NULL, (void**)&route))
577 {
578 net_change_t *change, lookup = {
579 .if_name = route->if_name,
580 };
581 /* check if a change for the outgoing interface is queued */
582 change = this->net_changes->get(this->net_changes, &lookup);
583 if (!change)
584 { /* in case src_ip is not on the outgoing interface */
585 if (this->public.interface.get_interface(&this->public.interface,
586 route->src_ip, &lookup.if_name))
587 {
588 if (!streq(lookup.if_name, route->if_name))
589 {
590 change = this->net_changes->get(this->net_changes, &lookup);
591 }
592 free(lookup.if_name);
593 }
594 }
595 if (change)
596 {
597 manage_srcroute(this, RTM_NEWROUTE, NLM_F_CREATE | NLM_F_EXCL,
598 route->dst_net, route->prefixlen, route->gateway,
599 route->src_ip, route->if_name);
600 }
601 }
602 enumerator->destroy(enumerator);
603 this->routes_lock->unlock(this->routes_lock);
604
605 net_changes_clear(this);
606 this->net_changes_lock->unlock(this->net_changes_lock);
607 return JOB_REQUEUE_NONE;
608 }
609
610 /**
611 * Queue route reinstallation caused by network changes for a given interface.
612 *
613 * The route reinstallation is delayed for a while and only done once for
614 * several calls during this delay, in order to avoid doing it too often.
615 * The interface name is freed.
616 */
617 static void queue_route_reinstall(private_kernel_netlink_net_t *this,
618 char *if_name)
619 {
620 net_change_t *update, *found;
621 timeval_t now;
622 job_t *job;
623
624 INIT(update,
625 .if_name = if_name
626 );
627
628 this->net_changes_lock->lock(this->net_changes_lock);
629 found = this->net_changes->put(this->net_changes, update, update);
630 if (found)
631 {
632 net_change_destroy(found);
633 }
634 time_monotonic(&now);
635 if (timercmp(&now, &this->last_route_reinstall, >))
636 {
637 timeval_add_ms(&now, ROUTE_DELAY);
638 this->last_route_reinstall = now;
639
640 job = (job_t*)callback_job_create((callback_job_cb_t)reinstall_routes,
641 this, NULL, NULL);
642 lib->scheduler->schedule_job_ms(lib->scheduler, job, ROUTE_DELAY);
643 }
644 this->net_changes_lock->unlock(this->net_changes_lock);
645 }
646
647 /**
648 * check if the given IP is known as virtual IP and currently installed
649 *
650 * this function will also return TRUE if the virtual IP entry disappeared.
651 * in that case the returned entry will be NULL.
652 *
653 * this->lock must be held when calling this function
654 */
655 static bool is_vip_installed_or_gone(private_kernel_netlink_net_t *this,
656 host_t *ip, addr_map_entry_t **entry)
657 {
658 addr_map_entry_t lookup = {
659 .ip = ip,
660 };
661
662 *entry = this->vips->get_match(this->vips, &lookup,
663 (void*)addr_map_entry_match);
664 if (*entry == NULL)
665 { /* the virtual IP disappeared */
666 return TRUE;
667 }
668 return (*entry)->addr->installed;
669 }
670
671 /**
672 * check if the given IP is known as virtual IP
673 *
674 * this->lock must be held when calling this function
675 */
676 static bool is_known_vip(private_kernel_netlink_net_t *this, host_t *ip)
677 {
678 addr_map_entry_t lookup = {
679 .ip = ip,
680 };
681
682 return this->vips->get_match(this->vips, &lookup,
683 (void*)addr_map_entry_match) != NULL;
684 }
685
686 /**
687 * Add an address map entry
688 */
689 static void addr_map_entry_add(hashtable_t *map, addr_entry_t *addr,
690 iface_entry_t *iface)
691 {
692 addr_map_entry_t *entry;
693
694 INIT(entry,
695 .ip = addr->ip,
696 .addr = addr,
697 .iface = iface,
698 );
699 entry = map->put(map, entry, entry);
700 free(entry);
701 }
702
703 /**
704 * Remove an address map entry
705 */
706 static void addr_map_entry_remove(hashtable_t *map, addr_entry_t *addr,
707 iface_entry_t *iface)
708 {
709 addr_map_entry_t *entry, lookup = {
710 .ip = addr->ip,
711 .addr = addr,
712 .iface = iface,
713 };
714
715 entry = map->remove(map, &lookup);
716 free(entry);
717 }
718
719 /**
720 * Check if an address or net (addr with prefix net bits) is in
721 * subnet (net with net_len net bits)
722 */
723 static bool addr_in_subnet(chunk_t addr, int prefix, chunk_t net, int net_len)
724 {
725 static const u_char mask[] = { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
726 int byte = 0;
727
728 if (net_len == 0)
729 { /* any address matches a /0 network */
730 return TRUE;
731 }
732 if (addr.len != net.len || net_len > 8 * net.len || prefix < net_len)
733 {
734 return FALSE;
735 }
736 /* scan through all bytes in network order */
737 while (net_len > 0)
738 {
739 if (net_len < 8)
740 {
741 return (mask[net_len] & addr.ptr[byte]) == (mask[net_len] & net.ptr[byte]);
742 }
743 else
744 {
745 if (addr.ptr[byte] != net.ptr[byte])
746 {
747 return FALSE;
748 }
749 byte++;
750 net_len -= 8;
751 }
752 }
753 return TRUE;
754 }
755
756 /**
757 * Check if the given address is in subnet (net with net_len net bits)
758 */
759 static bool host_in_subnet(host_t *host, chunk_t net, int net_len)
760 {
761 chunk_t addr;
762
763 addr = host->get_address(host);
764 return addr_in_subnet(addr, addr.len * 8, net, net_len);
765 }
766
767 /**
768 * Determine the type or scope of the given unicast IP address. This is not
769 * the same thing returned in rtm_scope/ifa_scope.
770 *
771 * We use return values as defined in RFC 6724 (referring to RFC 4291).
772 */
773 static u_char get_scope(host_t *ip)
774 {
775 chunk_t addr;
776
777 addr = ip->get_address(ip);
778 switch (addr.len)
779 {
780 case 4:
781 /* we use the mapping defined in RFC 6724, 3.2 */
782 if (addr.ptr[0] == 127)
783 { /* link-local, same as the IPv6 loopback address */
784 return 2;
785 }
786 if (addr.ptr[0] == 169 && addr.ptr[1] == 254)
787 { /* link-local */
788 return 2;
789 }
790 break;
791 case 16:
792 if (IN6_IS_ADDR_LOOPBACK((struct in6_addr*)addr.ptr))
793 { /* link-local, according to RFC 4291, 2.5.3 */
794 return 2;
795 }
796 if (IN6_IS_ADDR_LINKLOCAL((struct in6_addr*)addr.ptr))
797 {
798 return 2;
799 }
800 if (IN6_IS_ADDR_SITELOCAL((struct in6_addr*)addr.ptr))
801 { /* deprecated, according to RFC 4291, 2.5.7 */
802 return 5;
803 }
804 break;
805 default:
806 break;
807 }
808 /* global */
809 return 14;
810 }
811
812 /**
813 * Determine the label of the given unicast IP address.
814 *
815 * We currently only support the default table given in RFC 6724:
816 *
817 * Prefix Precedence Label
818 * ::1/128 50 0
819 * ::/0 40 1
820 * ::ffff:0:0/96 35 4
821 * 2002::/16 30 2
822 * 2001::/32 5 5
823 * fc00::/7 3 13
824 * ::/96 1 3
825 * fec0::/10 1 11
826 * 3ffe::/16 1 12
827 */
828 static u_char get_label(host_t *ip)
829 {
830 struct {
831 chunk_t net;
832 u_char prefix;
833 u_char label;
834 } priorities[] = {
835 /* priority table ordered by prefix */
836 /* ::1/128 */
837 { chunk_from_chars(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
838 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01), 128, 0 },
839 /* ::ffff:0:0/96 */
840 { chunk_from_chars(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
841 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00), 96, 4 },
842 /* ::/96 */
843 { chunk_from_chars(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
844 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00), 96, 3 },
845 /* 2001::/32 */
846 { chunk_from_chars(0x20, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
847 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00), 32, 5 },
848 /* 2002::/16 */
849 { chunk_from_chars(0x20, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
850 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00), 16, 2 },
851 /* 3ffe::/16 */
852 { chunk_from_chars(0x3f, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
853 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00), 16, 12 },
854 /* fec0::/10 */
855 { chunk_from_chars(0xfe, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
856 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00), 10, 11 },
857 /* fc00::/7 */
858 { chunk_from_chars(0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
859 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00), 7, 13 },
860 };
861 int i;
862
863 for (i = 0; i < countof(priorities); i++)
864 {
865 if (host_in_subnet(ip, priorities[i].net, priorities[i].prefix))
866 {
867 return priorities[i].label;
868 }
869 }
870 /* ::/0 */
871 return 1;
872 }
873
874 /**
875 * Returns the length of the common prefix in bits up to the length of a's
876 * prefix, defined by RFC 6724 as the portion of the address not including the
877 * interface ID, which is 64-bit for most unicast addresses (see RFC 4291).
878 */
879 static u_char common_prefix(host_t *a, host_t *b)
880 {
881 chunk_t aa, ba;
882 u_char byte, bits = 0, match;
883
884 aa = a->get_address(a);
885 ba = b->get_address(b);
886 for (byte = 0; byte < 8; byte++)
887 {
888 if (aa.ptr[byte] != ba.ptr[byte])
889 {
890 match = aa.ptr[byte] ^ ba.ptr[byte];
891 for (bits = 8; match; match >>= 1)
892 {
893 bits--;
894 }
895 break;
896 }
897 }
898 return byte * 8 + bits;
899 }
900
901 /**
902 * Compare two IP addresses and return TRUE if the second address is the better
903 * choice of the two to reach the destination.
904 * For IPv6 we approximately follow RFC 6724.
905 */
906 static bool is_address_better(private_kernel_netlink_net_t *this,
907 addr_entry_t *a, addr_entry_t *b, host_t *d)
908 {
909 u_char sa, sb, sd, la, lb, ld, pa, pb;
910
911 /* rule 2: prefer appropriate scope */
912 if (d)
913 {
914 sa = get_scope(a->ip);
915 sb = get_scope(b->ip);
916 sd = get_scope(d);
917 if (sa < sb)
918 {
919 return sa < sd;
920 }
921 else if (sb < sa)
922 {
923 return sb >= sd;
924 }
925 }
926 if (a->ip->get_family(a->ip) == AF_INET)
927 { /* stop here for IPv4, default to addresses found earlier */
928 return FALSE;
929 }
930 /* rule 3: avoid deprecated addresses (RFC 4862) */
931 if ((a->flags & IFA_F_DEPRECATED) != (b->flags & IFA_F_DEPRECATED))
932 {
933 return a->flags & IFA_F_DEPRECATED;
934 }
935 /* rule 4 is not applicable as we don't know if an address is a home or
936 * care-of addresses.
937 * rule 5 does not apply as we only compare addresses from one interface
938 */
939 /* rule 6: prefer matching label */
940 if (d)
941 {
942 la = get_label(a->ip);
943 lb = get_label(b->ip);
944 ld = get_label(d);
945 if (la == ld && lb != ld)
946 {
947 return FALSE;
948 }
949 else if (lb == ld && la != ld)
950 {
951 return TRUE;
952 }
953 }
954 /* rule 7: prefer temporary addresses (WE REVERSE THIS BY DEFAULT!) */
955 if ((a->flags & IFA_F_TEMPORARY) != (b->flags & IFA_F_TEMPORARY))
956 {
957 if (this->prefer_temporary_addrs)
958 {
959 return b->flags & IFA_F_TEMPORARY;
960 }
961 return a->flags & IFA_F_TEMPORARY;
962 }
963 /* rule 8: use longest matching prefix */
964 if (d)
965 {
966 pa = common_prefix(a->ip, d);
967 pb = common_prefix(b->ip, d);
968 if (pa != pb)
969 {
970 return pb > pa;
971 }
972 }
973 /* default to addresses found earlier */
974 return FALSE;
975 }
976
977 /**
978 * Get a non-virtual IP address on the given interfaces and optionally in a
979 * given subnet.
980 *
981 * If a candidate address is given, we first search for that address and if not
982 * found return the address as above.
983 * Returned host is a clone, has to be freed by caller.
984 *
985 * this->lock must be held when calling this function.
986 */
987 static host_t *get_matching_address(private_kernel_netlink_net_t *this,
988 int *ifindex, int family, chunk_t net,
989 uint8_t mask, host_t *dest,
990 host_t *candidate)
991 {
992 enumerator_t *ifaces, *addrs;
993 iface_entry_t *iface;
994 addr_entry_t *addr, *best = NULL;
995 bool candidate_matched = FALSE;
996
997 ifaces = this->ifaces->create_enumerator(this->ifaces);
998 while (ifaces->enumerate(ifaces, &iface))
999 {
1000 if (iface->usable && (!ifindex || iface->ifindex == *ifindex))
1001 { /* only use matching interfaces not excluded by config */
1002 addrs = iface->addrs->create_enumerator(iface->addrs);
1003 while (addrs->enumerate(addrs, &addr))
1004 {
1005 if (addr->refcount ||
1006 addr->ip->get_family(addr->ip) != family)
1007 { /* ignore virtual IP addresses and ensure family matches */
1008 continue;
1009 }
1010 if (net.ptr && !host_in_subnet(addr->ip, net, mask))
1011 { /* optionally match a subnet */
1012 continue;
1013 }
1014 if (candidate && candidate->ip_equals(candidate, addr->ip))
1015 { /* stop if we find the candidate */
1016 best = addr;
1017 candidate_matched = TRUE;
1018 break;
1019 }
1020 else if (!best || is_address_better(this, best, addr, dest))
1021 {
1022 best = addr;
1023 }
1024 }
1025 addrs->destroy(addrs);
1026 if (ifindex || candidate_matched)
1027 {
1028 break;
1029 }
1030 }
1031 }
1032 ifaces->destroy(ifaces);
1033 return best ? best->ip->clone(best->ip) : NULL;
1034 }
1035
1036 /**
1037 * Get a non-virtual IP address on the given interface.
1038 *
1039 * If a candidate address is given, we first search for that address and if not
1040 * found return the address as above.
1041 * Returned host is a clone, has to be freed by caller.
1042 *
1043 * this->lock must be held when calling this function.
1044 */
1045 static host_t *get_interface_address(private_kernel_netlink_net_t *this,
1046 int ifindex, int family, host_t *dest,
1047 host_t *candidate)
1048 {
1049 return get_matching_address(this, &ifindex, family, chunk_empty, 0, dest,
1050 candidate);
1051 }
1052
1053 /**
1054 * Get a non-virtual IP address in the given subnet.
1055 *
1056 * If a candidate address is given, we first search for that address and if not
1057 * found return the address as above.
1058 * Returned host is a clone, has to be freed by caller.
1059 *
1060 * this->lock must be held when calling this function.
1061 */
1062 static host_t *get_subnet_address(private_kernel_netlink_net_t *this,
1063 int family, chunk_t net, uint8_t mask,
1064 host_t *dest, host_t *candidate)
1065 {
1066 return get_matching_address(this, NULL, family, net, mask, dest, candidate);
1067 }
1068
1069 /**
1070 * callback function that raises the delayed roam event
1071 */
1072 static job_requeue_t roam_event(private_kernel_netlink_net_t *this)
1073 {
1074 bool address;
1075
1076 this->roam_lock->lock(this->roam_lock);
1077 address = this->roam_address;
1078 this->roam_address = FALSE;
1079 this->roam_lock->unlock(this->roam_lock);
1080 charon->kernel->roam(charon->kernel, address);
1081 return JOB_REQUEUE_NONE;
1082 }
1083
1084 /**
1085 * fire a roaming event. we delay it for a bit and fire only one event
1086 * for multiple calls. otherwise we would create too many events.
1087 */
1088 static void fire_roam_event(private_kernel_netlink_net_t *this, bool address)
1089 {
1090 timeval_t now;
1091 job_t *job;
1092
1093 if (!this->roam_events)
1094 {
1095 return;
1096 }
1097
1098 time_monotonic(&now);
1099 this->roam_lock->lock(this->roam_lock);
1100 this->roam_address |= address;
1101 if (!timercmp(&now, &this->next_roam, >))
1102 {
1103 this->roam_lock->unlock(this->roam_lock);
1104 return;
1105 }
1106 timeval_add_ms(&now, ROAM_DELAY);
1107 this->next_roam = now;
1108 this->roam_lock->unlock(this->roam_lock);
1109
1110 job = (job_t*)callback_job_create((callback_job_cb_t)roam_event,
1111 this, NULL, NULL);
1112 lib->scheduler->schedule_job_ms(lib->scheduler, job, ROAM_DELAY);
1113 }
1114
1115 /**
1116 * check if an interface with a given index is up and usable
1117 *
1118 * this->lock must be locked when calling this function
1119 */
1120 static bool is_interface_up_and_usable(private_kernel_netlink_net_t *this,
1121 int index)
1122 {
1123 iface_entry_t *iface;
1124
1125 if (this->ifaces->find_first(this->ifaces, iface_entry_by_index,
1126 (void**)&iface, index))
1127 {
1128 return iface_entry_up_and_usable(iface);
1129 }
1130 return FALSE;
1131 }
1132
1133 /**
1134 * unregister the current addr_entry_t from the hashtable it is stored in
1135 *
1136 * this->lock must be locked when calling this function
1137 */
1138 CALLBACK(addr_entry_unregister, void,
1139 addr_entry_t *addr, va_list args)
1140 {
1141 private_kernel_netlink_net_t *this;
1142 iface_entry_t *iface;
1143
1144 VA_ARGS_VGET(args, iface, this);
1145 if (addr->refcount)
1146 {
1147 addr_map_entry_remove(this->vips, addr, iface);
1148 this->condvar->broadcast(this->condvar);
1149 return;
1150 }
1151 addr_map_entry_remove(this->addrs, addr, iface);
1152 }
1153
1154 /**
1155 * process RTM_NEWLINK/RTM_DELLINK from kernel
1156 */
1157 static void process_link(private_kernel_netlink_net_t *this,
1158 struct nlmsghdr *hdr, bool event)
1159 {
1160 struct ifinfomsg* msg = NLMSG_DATA(hdr);
1161 struct rtattr *rta = IFLA_RTA(msg);
1162 size_t rtasize = IFLA_PAYLOAD (hdr);
1163 enumerator_t *enumerator;
1164 iface_entry_t *current, *entry = NULL;
1165 char *name = NULL;
1166 bool update = FALSE, update_routes = FALSE;
1167
1168 while (RTA_OK(rta, rtasize))
1169 {
1170 switch (rta->rta_type)
1171 {
1172 case IFLA_IFNAME:
1173 name = RTA_DATA(rta);
1174 break;
1175 }
1176 rta = RTA_NEXT(rta, rtasize);
1177 }
1178 if (!name)
1179 {
1180 name = "(unknown)";
1181 }
1182
1183 this->lock->write_lock(this->lock);
1184 switch (hdr->nlmsg_type)
1185 {
1186 case RTM_NEWLINK:
1187 {
1188 if (!this->ifaces->find_first(this->ifaces, iface_entry_by_index,
1189 (void**)&entry, msg->ifi_index))
1190 {
1191 INIT(entry,
1192 .ifindex = msg->ifi_index,
1193 .addrs = linked_list_create(),
1194 );
1195 this->ifaces->insert_last(this->ifaces, entry);
1196 }
1197 strncpy(entry->ifname, name, IFNAMSIZ);
1198 entry->ifname[IFNAMSIZ-1] = '\0';
1199 entry->usable = charon->kernel->is_interface_usable(charon->kernel,
1200 name);
1201 if (event && entry->usable)
1202 {
1203 if (!(entry->flags & IFF_UP) && (msg->ifi_flags & IFF_UP))
1204 {
1205 update = update_routes = TRUE;
1206 DBG1(DBG_KNL, "interface %s activated", name);
1207 }
1208 if ((entry->flags & IFF_UP) && !(msg->ifi_flags & IFF_UP))
1209 {
1210 update = TRUE;
1211 DBG1(DBG_KNL, "interface %s deactivated", name);
1212 }
1213 }
1214 entry->flags = msg->ifi_flags;
1215 break;
1216 }
1217 case RTM_DELLINK:
1218 {
1219 enumerator = this->ifaces->create_enumerator(this->ifaces);
1220 while (enumerator->enumerate(enumerator, &current))
1221 {
1222 if (current->ifindex == msg->ifi_index)
1223 {
1224 if (event && current->usable)
1225 {
1226 update = TRUE;
1227 DBG1(DBG_KNL, "interface %s deleted", current->ifname);
1228 }
1229 /* TODO: move virtual IPs installed on this interface to
1230 * another interface? */
1231 this->ifaces->remove_at(this->ifaces, enumerator);
1232 current->addrs->invoke_function(current->addrs,
1233 addr_entry_unregister, current, this);
1234 iface_entry_destroy(current);
1235 break;
1236 }
1237 }
1238 enumerator->destroy(enumerator);
1239 break;
1240 }
1241 }
1242 this->lock->unlock(this->lock);
1243
1244 if (update_routes && event)
1245 {
1246 queue_route_reinstall(this, strdup(name));
1247 }
1248
1249 if (update && event)
1250 {
1251 fire_roam_event(this, TRUE);
1252 }
1253 }
1254
1255 /**
1256 * process RTM_NEWADDR/RTM_DELADDR from kernel
1257 */
1258 static void process_addr(private_kernel_netlink_net_t *this,
1259 struct nlmsghdr *hdr, bool event)
1260 {
1261 struct ifaddrmsg* msg = NLMSG_DATA(hdr);
1262 struct rtattr *rta = IFA_RTA(msg);
1263 size_t rtasize = IFA_PAYLOAD (hdr);
1264 host_t *host = NULL;
1265 iface_entry_t *iface;
1266 chunk_t local = chunk_empty, address = chunk_empty;
1267 char *route_ifname = NULL;
1268 bool update = FALSE, found = FALSE, changed = FALSE;
1269
1270 while (RTA_OK(rta, rtasize))
1271 {
1272 switch (rta->rta_type)
1273 {
1274 case IFA_LOCAL:
1275 local.ptr = RTA_DATA(rta);
1276 local.len = RTA_PAYLOAD(rta);
1277 break;
1278 case IFA_ADDRESS:
1279 address.ptr = RTA_DATA(rta);
1280 address.len = RTA_PAYLOAD(rta);
1281 break;
1282 }
1283 rta = RTA_NEXT(rta, rtasize);
1284 }
1285
1286 /* For PPP interfaces, we need the IFA_LOCAL address,
1287 * IFA_ADDRESS is the peers address. But IFA_LOCAL is
1288 * not included in all cases (IPv6?), so fallback to IFA_ADDRESS. */
1289 if (local.ptr)
1290 {
1291 host = host_create_from_chunk(msg->ifa_family, local, 0);
1292 }
1293 else if (address.ptr)
1294 {
1295 host = host_create_from_chunk(msg->ifa_family, address, 0);
1296 }
1297
1298 if (host == NULL)
1299 { /* bad family? */
1300 return;
1301 }
1302
1303 this->lock->write_lock(this->lock);
1304 if (this->ifaces->find_first(this->ifaces, iface_entry_by_index,
1305 (void**)&iface, msg->ifa_index))
1306 {
1307 addr_map_entry_t *entry, lookup = {
1308 .ip = host,
1309 .iface = iface,
1310 };
1311 addr_entry_t *addr;
1312
1313 entry = this->vips->get(this->vips, &lookup);
1314 if (entry)
1315 {
1316 if (hdr->nlmsg_type == RTM_NEWADDR)
1317 { /* mark as installed and signal waiting threads */
1318 entry->addr->installed = TRUE;
1319 }
1320 else
1321 { /* the address was already marked as uninstalled */
1322 addr = entry->addr;
1323 iface->addrs->remove(iface->addrs, addr, NULL);
1324 addr_map_entry_remove(this->vips, addr, iface);
1325 addr_entry_destroy(addr);
1326 }
1327 /* no roam events etc. for virtual IPs */
1328 this->condvar->broadcast(this->condvar);
1329 this->lock->unlock(this->lock);
1330 host->destroy(host);
1331 return;
1332 }
1333 entry = this->addrs->get(this->addrs, &lookup);
1334 if (entry)
1335 {
1336 if (hdr->nlmsg_type == RTM_DELADDR)
1337 {
1338 found = TRUE;
1339 addr = entry->addr;
1340 iface->addrs->remove(iface->addrs, addr, NULL);
1341 if (iface->usable)
1342 {
1343 changed = TRUE;
1344 DBG1(DBG_KNL, "%H disappeared from %s", host,
1345 iface->ifname);
1346 }
1347 addr_map_entry_remove(this->addrs, addr, iface);
1348 addr_entry_destroy(addr);
1349 }
1350 }
1351 else
1352 {
1353 if (hdr->nlmsg_type == RTM_NEWADDR)
1354 {
1355 found = TRUE;
1356 changed = TRUE;
1357 route_ifname = strdup(iface->ifname);
1358 INIT(addr,
1359 .ip = host->clone(host),
1360 .flags = msg->ifa_flags,
1361 .scope = msg->ifa_scope,
1362 );
1363 iface->addrs->insert_last(iface->addrs, addr);
1364 addr_map_entry_add(this->addrs, addr, iface);
1365 if (event && iface->usable)
1366 {
1367 DBG1(DBG_KNL, "%H appeared on %s", host, iface->ifname);
1368 }
1369 }
1370 }
1371 if (found && (iface->flags & IFF_UP))
1372 {
1373 update = TRUE;
1374 }
1375 if (!iface->usable)
1376 { /* ignore events for interfaces excluded by config */
1377 update = changed = FALSE;
1378 }
1379 }
1380 this->lock->unlock(this->lock);
1381
1382 if (update && event && route_ifname)
1383 {
1384 queue_route_reinstall(this, route_ifname);
1385 }
1386 else
1387 {
1388 free(route_ifname);
1389 }
1390 host->destroy(host);
1391
1392 /* send an update to all IKE_SAs */
1393 if (update && event && changed)
1394 {
1395 fire_roam_event(this, TRUE);
1396 }
1397 }
1398
1399 /**
1400 * process RTM_NEWROUTE and RTM_DELROUTE from kernel
1401 */
1402 static void process_route(private_kernel_netlink_net_t *this, struct nlmsghdr *hdr)
1403 {
1404 struct rtmsg* msg = NLMSG_DATA(hdr);
1405 struct rtattr *rta = RTM_RTA(msg);
1406 size_t rtasize = RTM_PAYLOAD(hdr);
1407 uint32_t rta_oif = 0;
1408 host_t *host = NULL;
1409
1410 /* ignore routes added by us or in the local routing table (local addrs) */
1411 if (msg->rtm_table && (msg->rtm_table == this->routing_table ||
1412 msg->rtm_table == RT_TABLE_LOCAL))
1413 {
1414 return;
1415 }
1416 else if (msg->rtm_flags & RTM_F_CLONED)
1417 { /* ignore cached routes, seem to be created a lot for IPv6 */
1418 return;
1419 }
1420
1421 while (RTA_OK(rta, rtasize))
1422 {
1423 switch (rta->rta_type)
1424 {
1425 case RTA_PREFSRC:
1426 DESTROY_IF(host);
1427 host = host_create_from_chunk(msg->rtm_family,
1428 chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta)), 0);
1429 break;
1430 case RTA_OIF:
1431 if (RTA_PAYLOAD(rta) == sizeof(rta_oif))
1432 {
1433 rta_oif = *(uint32_t*)RTA_DATA(rta);
1434 }
1435 break;
1436 }
1437 rta = RTA_NEXT(rta, rtasize);
1438 }
1439 this->lock->read_lock(this->lock);
1440 if (rta_oif && !is_interface_up_and_usable(this, rta_oif))
1441 { /* ignore route changes for interfaces that are ignored or down */
1442 this->lock->unlock(this->lock);
1443 DESTROY_IF(host);
1444 return;
1445 }
1446 if (!host && rta_oif)
1447 {
1448 host = get_interface_address(this, rta_oif, msg->rtm_family,
1449 NULL, NULL);
1450 }
1451 if (!host || is_known_vip(this, host))
1452 { /* ignore routes added for virtual IPs */
1453 this->lock->unlock(this->lock);
1454 DESTROY_IF(host);
1455 return;
1456 }
1457 this->lock->unlock(this->lock);
1458 fire_roam_event(this, FALSE);
1459 host->destroy(host);
1460 }
1461
1462 /**
1463 * process RTM_NEW|DELRULE from kernel
1464 */
1465 static void process_rule(private_kernel_netlink_net_t *this, struct nlmsghdr *hdr)
1466 {
1467 #ifdef HAVE_LINUX_FIB_RULES_H
1468 struct rtmsg* msg = NLMSG_DATA(hdr);
1469 struct rtattr *rta = RTM_RTA(msg);
1470 size_t rtasize = RTM_PAYLOAD(hdr);
1471 uint32_t table = 0;
1472
1473 /* ignore rules added by us or in the local routing table (local addrs) */
1474 if (msg->rtm_table && (msg->rtm_table == this->routing_table ||
1475 msg->rtm_table == RT_TABLE_LOCAL))
1476 {
1477 return;
1478 }
1479
1480 while (RTA_OK(rta, rtasize))
1481 {
1482 switch (rta->rta_type)
1483 {
1484 case FRA_TABLE:
1485 if (RTA_PAYLOAD(rta) == sizeof(table))
1486 {
1487 table = *(uint32_t*)RTA_DATA(rta);
1488 }
1489 break;
1490 }
1491 rta = RTA_NEXT(rta, rtasize);
1492 }
1493 if (table && table == this->routing_table)
1494 { /* also check against extended table ID */
1495 return;
1496 }
1497 fire_roam_event(this, FALSE);
1498 #endif
1499 }
1500
1501 /**
1502 * Receives events from kernel
1503 */
1504 static bool receive_events(private_kernel_netlink_net_t *this, int fd,
1505 watcher_event_t event)
1506 {
1507 char response[netlink_get_buflen()];
1508 struct nlmsghdr *hdr = (struct nlmsghdr*)response;
1509 struct sockaddr_nl addr;
1510 socklen_t addr_len = sizeof(addr);
1511 int len;
1512
1513 len = recvfrom(this->socket_events, response, sizeof(response),
1514 MSG_DONTWAIT, (struct sockaddr*)&addr, &addr_len);
1515 if (len < 0)
1516 {
1517 switch (errno)
1518 {
1519 case EINTR:
1520 /* interrupted, try again */
1521 return TRUE;
1522 case EAGAIN:
1523 /* no data ready, select again */
1524 return TRUE;
1525 default:
1526 DBG1(DBG_KNL, "unable to receive from RT event socket %s (%d)",
1527 strerror(errno), errno);
1528 sleep(1);
1529 return TRUE;
1530 }
1531 }
1532
1533 if (addr.nl_pid != 0)
1534 { /* not from kernel. not interested, try another one */
1535 return TRUE;
1536 }
1537
1538 while (NLMSG_OK(hdr, len))
1539 {
1540 /* looks good so far, dispatch netlink message */
1541 switch (hdr->nlmsg_type)
1542 {
1543 case RTM_NEWADDR:
1544 case RTM_DELADDR:
1545 process_addr(this, hdr, TRUE);
1546 break;
1547 case RTM_NEWLINK:
1548 case RTM_DELLINK:
1549 process_link(this, hdr, TRUE);
1550 break;
1551 case RTM_NEWROUTE:
1552 case RTM_DELROUTE:
1553 if (this->process_route)
1554 {
1555 process_route(this, hdr);
1556 }
1557 break;
1558 case RTM_NEWRULE:
1559 case RTM_DELRULE:
1560 if (this->process_rules)
1561 {
1562 process_rule(this, hdr);
1563 }
1564 break;
1565 default:
1566 break;
1567 }
1568 hdr = NLMSG_NEXT(hdr, len);
1569 }
1570 return TRUE;
1571 }
1572
1573 /** enumerator over addresses */
1574 typedef struct {
1575 private_kernel_netlink_net_t* this;
1576 /** which addresses to enumerate */
1577 kernel_address_type_t which;
1578 } address_enumerator_t;
1579
1580 CALLBACK(address_enumerator_destroy, void,
1581 address_enumerator_t *data)
1582 {
1583 data->this->lock->unlock(data->this->lock);
1584 free(data);
1585 }
1586
1587 CALLBACK(filter_addresses, bool,
1588 address_enumerator_t *data, enumerator_t *orig, va_list args)
1589 {
1590 addr_entry_t *addr;
1591 host_t **out;
1592
1593 VA_ARGS_VGET(args, out);
1594
1595 while (orig->enumerate(orig, &addr))
1596 {
1597 if (!(data->which & ADDR_TYPE_VIRTUAL) && addr->refcount)
1598 { /* skip virtual interfaces added by us */
1599 continue;
1600 }
1601 if (!(data->which & ADDR_TYPE_REGULAR) && !addr->refcount)
1602 { /* address is regular, but not requested */
1603 continue;
1604 }
1605 if (addr->scope >= RT_SCOPE_LINK)
1606 { /* skip addresses with a unusable scope */
1607 continue;
1608 }
1609 *out = addr->ip;
1610 return TRUE;
1611 }
1612 return FALSE;
1613 }
1614
1615 /**
1616 * enumerator constructor for interfaces
1617 */
1618 static enumerator_t *create_iface_enumerator(iface_entry_t *iface,
1619 address_enumerator_t *data)
1620 {
1621 return enumerator_create_filter(
1622 iface->addrs->create_enumerator(iface->addrs),
1623 filter_addresses, data, NULL);
1624 }
1625
1626 CALLBACK(filter_interfaces, bool,
1627 address_enumerator_t *data, enumerator_t *orig, va_list args)
1628 {
1629 iface_entry_t *iface, **out;
1630
1631 VA_ARGS_VGET(args, out);
1632
1633 while (orig->enumerate(orig, &iface))
1634 {
1635 if (!(data->which & ADDR_TYPE_IGNORED) && !iface->usable)
1636 { /* skip interfaces excluded by config */
1637 continue;
1638 }
1639 if (!(data->which & ADDR_TYPE_LOOPBACK) && (iface->flags & IFF_LOOPBACK))
1640 { /* ignore loopback devices */
1641 continue;
1642 }
1643 if (!(data->which & ADDR_TYPE_DOWN) && !(iface->flags & IFF_UP))
1644 { /* skip interfaces not up */
1645 continue;
1646 }
1647 *out = iface;
1648 return TRUE;
1649 }
1650 return FALSE;
1651 }
1652
1653 METHOD(kernel_net_t, create_address_enumerator, enumerator_t*,
1654 private_kernel_netlink_net_t *this, kernel_address_type_t which)
1655 {
1656 address_enumerator_t *data;
1657
1658 INIT(data,
1659 .this = this,
1660 .which = which,
1661 );
1662
1663 this->lock->read_lock(this->lock);
1664 return enumerator_create_nested(
1665 enumerator_create_filter(
1666 this->ifaces->create_enumerator(this->ifaces),
1667 filter_interfaces, data, NULL),
1668 (void*)create_iface_enumerator, data,
1669 address_enumerator_destroy);
1670 }
1671
1672 METHOD(kernel_net_t, get_interface_name, bool,
1673 private_kernel_netlink_net_t *this, host_t* ip, char **name)
1674 {
1675 addr_map_entry_t *entry, lookup = {
1676 .ip = ip,
1677 };
1678
1679 if (ip->is_anyaddr(ip))
1680 {
1681 return FALSE;
1682 }
1683 this->lock->read_lock(this->lock);
1684 /* first try to find it on an up and usable interface */
1685 entry = this->addrs->get_match(this->addrs, &lookup,
1686 (void*)addr_map_entry_match_up_and_usable);
1687 if (entry)
1688 {
1689 if (name)
1690 {
1691 *name = strdup(entry->iface->ifname);
1692 DBG2(DBG_KNL, "%H is on interface %s", ip, *name);
1693 }
1694 this->lock->unlock(this->lock);
1695 return TRUE;
1696 }
1697 /* in a second step, consider virtual IPs installed by us */
1698 entry = this->vips->get_match(this->vips, &lookup,
1699 (void*)addr_map_entry_match_up_and_usable);
1700 if (entry)
1701 {
1702 if (name)
1703 {
1704 *name = strdup(entry->iface->ifname);
1705 DBG2(DBG_KNL, "virtual IP %H is on interface %s", ip, *name);
1706 }
1707 this->lock->unlock(this->lock);
1708 return TRUE;
1709 }
1710 /* maybe it is installed on an ignored interface */
1711 entry = this->addrs->get_match(this->addrs, &lookup,
1712 (void*)addr_map_entry_match_up);
1713 if (!entry)
1714 {
1715 DBG2(DBG_KNL, "%H is not a local address or the interface is down", ip);
1716 }
1717 this->lock->unlock(this->lock);
1718 return FALSE;
1719 }
1720
1721 /**
1722 * get the index of an interface by name
1723 */
1724 static int get_interface_index(private_kernel_netlink_net_t *this, char* name)
1725 {
1726 iface_entry_t *iface;
1727 int ifindex = 0;
1728
1729 DBG2(DBG_KNL, "getting iface index for %s", name);
1730
1731 this->lock->read_lock(this->lock);
1732 if (this->ifaces->find_first(this->ifaces, iface_entry_by_name,
1733 (void**)&iface, name))
1734 {
1735 ifindex = iface->ifindex;
1736 }
1737 this->lock->unlock(this->lock);
1738
1739 if (ifindex == 0)
1740 {
1741 DBG1(DBG_KNL, "unable to get interface index for %s", name);
1742 }
1743 return ifindex;
1744 }
1745
1746 /**
1747 * get the name of an interface by index (allocated)
1748 */
1749 static char *get_interface_name_by_index(private_kernel_netlink_net_t *this,
1750 int index)
1751 {
1752 iface_entry_t *iface;
1753 char *name = NULL;
1754
1755 DBG2(DBG_KNL, "getting iface name for index %d", index);
1756
1757 this->lock->read_lock(this->lock);
1758 if (this->ifaces->find_first(this->ifaces, iface_entry_by_index,
1759 (void**)&iface, index))
1760 {
1761 name = strdup(iface->ifname);
1762 }
1763 this->lock->unlock(this->lock);
1764
1765 if (!name)
1766 {
1767 DBG1(DBG_KNL, "unable to get interface name for %d", index);
1768 }
1769 return name;
1770 }
1771
1772 /**
1773 * Store information about a route retrieved via RTNETLINK
1774 */
1775 typedef struct {
1776 chunk_t gtw;
1777 chunk_t pref_src;
1778 chunk_t dst;
1779 chunk_t src;
1780 host_t *src_host;
1781 uint8_t dst_len;
1782 uint8_t src_len;
1783 uint32_t table;
1784 uint32_t oif;
1785 uint32_t priority;
1786 } rt_entry_t;
1787
1788 /**
1789 * Free a route entry
1790 */
1791 static void rt_entry_destroy(rt_entry_t *this)
1792 {
1793 DESTROY_IF(this->src_host);
1794 free(this);
1795 }
1796
1797 /**
1798 * Check if the route received with RTM_NEWROUTE is usable based on its type.
1799 */
1800 static bool route_usable(struct nlmsghdr *hdr, bool allow_local)
1801 {
1802 struct rtmsg *msg;
1803
1804 msg = NLMSG_DATA(hdr);
1805 switch (msg->rtm_type)
1806 {
1807 case RTN_BLACKHOLE:
1808 case RTN_UNREACHABLE:
1809 case RTN_PROHIBIT:
1810 case RTN_THROW:
1811 return FALSE;
1812 case RTN_LOCAL:
1813 return allow_local;
1814 default:
1815 return TRUE;
1816 }
1817 }
1818
1819 /**
1820 * Parse route received with RTM_NEWROUTE. The given rt_entry_t object will be
1821 * reused if not NULL.
1822 *
1823 * Returned chunks point to internal data of the Netlink message.
1824 */
1825 static rt_entry_t *parse_route(struct nlmsghdr *hdr, rt_entry_t *route)
1826 {
1827 struct rtattr *rta;
1828 struct rtmsg *msg;
1829 size_t rtasize;
1830
1831 msg = NLMSG_DATA(hdr);
1832 rta = RTM_RTA(msg);
1833 rtasize = RTM_PAYLOAD(hdr);
1834
1835 if (route)
1836 {
1837 *route = (rt_entry_t){
1838 .dst_len = msg->rtm_dst_len,
1839 .src_len = msg->rtm_src_len,
1840 .table = msg->rtm_table,
1841 };
1842 }
1843 else
1844 {
1845 INIT(route,
1846 .dst_len = msg->rtm_dst_len,
1847 .src_len = msg->rtm_src_len,
1848 .table = msg->rtm_table,
1849 );
1850 }
1851
1852 while (RTA_OK(rta, rtasize))
1853 {
1854 switch (rta->rta_type)
1855 {
1856 case RTA_PREFSRC:
1857 route->pref_src = chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta));
1858 break;
1859 case RTA_GATEWAY:
1860 route->gtw = chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta));
1861 break;
1862 case RTA_DST:
1863 route->dst = chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta));
1864 break;
1865 case RTA_SRC:
1866 route->src = chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta));
1867 break;
1868 case RTA_OIF:
1869 if (RTA_PAYLOAD(rta) == sizeof(route->oif))
1870 {
1871 route->oif = *(uint32_t*)RTA_DATA(rta);
1872 }
1873 break;
1874 case RTA_PRIORITY:
1875 if (RTA_PAYLOAD(rta) == sizeof(route->priority))
1876 {
1877 route->priority = *(uint32_t*)RTA_DATA(rta);
1878 }
1879 break;
1880 #ifdef HAVE_RTA_TABLE
1881 case RTA_TABLE:
1882 if (RTA_PAYLOAD(rta) == sizeof(route->table))
1883 {
1884 route->table = *(uint32_t*)RTA_DATA(rta);
1885 }
1886 break;
1887 #endif /* HAVE_RTA_TABLE*/
1888 }
1889 rta = RTA_NEXT(rta, rtasize);
1890 }
1891 return route;
1892 }
1893
1894 /**
1895 * Get a route: If "nexthop", the nexthop is returned. source addr otherwise.
1896 */
1897 static host_t *get_route(private_kernel_netlink_net_t *this, host_t *dest,
1898 int prefix, bool nexthop, host_t *candidate,
1899 char **iface, u_int recursion)
1900 {
1901 netlink_buf_t request;
1902 struct nlmsghdr *hdr, *out, *current;
1903 struct rtmsg *msg;
1904 chunk_t chunk;
1905 size_t len;
1906 linked_list_t *routes;
1907 rt_entry_t *route = NULL, *best = NULL;
1908 enumerator_t *enumerator;
1909 host_t *addr = NULL;
1910 bool match_net;
1911 int family;
1912
1913 if (recursion > MAX_ROUTE_RECURSION)
1914 {
1915 return NULL;
1916 }
1917 chunk = dest->get_address(dest);
1918 len = chunk.len * 8;
1919 prefix = prefix < 0 ? len : min(prefix, len);
1920 match_net = prefix != len;
1921
1922 memset(&request, 0, sizeof(request));
1923
1924 family = dest->get_family(dest);
1925 hdr = &request.hdr;
1926 hdr->nlmsg_flags = NLM_F_REQUEST;
1927 hdr->nlmsg_type = RTM_GETROUTE;
1928 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
1929
1930 msg = NLMSG_DATA(hdr);
1931 msg->rtm_family = family;
1932 if (!match_net && this->rta_mark && this->routing_mark.value)
1933 {
1934 /* if our routing rule excludes packets with a certain mark we can
1935 * get the preferred route without having to dump all routes */
1936 chunk = chunk_from_thing(this->routing_mark.value);
1937 netlink_add_attribute(hdr, RTA_MARK, chunk, sizeof(request));
1938 }
1939 else if (family == AF_INET || this->rta_prefsrc_for_ipv6 ||
1940 this->routing_table || match_net)
1941 { /* kernels prior to 3.0 do not support RTA_PREFSRC for IPv6 routes.
1942 * as we want to ignore routes with virtual IPs we cannot use DUMP
1943 * if these routes are not installed in a separate table */
1944 if (this->install_routes)
1945 {
1946 hdr->nlmsg_flags |= NLM_F_DUMP;
1947 }
1948 }
1949 if (candidate)
1950 {
1951 chunk = candidate->get_address(candidate);
1952 if (hdr->nlmsg_flags & NLM_F_DUMP)
1953 {
1954 netlink_add_attribute(hdr, RTA_PREFSRC, chunk, sizeof(request));
1955 }
1956 else
1957 {
1958 netlink_add_attribute(hdr, RTA_SRC, chunk, sizeof(request));
1959 }
1960 }
1961 /* we use this below to match against the routes */
1962 chunk = dest->get_address(dest);
1963 if (!match_net)
1964 {
1965 netlink_add_attribute(hdr, RTA_DST, chunk, sizeof(request));
1966 }
1967
1968 if (this->socket->send(this->socket, hdr, &out, &len) != SUCCESS)
1969 {
1970 DBG2(DBG_KNL, "getting %s to reach %H/%d failed",
1971 nexthop ? "nexthop" : "address", dest, prefix);
1972 return NULL;
1973 }
1974 routes = linked_list_create();
1975 this->lock->read_lock(this->lock);
1976
1977 for (current = out; NLMSG_OK(current, len);
1978 current = NLMSG_NEXT(current, len))
1979 {
1980 switch (current->nlmsg_type)
1981 {
1982 case NLMSG_DONE:
1983 break;
1984 case RTM_NEWROUTE:
1985 {
1986 rt_entry_t *other;
1987 uintptr_t table;
1988
1989 if (!route_usable(current, TRUE))
1990 {
1991 continue;
1992 }
1993 route = parse_route(current, route);
1994
1995 table = (uintptr_t)route->table;
1996 if (this->rt_exclude->find_first(this->rt_exclude, NULL,
1997 (void**)&table))
1998 { /* route is from an excluded routing table */
1999 continue;
2000 }
2001 if (this->routing_table != 0 &&
2002 route->table == this->routing_table)
2003 { /* route is from our own ipsec routing table */
2004 continue;
2005 }
2006 if (route->oif && !is_interface_up_and_usable(this, route->oif))
2007 { /* interface is down */
2008 continue;
2009 }
2010 if (!addr_in_subnet(chunk, prefix, route->dst, route->dst_len))
2011 { /* route destination does not contain dest */
2012 continue;
2013 }
2014 if (route->pref_src.ptr)
2015 { /* verify source address, if any */
2016 host_t *src = host_create_from_chunk(msg->rtm_family,
2017 route->pref_src, 0);
2018 if (src && is_known_vip(this, src))
2019 { /* ignore routes installed by us */
2020 src->destroy(src);
2021 continue;
2022 }
2023 route->src_host = src;
2024 }
2025 /* insert route, sorted by network prefix and priority */
2026 enumerator = routes->create_enumerator(routes);
2027 while (enumerator->enumerate(enumerator, &other))
2028 {
2029 if (route->dst_len > other->dst_len)
2030 {
2031 break;
2032 }
2033 if (route->dst_len == other->dst_len &&
2034 route->priority < other->priority)
2035 {
2036 break;
2037 }
2038 }
2039 routes->insert_before(routes, enumerator, route);
2040 enumerator->destroy(enumerator);
2041 route = NULL;
2042 continue;
2043 }
2044 default:
2045 continue;
2046 }
2047 break;
2048 }
2049 if (route)
2050 {
2051 rt_entry_destroy(route);
2052 }
2053
2054 /* now we have a list of routes matching dest, sorted by net prefix.
2055 * we will look for source addresses for these routes and select the one
2056 * with the preferred source address, if possible */
2057 enumerator = routes->create_enumerator(routes);
2058 while (enumerator->enumerate(enumerator, &route))
2059 {
2060 if (route->src_host)
2061 { /* got a source address with the route, if no preferred source
2062 * is given or it matches we are done, as this is the best route */
2063 if (!candidate || candidate->ip_equals(candidate, route->src_host))
2064 {
2065 best = route;
2066 break;
2067 }
2068 else if (route->oif)
2069 { /* no match yet, maybe it is assigned to the same interface */
2070 host_t *src = get_interface_address(this, route->oif,
2071 msg->rtm_family, dest, candidate);
2072 if (src && src->ip_equals(src, candidate))
2073 {
2074 route->src_host->destroy(route->src_host);
2075 route->src_host = src;
2076 best = route;
2077 break;
2078 }
2079 DESTROY_IF(src);
2080 }
2081 /* no luck yet with the source address. if this is the best (first)
2082 * route we store it as fallback in case we don't find a route with
2083 * the preferred source */
2084 best = best ?: route;
2085 continue;
2086 }
2087 if (route->src.ptr)
2088 { /* no src, but a source selector, try to find a matching address */
2089 route->src_host = get_subnet_address(this, msg->rtm_family,
2090 route->src, route->src_len, dest,
2091 candidate);
2092 if (route->src_host)
2093 { /* we handle this address the same as the one above */
2094 if (!candidate ||
2095 candidate->ip_equals(candidate, route->src_host))
2096 {
2097 best = route;
2098 break;
2099 }
2100 best = best ?: route;
2101 continue;
2102 }
2103 }
2104 if (route->oif)
2105 { /* no src, but an interface - get address from it */
2106 route->src_host = get_interface_address(this, route->oif,
2107 msg->rtm_family, dest, candidate);
2108 if (route->src_host)
2109 { /* more of the same */
2110 if (!candidate ||
2111 candidate->ip_equals(candidate, route->src_host))
2112 {
2113 best = route;
2114 break;
2115 }
2116 best = best ?: route;
2117 continue;
2118 }
2119 }
2120 if (route->gtw.ptr)
2121 { /* no src, no iface, but a gateway - lookup src to reach gtw */
2122 host_t *gtw;
2123
2124 gtw = host_create_from_chunk(msg->rtm_family, route->gtw, 0);
2125 if (gtw && !gtw->ip_equals(gtw, dest))
2126 {
2127 route->src_host = get_route(this, gtw, -1, FALSE, candidate,
2128 iface, recursion + 1);
2129 }
2130 DESTROY_IF(gtw);
2131 if (route->src_host)
2132 { /* more of the same */
2133 if (!candidate ||
2134 candidate->ip_equals(candidate, route->src_host))
2135 {
2136 best = route;
2137 break;
2138 }
2139 best = best ?: route;
2140 }
2141 }
2142 }
2143 enumerator->destroy(enumerator);
2144
2145 if (nexthop)
2146 { /* nexthop lookup, return gateway and oif if any */
2147 if (iface)
2148 {
2149 *iface = NULL;
2150 }
2151 if (best || routes->get_first(routes, (void**)&best) == SUCCESS)
2152 {
2153 addr = host_create_from_chunk(msg->rtm_family, best->gtw, 0);
2154 if (iface && best->oif)
2155 {
2156 *iface = get_interface_name_by_index(this, best->oif);
2157 }
2158 }
2159 if (!addr && !match_net)
2160 { /* fallback to destination address */
2161 addr = dest->clone(dest);
2162 }
2163 }
2164 else
2165 {
2166 if (best)
2167 {
2168 addr = best->src_host->clone(best->src_host);
2169 }
2170 }
2171 this->lock->unlock(this->lock);
2172 routes->destroy_function(routes, (void*)rt_entry_destroy);
2173 free(out);
2174
2175 if (addr)
2176 {
2177 if (nexthop && iface && *iface)
2178 {
2179 DBG2(DBG_KNL, "using %H as nexthop and %s as dev to reach %H/%d",
2180 addr, *iface, dest, prefix);
2181 }
2182 else
2183 {
2184 DBG2(DBG_KNL, "using %H as %s to reach %H/%d", addr,
2185 nexthop ? "nexthop" : "address", dest, prefix);
2186 }
2187 }
2188 else if (!recursion)
2189 {
2190 DBG2(DBG_KNL, "no %s found to reach %H/%d",
2191 nexthop ? "nexthop" : "address", dest, prefix);
2192 }
2193 return addr;
2194 }
2195
2196 METHOD(kernel_net_t, get_source_addr, host_t*,
2197 private_kernel_netlink_net_t *this, host_t *dest, host_t *src)
2198 {
2199 return get_route(this, dest, -1, FALSE, src, NULL, 0);
2200 }
2201
2202 METHOD(kernel_net_t, get_nexthop, host_t*,
2203 private_kernel_netlink_net_t *this, host_t *dest, int prefix, host_t *src,
2204 char **iface)
2205 {
2206 return get_route(this, dest, prefix, TRUE, src, iface, 0);
2207 }
2208
2209 /** enumerator over subnets */
2210 typedef struct {
2211 enumerator_t public;
2212 private_kernel_netlink_net_t *private;
2213 /** message from the kernel */
2214 struct nlmsghdr *msg;
2215 /** current message from the kernel */
2216 struct nlmsghdr *current;
2217 /** remaining length */
2218 size_t len;
2219 /** last subnet enumerated */
2220 host_t *net;
2221 /** interface of current net */
2222 char ifname[IFNAMSIZ];
2223 } subnet_enumerator_t;
2224
2225 METHOD(enumerator_t, destroy_subnet_enumerator, void,
2226 subnet_enumerator_t *this)
2227 {
2228 DESTROY_IF(this->net);
2229 free(this->msg);
2230 free(this);
2231 }
2232
2233 METHOD(enumerator_t, enumerate_subnets, bool,
2234 subnet_enumerator_t *this, va_list args)
2235 {
2236 host_t **net;
2237 uint8_t *mask;
2238 char **ifname;
2239
2240 VA_ARGS_VGET(args, net, mask, ifname);
2241
2242 if (!this->current)
2243 {
2244 this->current = this->msg;
2245 }
2246 else
2247 {
2248 this->current = NLMSG_NEXT(this->current, this->len);
2249 DESTROY_IF(this->net);
2250 this->net = NULL;
2251 }
2252
2253 while (NLMSG_OK(this->current, this->len))
2254 {
2255 switch (this->current->nlmsg_type)
2256 {
2257 case NLMSG_DONE:
2258 break;
2259 case RTM_NEWROUTE:
2260 {
2261 rt_entry_t route;
2262
2263 if (!route_usable(this->current, FALSE))
2264 {
2265 break;
2266 }
2267 parse_route(this->current, &route);
2268
2269 if (route.table && (
2270 route.table == RT_TABLE_LOCAL ||
2271 route.table == this->private->routing_table))
2272 { /* ignore our own and the local routing tables */
2273 break;
2274 }
2275 else if (route.gtw.ptr)
2276 { /* ignore routes via gateway/next hop */
2277 break;
2278 }
2279
2280 if (route.dst.ptr && route.oif &&
2281 if_indextoname(route.oif, this->ifname))
2282 {
2283 this->net = host_create_from_chunk(AF_UNSPEC, route.dst, 0);
2284 *net = this->net;
2285 *mask = route.dst_len;
2286 *ifname = this->ifname;
2287 return TRUE;
2288 }
2289 break;
2290 }
2291 default:
2292 break;
2293 }
2294 this->current = NLMSG_NEXT(this->current, this->len);
2295 }
2296 return FALSE;
2297 }
2298
2299 METHOD(kernel_net_t, create_local_subnet_enumerator, enumerator_t*,
2300 private_kernel_netlink_net_t *this)
2301 {
2302 netlink_buf_t request;
2303 struct nlmsghdr *hdr, *out;
2304 struct rtmsg *msg;
2305 size_t len;
2306 subnet_enumerator_t *enumerator;
2307
2308 memset(&request, 0, sizeof(request));
2309
2310 hdr = &request.hdr;
2311 hdr->nlmsg_flags = NLM_F_REQUEST;
2312 hdr->nlmsg_type = RTM_GETROUTE;
2313 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
2314 hdr->nlmsg_flags |= NLM_F_DUMP;
2315
2316 msg = NLMSG_DATA(hdr);
2317 msg->rtm_scope = RT_SCOPE_LINK;
2318
2319 if (this->socket->send(this->socket, hdr, &out, &len) != SUCCESS)
2320 {
2321 DBG2(DBG_KNL, "enumerating local subnets failed");
2322 return enumerator_create_empty();
2323 }
2324
2325 INIT(enumerator,
2326 .public = {
2327 .enumerate = enumerator_enumerate_default,
2328 .venumerate = _enumerate_subnets,
2329 .destroy = _destroy_subnet_enumerator,
2330 },
2331 .private = this,
2332 .msg = out,
2333 .len = len,
2334 );
2335 return &enumerator->public;
2336 }
2337
2338 /**
2339 * Manages the creation and deletion of ip addresses on an interface.
2340 * By setting the appropriate nlmsg_type, the ip will be set or unset.
2341 */
2342 static status_t manage_ipaddr(private_kernel_netlink_net_t *this, int nlmsg_type,
2343 int flags, int if_index, host_t *ip, int prefix)
2344 {
2345 netlink_buf_t request;
2346 struct nlmsghdr *hdr;
2347 struct ifaddrmsg *msg;
2348 chunk_t chunk;
2349
2350 memset(&request, 0, sizeof(request));
2351
2352 chunk = ip->get_address(ip);
2353
2354 hdr = &request.hdr;
2355 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
2356 hdr->nlmsg_type = nlmsg_type;
2357 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg));
2358
2359 msg = NLMSG_DATA(hdr);
2360 msg->ifa_family = ip->get_family(ip);
2361 msg->ifa_flags = 0;
2362 msg->ifa_prefixlen = prefix < 0 ? chunk.len * 8 : prefix;
2363 msg->ifa_scope = RT_SCOPE_UNIVERSE;
2364 msg->ifa_index = if_index;
2365
2366 netlink_add_attribute(hdr, IFA_LOCAL, chunk, sizeof(request));
2367
2368 if (ip->get_family(ip) == AF_INET6)
2369 {
2370 #ifdef IFA_F_NODAD
2371 msg->ifa_flags |= IFA_F_NODAD;
2372 #endif
2373 if (this->rta_prefsrc_for_ipv6)
2374 {
2375 /* if source routes are possible we let the virtual IP get
2376 * deprecated immediately (but mark it as valid forever) so it gets
2377 * only used if forced by our route, and not by the default IPv6
2378 * address selection */
2379 struct ifa_cacheinfo cache = {
2380 .ifa_valid = 0xFFFFFFFF,
2381 .ifa_prefered = 0,
2382 };
2383 netlink_add_attribute(hdr, IFA_CACHEINFO, chunk_from_thing(cache),
2384 sizeof(request));
2385 }
2386 }
2387 return this->socket->send_ack(this->socket, hdr);
2388 }
2389
2390 METHOD(kernel_net_t, add_ip, status_t,
2391 private_kernel_netlink_net_t *this, host_t *virtual_ip, int prefix,
2392 char *iface_name)
2393 {
2394 addr_map_entry_t *entry, lookup = {
2395 .ip = virtual_ip,
2396 };
2397 iface_entry_t *iface = NULL;
2398
2399 if (!this->install_virtual_ip)
2400 { /* disabled by config */
2401 return SUCCESS;
2402 }
2403
2404 this->lock->write_lock(this->lock);
2405 /* the virtual IP might actually be installed as regular IP, in which case
2406 * we don't track it as virtual IP */
2407 entry = this->addrs->get_match(this->addrs, &lookup,
2408 (void*)addr_map_entry_match);
2409 if (!entry)
2410 { /* otherwise it might already be installed as virtual IP */
2411 entry = this->vips->get_match(this->vips, &lookup,
2412 (void*)addr_map_entry_match);
2413 if (entry)
2414 { /* the vip we found can be in one of three states: 1) installed and
2415 * ready, 2) just added by another thread, but not yet confirmed to
2416 * be installed by the kernel, 3) just deleted, but not yet gone.
2417 * Then while we wait below, several things could happen (as we
2418 * release the lock). For instance, the interface could disappear,
2419 * or the IP is finally deleted, and it reappears on a different
2420 * interface. All these cases are handled by the call below. */
2421 while (!is_vip_installed_or_gone(this, virtual_ip, &entry))
2422 {
2423 this->condvar->wait(this->condvar, this->lock);
2424 }
2425 if (entry)
2426 {
2427 entry->addr->refcount++;
2428 }
2429 }
2430 }
2431 if (entry)
2432 {
2433 DBG2(DBG_KNL, "virtual IP %H is already installed on %s", virtual_ip,
2434 entry->iface->ifname);
2435 this->lock->unlock(this->lock);
2436 return SUCCESS;
2437 }
2438 /* try to find the target interface, either by config or via src ip */
2439 if (!this->install_virtual_ip_on ||
2440 !this->ifaces->find_first(this->ifaces, iface_entry_by_name,
2441 (void**)&iface, this->install_virtual_ip_on))
2442 {
2443 if (!this->ifaces->find_first(this->ifaces, iface_entry_by_name,
2444 (void**)&iface, iface_name))
2445 { /* if we don't find the requested interface we just use the first */
2446 this->ifaces->get_first(this->ifaces, (void**)&iface);
2447 }
2448 }
2449 if (iface)
2450 {
2451 addr_entry_t *addr;
2452 char *ifname;
2453 int ifi;
2454
2455 INIT(addr,
2456 .ip = virtual_ip->clone(virtual_ip),
2457 .refcount = 1,
2458 .scope = RT_SCOPE_UNIVERSE,
2459 );
2460 iface->addrs->insert_last(iface->addrs, addr);
2461 addr_map_entry_add(this->vips, addr, iface);
2462 ifi = iface->ifindex;
2463 this->lock->unlock(this->lock);
2464 if (manage_ipaddr(this, RTM_NEWADDR, NLM_F_CREATE | NLM_F_EXCL,
2465 ifi, virtual_ip, prefix) == SUCCESS)
2466 {
2467 this->lock->write_lock(this->lock);
2468 while (!is_vip_installed_or_gone(this, virtual_ip, &entry))
2469 { /* wait until address appears */
2470 this->condvar->wait(this->condvar, this->lock);
2471 }
2472 if (entry)
2473 { /* we fail if the interface got deleted in the meantime */
2474 ifname = strdup(entry->iface->ifname);
2475 this->lock->unlock(this->lock);
2476 DBG2(DBG_KNL, "virtual IP %H installed on %s",
2477 virtual_ip, ifname);
2478 /* during IKEv1 reauthentication, children get moved from
2479 * old the new SA before the virtual IP is available. This
2480 * kills the route for our virtual IP, reinstall. */
2481 queue_route_reinstall(this, ifname);
2482 return SUCCESS;
2483 }
2484 this->lock->unlock(this->lock);
2485 }
2486 DBG1(DBG_KNL, "adding virtual IP %H failed", virtual_ip);
2487 return FAILED;
2488 }
2489 this->lock->unlock(this->lock);
2490 DBG1(DBG_KNL, "no interface available, unable to install virtual IP %H",
2491 virtual_ip);
2492 return FAILED;
2493 }
2494
2495 METHOD(kernel_net_t, del_ip, status_t,
2496 private_kernel_netlink_net_t *this, host_t *virtual_ip, int prefix,
2497 bool wait)
2498 {
2499 addr_map_entry_t *entry, lookup = {
2500 .ip = virtual_ip,
2501 };
2502
2503 if (!this->install_virtual_ip)
2504 { /* disabled by config */
2505 return SUCCESS;
2506 }
2507
2508 DBG2(DBG_KNL, "deleting virtual IP %H", virtual_ip);
2509
2510 this->lock->write_lock(this->lock);
2511 entry = this->vips->get_match(this->vips, &lookup,
2512 (void*)addr_map_entry_match);
2513 if (!entry)
2514 { /* we didn't install this IP as virtual IP */
2515 entry = this->addrs->get_match(this->addrs, &lookup,
2516 (void*)addr_map_entry_match);
2517 if (entry)
2518 {
2519 DBG2(DBG_KNL, "not deleting existing IP %H on %s", virtual_ip,
2520 entry->iface->ifname);
2521 this->lock->unlock(this->lock);
2522 return SUCCESS;
2523 }
2524 DBG2(DBG_KNL, "virtual IP %H not cached, unable to delete", virtual_ip);
2525 this->lock->unlock(this->lock);
2526 return FAILED;
2527 }
2528 if (entry->addr->refcount == 1)
2529 {
2530 status_t status;
2531 int ifi;
2532
2533 /* we set this flag so that threads calling add_ip will block and wait
2534 * until the entry is gone, also so we can wait below */
2535 entry->addr->installed = FALSE;
2536 ifi = entry->iface->ifindex;
2537 this->lock->unlock(this->lock);
2538 status = manage_ipaddr(this, RTM_DELADDR, 0, ifi, virtual_ip, prefix);
2539 if (status == SUCCESS && wait)
2540 { /* wait until the address is really gone */
2541 this->lock->write_lock(this->lock);
2542 while (is_known_vip(this, virtual_ip))
2543 {
2544 this->condvar->wait(this->condvar, this->lock);
2545 }
2546 this->lock->unlock(this->lock);
2547 }
2548 return status;
2549 }
2550 else
2551 {
2552 entry->addr->refcount--;
2553 }
2554 DBG2(DBG_KNL, "virtual IP %H used by other SAs, not deleting",
2555 virtual_ip);
2556 this->lock->unlock(this->lock);
2557 return SUCCESS;
2558 }
2559
2560 /**
2561 * Manages source routes in the routing table.
2562 * By setting the appropriate nlmsg_type, the route gets added or removed.
2563 */
2564 static status_t manage_srcroute(private_kernel_netlink_net_t *this,
2565 int nlmsg_type, int flags, chunk_t dst_net,
2566 uint8_t prefixlen, host_t *gateway,
2567 host_t *src_ip, char *if_name)
2568 {
2569 netlink_buf_t request;
2570 struct nlmsghdr *hdr;
2571 struct rtmsg *msg;
2572 struct rtattr *rta;
2573 int ifindex;
2574 chunk_t chunk;
2575
2576 /* if route is 0.0.0.0/0, we can't install it, as it would
2577 * overwrite the default route. Instead, we add two routes:
2578 * 0.0.0.0/1 and 128.0.0.0/1 */
2579 if (this->routing_table == 0 && prefixlen == 0)
2580 {
2581 chunk_t half_net;
2582 uint8_t half_prefixlen;
2583 status_t status;
2584
2585 half_net = chunk_alloca(dst_net.len);
2586 memset(half_net.ptr, 0, half_net.len);
2587 half_prefixlen = 1;
2588
2589 status = manage_srcroute(this, nlmsg_type, flags, half_net,
2590 half_prefixlen, gateway, src_ip, if_name);
2591 half_net.ptr[0] |= 0x80;
2592 status |= manage_srcroute(this, nlmsg_type, flags, half_net,
2593 half_prefixlen, gateway, src_ip, if_name);
2594 return status;
2595 }
2596
2597 memset(&request, 0, sizeof(request));
2598
2599 hdr = &request.hdr;
2600 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
2601 hdr->nlmsg_type = nlmsg_type;
2602 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
2603
2604 msg = NLMSG_DATA(hdr);
2605 msg->rtm_family = src_ip->get_family(src_ip);
2606 msg->rtm_dst_len = prefixlen;
2607 msg->rtm_table = this->routing_table;
2608 msg->rtm_protocol = RTPROT_STATIC;
2609 msg->rtm_type = RTN_UNICAST;
2610 msg->rtm_scope = RT_SCOPE_UNIVERSE;
2611
2612 netlink_add_attribute(hdr, RTA_DST, dst_net, sizeof(request));
2613 chunk = src_ip->get_address(src_ip);
2614 netlink_add_attribute(hdr, RTA_PREFSRC, chunk, sizeof(request));
2615 if (gateway && gateway->get_family(gateway) == src_ip->get_family(src_ip))
2616 {
2617 chunk = gateway->get_address(gateway);
2618 netlink_add_attribute(hdr, RTA_GATEWAY, chunk, sizeof(request));
2619 }
2620 ifindex = get_interface_index(this, if_name);
2621 chunk.ptr = (char*)&ifindex;
2622 chunk.len = sizeof(ifindex);
2623 netlink_add_attribute(hdr, RTA_OIF, chunk, sizeof(request));
2624
2625 if (this->mtu || this->mss)
2626 {
2627 chunk = chunk_alloca(RTA_LENGTH((sizeof(struct rtattr) +
2628 sizeof(uint32_t)) * 2));
2629 chunk.len = 0;
2630 rta = (struct rtattr*)chunk.ptr;
2631 if (this->mtu)
2632 {
2633 rta->rta_type = RTAX_MTU;
2634 rta->rta_len = RTA_LENGTH(sizeof(uint32_t));
2635 memcpy(RTA_DATA(rta), &this->mtu, sizeof(uint32_t));
2636 chunk.len = rta->rta_len;
2637 }
2638 if (this->mss)
2639 {
2640 rta = (struct rtattr*)(chunk.ptr + RTA_ALIGN(chunk.len));
2641 rta->rta_type = RTAX_ADVMSS;
2642 rta->rta_len = RTA_LENGTH(sizeof(uint32_t));
2643 memcpy(RTA_DATA(rta), &this->mss, sizeof(uint32_t));
2644 chunk.len = RTA_ALIGN(chunk.len) + rta->rta_len;
2645 }
2646 netlink_add_attribute(hdr, RTA_METRICS, chunk, sizeof(request));
2647 }
2648
2649 return this->socket->send_ack(this->socket, hdr);
2650 }
2651
2652 /**
2653 * Helper struct used to check routes
2654 */
2655 typedef struct {
2656 /** the entry we look for */
2657 route_entry_t route;
2658 /** kernel interface */
2659 private_kernel_netlink_net_t *this;
2660 } route_entry_lookup_t;
2661
2662 /**
2663 * Check if a matching route entry has a VIP associated
2664 */
2665 static bool route_with_vip(route_entry_lookup_t *a, route_entry_t *b)
2666 {
2667 if (chunk_equals(a->route.dst_net, b->dst_net) &&
2668 a->route.prefixlen == b->prefixlen &&
2669 is_known_vip(a->this, b->src_ip))
2670 {
2671 return TRUE;
2672 }
2673 return FALSE;
2674 }
2675
2676 /**
2677 * Check if there is any route entry with a matching destination
2678 */
2679 static bool route_with_dst(route_entry_lookup_t *a, route_entry_t *b)
2680 {
2681 if (chunk_equals(a->route.dst_net, b->dst_net) &&
2682 a->route.prefixlen == b->prefixlen)
2683 {
2684 return TRUE;
2685 }
2686 return FALSE;
2687 }
2688
2689 METHOD(kernel_net_t, add_route, status_t,
2690 private_kernel_netlink_net_t *this, chunk_t dst_net, uint8_t prefixlen,
2691 host_t *gateway, host_t *src_ip, char *if_name)
2692 {
2693 status_t status;
2694 route_entry_t *found;
2695 route_entry_lookup_t lookup = {
2696 .route = {
2697 .dst_net = dst_net,
2698 .prefixlen = prefixlen,
2699 .gateway = gateway,
2700 .src_ip = src_ip,
2701 .if_name = if_name,
2702 },
2703 .this = this,
2704 };
2705
2706 this->routes_lock->lock(this->routes_lock);
2707 found = this->routes->get(this->routes, &lookup.route);
2708 if (found)
2709 {
2710 this->routes_lock->unlock(this->routes_lock);
2711 return ALREADY_DONE;
2712 }
2713
2714 /* don't replace the route if we already have one with a VIP installed,
2715 * but keep track of it in case that other route is uninstalled */
2716 this->lock->read_lock(this->lock);
2717 if (!is_known_vip(this, src_ip))
2718 {
2719 found = this->routes->get_match(this->routes, &lookup,
2720 (void*)route_with_vip);
2721 }
2722 this->lock->unlock(this->lock);
2723 if (found)
2724 {
2725 status = SUCCESS;
2726 }
2727 else
2728 {
2729 status = manage_srcroute(this, RTM_NEWROUTE, NLM_F_CREATE|NLM_F_REPLACE,
2730 dst_net, prefixlen, gateway, src_ip, if_name);
2731 }
2732 if (status == SUCCESS)
2733 {
2734 found = route_entry_clone(&lookup.route);
2735 this->routes->put(this->routes, found, found);
2736 }
2737 this->routes_lock->unlock(this->routes_lock);
2738 return status;
2739 }
2740
2741 METHOD(kernel_net_t, del_route, status_t,
2742 private_kernel_netlink_net_t *this, chunk_t dst_net, uint8_t prefixlen,
2743 host_t *gateway, host_t *src_ip, char *if_name)
2744 {
2745 status_t status;
2746 route_entry_t *found;
2747 route_entry_lookup_t lookup = {
2748 .route = {
2749 .dst_net = dst_net,
2750 .prefixlen = prefixlen,
2751 .gateway = gateway,
2752 .src_ip = src_ip,
2753 .if_name = if_name,
2754 },
2755 .this = this,
2756 };
2757
2758 this->routes_lock->lock(this->routes_lock);
2759 found = this->routes->remove(this->routes, &lookup.route);
2760 if (!found)
2761 {
2762 this->routes_lock->unlock(this->routes_lock);
2763 return NOT_FOUND;
2764 }
2765 route_entry_destroy(found);
2766
2767 /* check if there are any other routes for the same destination and if
2768 * so update the route, otherwise uninstall it */
2769 this->lock->read_lock(this->lock);
2770 found = this->routes->get_match(this->routes, &lookup,
2771 (void*)route_with_vip);
2772 this->lock->unlock(this->lock);
2773 if (!found)
2774 {
2775 found = this->routes->get_match(this->routes, &lookup,
2776 (void*)route_with_dst);
2777 }
2778 if (found)
2779 {
2780 status = manage_srcroute(this, RTM_NEWROUTE, NLM_F_CREATE|NLM_F_REPLACE,
2781 found->dst_net, found->prefixlen, found->gateway,
2782 found->src_ip, found->if_name);
2783 }
2784 else
2785 {
2786 status = manage_srcroute(this, RTM_DELROUTE, 0, dst_net, prefixlen,
2787 gateway, src_ip, if_name);
2788 }
2789 this->routes_lock->unlock(this->routes_lock);
2790 return status;
2791 }
2792
2793 /**
2794 * Initialize a list of local addresses.
2795 */
2796 static status_t init_address_list(private_kernel_netlink_net_t *this)
2797 {
2798 netlink_buf_t request;
2799 struct nlmsghdr *out, *current, *in;
2800 struct rtgenmsg *msg;
2801 size_t len;
2802 enumerator_t *ifaces, *addrs;
2803 iface_entry_t *iface;
2804 addr_entry_t *addr;
2805
2806 DBG2(DBG_KNL, "known interfaces and IP addresses:");
2807
2808 memset(&request, 0, sizeof(request));
2809
2810 in = &request.hdr;
2811 in->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg));
2812 in->nlmsg_flags = NLM_F_REQUEST | NLM_F_MATCH | NLM_F_ROOT;
2813 msg = NLMSG_DATA(in);
2814 msg->rtgen_family = AF_UNSPEC;
2815
2816 /* get all links */
2817 in->nlmsg_type = RTM_GETLINK;
2818 if (this->socket->send(this->socket, in, &out, &len) != SUCCESS)
2819 {
2820 return FAILED;
2821 }
2822 current = out;
2823 while (NLMSG_OK(current, len))
2824 {
2825 switch (current->nlmsg_type)
2826 {
2827 case NLMSG_DONE:
2828 break;
2829 case RTM_NEWLINK:
2830 process_link(this, current, FALSE);
2831 /* fall through */
2832 default:
2833 current = NLMSG_NEXT(current, len);
2834 continue;
2835 }
2836 break;
2837 }
2838 free(out);
2839
2840 /* get all interface addresses */
2841 in->nlmsg_type = RTM_GETADDR;
2842 if (this->socket->send(this->socket, in, &out, &len) != SUCCESS)
2843 {
2844 return FAILED;
2845 }
2846 current = out;
2847 while (NLMSG_OK(current, len))
2848 {
2849 switch (current->nlmsg_type)
2850 {
2851 case NLMSG_DONE:
2852 break;
2853 case RTM_NEWADDR:
2854 process_addr(this, current, FALSE);
2855 /* fall through */
2856 default:
2857 current = NLMSG_NEXT(current, len);
2858 continue;
2859 }
2860 break;
2861 }
2862 free(out);
2863
2864 this->lock->read_lock(this->lock);
2865 ifaces = this->ifaces->create_enumerator(this->ifaces);
2866 while (ifaces->enumerate(ifaces, &iface))
2867 {
2868 if (iface_entry_up_and_usable(iface))
2869 {
2870 DBG2(DBG_KNL, " %s", iface->ifname);
2871 addrs = iface->addrs->create_enumerator(iface->addrs);
2872 while (addrs->enumerate(addrs, (void**)&addr))
2873 {
2874 DBG2(DBG_KNL, " %H", addr->ip);
2875 }
2876 addrs->destroy(addrs);
2877 }
2878 }
2879 ifaces->destroy(ifaces);
2880 this->lock->unlock(this->lock);
2881 return SUCCESS;
2882 }
2883
2884 /**
2885 * create or delete a rule to use our routing table
2886 */
2887 static status_t manage_rule(private_kernel_netlink_net_t *this, int nlmsg_type,
2888 int family, uint32_t table, uint32_t prio)
2889 {
2890 netlink_buf_t request;
2891 struct nlmsghdr *hdr;
2892 struct rtmsg *msg;
2893 chunk_t chunk;
2894 char *fwmark;
2895
2896 memset(&request, 0, sizeof(request));
2897 hdr = &request.hdr;
2898 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2899 hdr->nlmsg_type = nlmsg_type;
2900 if (nlmsg_type == RTM_NEWRULE)
2901 {
2902 hdr->nlmsg_flags |= NLM_F_CREATE | NLM_F_EXCL;
2903 }
2904 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
2905
2906 msg = NLMSG_DATA(hdr);
2907 msg->rtm_table = table;
2908 msg->rtm_family = family;
2909 msg->rtm_protocol = RTPROT_BOOT;
2910 msg->rtm_scope = RT_SCOPE_UNIVERSE;
2911 msg->rtm_type = RTN_UNICAST;
2912
2913 chunk = chunk_from_thing(prio);
2914 netlink_add_attribute(hdr, RTA_PRIORITY, chunk, sizeof(request));
2915
2916 fwmark = lib->settings->get_str(lib->settings,
2917 "%s.plugins.kernel-netlink.fwmark", NULL, lib->ns);
2918 if (fwmark)
2919 {
2920 #ifdef HAVE_LINUX_FIB_RULES_H
2921 mark_t mark;
2922
2923 if (fwmark[0] == '!')
2924 {
2925 msg->rtm_flags |= FIB_RULE_INVERT;
2926 fwmark++;
2927 }
2928 if (mark_from_string(fwmark, MARK_OP_NONE, &mark))
2929 {
2930 chunk = chunk_from_thing(mark.value);
2931 netlink_add_attribute(hdr, FRA_FWMARK, chunk, sizeof(request));
2932 chunk = chunk_from_thing(mark.mask);
2933 netlink_add_attribute(hdr, FRA_FWMASK, chunk, sizeof(request));
2934 if (msg->rtm_flags & FIB_RULE_INVERT)
2935 {
2936 this->routing_mark = mark;
2937 }
2938 }
2939 #else
2940 DBG1(DBG_KNL, "setting firewall mark on routing rule is not supported");
2941 #endif
2942 }
2943 return this->socket->send_ack(this->socket, hdr);
2944 }
2945
2946 /**
2947 * check for kernel features (currently only via version number)
2948 */
2949 static void check_kernel_features(private_kernel_netlink_net_t *this)
2950 {
2951 struct utsname utsname;
2952 int a, b, c;
2953
2954 if (uname(&utsname) == 0)
2955 {
2956 switch(sscanf(utsname.release, "%d.%d.%d", &a, &b, &c))
2957 {
2958 case 3:
2959 if (a == 2)
2960 {
2961 if (b == 6 && c >= 36)
2962 {
2963 this->rta_mark = TRUE;
2964 }
2965 DBG2(DBG_KNL, "detected Linux %d.%d.%d, no support for "
2966 "RTA_PREFSRC for IPv6 routes", a, b, c);
2967 break;
2968 }
2969 /* fall-through */
2970 case 2:
2971 /* only 3.x+ uses two part version numbers */
2972 this->rta_prefsrc_for_ipv6 = TRUE;
2973 this->rta_mark = TRUE;
2974 break;
2975 default:
2976 break;
2977 }
2978 }
2979 }
2980
2981 /**
2982 * Destroy an address to iface map
2983 */
2984 static void addr_map_destroy(hashtable_t *map)
2985 {
2986 enumerator_t *enumerator;
2987 addr_map_entry_t *addr;
2988
2989 enumerator = map->create_enumerator(map);
2990 while (enumerator->enumerate(enumerator, NULL, (void**)&addr))
2991 {
2992 free(addr);
2993 }
2994 enumerator->destroy(enumerator);
2995 map->destroy(map);
2996 }
2997
2998 METHOD(kernel_net_t, destroy, void,
2999 private_kernel_netlink_net_t *this)
3000 {
3001 enumerator_t *enumerator;
3002 route_entry_t *route;
3003
3004 if (this->routing_table)
3005 {
3006 manage_rule(this, RTM_DELRULE, AF_INET, this->routing_table,
3007 this->routing_table_prio);
3008 manage_rule(this, RTM_DELRULE, AF_INET6, this->routing_table,
3009 this->routing_table_prio);
3010 }
3011 if (this->socket_events > 0)
3012 {
3013 lib->watcher->remove(lib->watcher, this->socket_events);
3014 close(this->socket_events);
3015 }
3016 enumerator = this->routes->create_enumerator(this->routes);
3017 while (enumerator->enumerate(enumerator, NULL, (void**)&route))
3018 {
3019 manage_srcroute(this, RTM_DELROUTE, 0, route->dst_net, route->prefixlen,
3020 route->gateway, route->src_ip, route->if_name);
3021 route_entry_destroy(route);
3022 }
3023 enumerator->destroy(enumerator);
3024 this->routes->destroy(this->routes);
3025 this->routes_lock->destroy(this->routes_lock);
3026 DESTROY_IF(this->socket);
3027
3028 net_changes_clear(this);
3029 this->net_changes->destroy(this->net_changes);
3030 this->net_changes_lock->destroy(this->net_changes_lock);
3031
3032 addr_map_destroy(this->addrs);
3033 addr_map_destroy(this->vips);
3034
3035 this->ifaces->destroy_function(this->ifaces, (void*)iface_entry_destroy);
3036 this->rt_exclude->destroy(this->rt_exclude);
3037 this->roam_lock->destroy(this->roam_lock);
3038 this->condvar->destroy(this->condvar);
3039 this->lock->destroy(this->lock);
3040 free(this);
3041 }
3042
3043 /*
3044 * Described in header.
3045 */
3046 kernel_netlink_net_t *kernel_netlink_net_create()
3047 {
3048 private_kernel_netlink_net_t *this;
3049 enumerator_t *enumerator;
3050 bool register_for_events = TRUE;
3051 char *exclude;
3052
3053 INIT(this,
3054 .public = {
3055 .interface = {
3056 .get_interface = _get_interface_name,
3057 .create_address_enumerator = _create_address_enumerator,
3058 .create_local_subnet_enumerator = _create_local_subnet_enumerator,
3059 .get_source_addr = _get_source_addr,
3060 .get_nexthop = _get_nexthop,
3061 .add_ip = _add_ip,
3062 .del_ip = _del_ip,
3063 .add_route = _add_route,
3064 .del_route = _del_route,
3065 .destroy = _destroy,
3066 },
3067 },
3068 .socket = netlink_socket_create(NETLINK_ROUTE, rt_msg_names,
3069 lib->settings->get_bool(lib->settings,
3070 "%s.plugins.kernel-netlink.parallel_route", FALSE, lib->ns)),
3071 .rt_exclude = linked_list_create(),
3072 .routes = hashtable_create((hashtable_hash_t)route_entry_hash,
3073 (hashtable_equals_t)route_entry_equals, 16),
3074 .net_changes = hashtable_create(
3075 (hashtable_hash_t)net_change_hash,
3076 (hashtable_equals_t)net_change_equals, 16),
3077 .addrs = hashtable_create(
3078 (hashtable_hash_t)addr_map_entry_hash,
3079 (hashtable_equals_t)addr_map_entry_equals, 16),
3080 .vips = hashtable_create((hashtable_hash_t)addr_map_entry_hash,
3081 (hashtable_equals_t)addr_map_entry_equals, 16),
3082 .routes_lock = mutex_create(MUTEX_TYPE_DEFAULT),
3083 .net_changes_lock = mutex_create(MUTEX_TYPE_DEFAULT),
3084 .ifaces = linked_list_create(),
3085 .lock = rwlock_create(RWLOCK_TYPE_DEFAULT),
3086 .condvar = rwlock_condvar_create(),
3087 .roam_lock = spinlock_create(),
3088 .routing_table = lib->settings->get_int(lib->settings,
3089 "%s.routing_table", ROUTING_TABLE, lib->ns),
3090 .routing_table_prio = lib->settings->get_int(lib->settings,
3091 "%s.routing_table_prio", ROUTING_TABLE_PRIO, lib->ns),
3092 .process_route = lib->settings->get_bool(lib->settings,
3093 "%s.process_route", TRUE, lib->ns),
3094 .install_routes = lib->settings->get_bool(lib->settings,
3095 "%s.install_routes", TRUE, lib->ns),
3096 .install_virtual_ip = lib->settings->get_bool(lib->settings,
3097 "%s.install_virtual_ip", TRUE, lib->ns),
3098 .install_virtual_ip_on = lib->settings->get_str(lib->settings,
3099 "%s.install_virtual_ip_on", NULL, lib->ns),
3100 .prefer_temporary_addrs = lib->settings->get_bool(lib->settings,
3101 "%s.prefer_temporary_addrs", FALSE, lib->ns),
3102 .roam_events = lib->settings->get_bool(lib->settings,
3103 "%s.plugins.kernel-netlink.roam_events", TRUE, lib->ns),
3104 .process_rules = lib->settings->get_bool(lib->settings,
3105 "%s.plugins.kernel-netlink.process_rules", FALSE, lib->ns),
3106 .mtu = lib->settings->get_int(lib->settings,
3107 "%s.plugins.kernel-netlink.mtu", 0, lib->ns),
3108 .mss = lib->settings->get_int(lib->settings,
3109 "%s.plugins.kernel-netlink.mss", 0, lib->ns),
3110 );
3111 timerclear(&this->last_route_reinstall);
3112 timerclear(&this->next_roam);
3113
3114 check_kernel_features(this);
3115
3116 if (streq(lib->ns, "starter"))
3117 { /* starter has no threads, so we do not register for kernel events */
3118 register_for_events = FALSE;
3119 }
3120
3121 exclude = lib->settings->get_str(lib->settings,
3122 "%s.ignore_routing_tables", NULL, lib->ns);
3123 if (exclude)
3124 {
3125 char *token;
3126 uintptr_t table;
3127
3128 enumerator = enumerator_create_token(exclude, " ", " ");
3129 while (enumerator->enumerate(enumerator, &token))
3130 {
3131 errno = 0;
3132 table = strtoul(token, NULL, 10);
3133
3134 if (errno == 0)
3135 {
3136 this->rt_exclude->insert_last(this->rt_exclude, (void*)table);
3137 }
3138 }
3139 enumerator->destroy(enumerator);
3140 }
3141
3142 if (register_for_events)
3143 {
3144 struct sockaddr_nl addr;
3145
3146 memset(&addr, 0, sizeof(addr));
3147 addr.nl_family = AF_NETLINK;
3148
3149 /* create and bind RT socket for events (address/interface/route changes) */
3150 this->socket_events = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
3151 if (this->socket_events < 0)
3152 {
3153 DBG1(DBG_KNL, "unable to create RT event socket: %s (%d)",
3154 strerror(errno), errno);
3155 destroy(this);
3156 return NULL;
3157 }
3158 addr.nl_groups = nl_group(RTNLGRP_IPV4_IFADDR) |
3159 nl_group(RTNLGRP_IPV6_IFADDR) |
3160 nl_group(RTNLGRP_LINK);
3161 if (this->process_route)
3162 {
3163 addr.nl_groups |= nl_group(RTNLGRP_IPV4_ROUTE) |
3164 nl_group(RTNLGRP_IPV6_ROUTE);
3165 }
3166 if (this->process_rules)
3167 {
3168 addr.nl_groups |= nl_group(RTNLGRP_IPV4_RULE) |
3169 nl_group(RTNLGRP_IPV6_RULE);
3170 }
3171 if (bind(this->socket_events, (struct sockaddr*)&addr, sizeof(addr)))
3172 {
3173 DBG1(DBG_KNL, "unable to bind RT event socket: %s (%d)",
3174 strerror(errno), errno);
3175 destroy(this);
3176 return NULL;
3177 }
3178
3179 lib->watcher->add(lib->watcher, this->socket_events, WATCHER_READ,
3180 (watcher_cb_t)receive_events, this);
3181 }
3182
3183 if (init_address_list(this) != SUCCESS)
3184 {
3185 DBG1(DBG_KNL, "unable to get interface list");
3186 destroy(this);
3187 return NULL;
3188 }
3189
3190 if (this->routing_table)
3191 {
3192 if (manage_rule(this, RTM_NEWRULE, AF_INET, this->routing_table,
3193 this->routing_table_prio) != SUCCESS)
3194 {
3195 DBG1(DBG_KNL, "unable to create IPv4 routing table rule");
3196 }
3197 if (manage_rule(this, RTM_NEWRULE, AF_INET6, this->routing_table,
3198 this->routing_table_prio) != SUCCESS)
3199 {
3200 DBG1(DBG_KNL, "unable to create IPv6 routing table rule");
3201 }
3202 }
3203
3204 return &this->public;
3205 }