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