kernel-netlink: Use RTA_SRC to specify route source in kernel-based lookups
[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 if (hdr->nlmsg_flags & NLM_F_DUMP)
1887 {
1888 netlink_add_attribute(hdr, RTA_PREFSRC, chunk, sizeof(request));
1889 }
1890 else
1891 {
1892 netlink_add_attribute(hdr, RTA_SRC, chunk, sizeof(request));
1893 }
1894 }
1895 /* we use this below to match against the routes */
1896 chunk = dest->get_address(dest);
1897 if (!match_net)
1898 {
1899 netlink_add_attribute(hdr, RTA_DST, chunk, sizeof(request));
1900 }
1901
1902 if (this->socket->send(this->socket, hdr, &out, &len) != SUCCESS)
1903 {
1904 DBG2(DBG_KNL, "getting %s to reach %H/%d failed",
1905 nexthop ? "nexthop" : "address", dest, prefix);
1906 return NULL;
1907 }
1908 routes = linked_list_create();
1909 this->lock->read_lock(this->lock);
1910
1911 for (current = out; NLMSG_OK(current, len);
1912 current = NLMSG_NEXT(current, len))
1913 {
1914 switch (current->nlmsg_type)
1915 {
1916 case NLMSG_DONE:
1917 break;
1918 case RTM_NEWROUTE:
1919 {
1920 rt_entry_t *other;
1921 uintptr_t table;
1922
1923 if (!route_usable(current))
1924 {
1925 continue;
1926 }
1927 route = parse_route(current, route);
1928
1929 table = (uintptr_t)route->table;
1930 if (this->rt_exclude->find_first(this->rt_exclude, NULL,
1931 (void**)&table) == SUCCESS)
1932 { /* route is from an excluded routing table */
1933 continue;
1934 }
1935 if (this->routing_table != 0 &&
1936 route->table == this->routing_table)
1937 { /* route is from our own ipsec routing table */
1938 continue;
1939 }
1940 if (route->oif && !is_interface_up_and_usable(this, route->oif))
1941 { /* interface is down */
1942 continue;
1943 }
1944 if (!addr_in_subnet(chunk, prefix, route->dst, route->dst_len))
1945 { /* route destination does not contain dest */
1946 continue;
1947 }
1948 if (route->pref_src.ptr)
1949 { /* verify source address, if any */
1950 host_t *src = host_create_from_chunk(msg->rtm_family,
1951 route->pref_src, 0);
1952 if (src && is_known_vip(this, src))
1953 { /* ignore routes installed by us */
1954 src->destroy(src);
1955 continue;
1956 }
1957 route->src_host = src;
1958 }
1959 /* insert route, sorted by network prefix and priority */
1960 enumerator = routes->create_enumerator(routes);
1961 while (enumerator->enumerate(enumerator, &other))
1962 {
1963 if (route->dst_len > other->dst_len)
1964 {
1965 break;
1966 }
1967 if (route->dst_len == other->dst_len &&
1968 route->priority < other->priority)
1969 {
1970 break;
1971 }
1972 }
1973 routes->insert_before(routes, enumerator, route);
1974 enumerator->destroy(enumerator);
1975 route = NULL;
1976 continue;
1977 }
1978 default:
1979 continue;
1980 }
1981 break;
1982 }
1983 if (route)
1984 {
1985 rt_entry_destroy(route);
1986 }
1987
1988 /* now we have a list of routes matching dest, sorted by net prefix.
1989 * we will look for source addresses for these routes and select the one
1990 * with the preferred source address, if possible */
1991 enumerator = routes->create_enumerator(routes);
1992 while (enumerator->enumerate(enumerator, &route))
1993 {
1994 if (route->src_host)
1995 { /* got a source address with the route, if no preferred source
1996 * is given or it matches we are done, as this is the best route */
1997 if (!candidate || candidate->ip_equals(candidate, route->src_host))
1998 {
1999 best = route;
2000 break;
2001 }
2002 else if (route->oif)
2003 { /* no match yet, maybe it is assigned to the same interface */
2004 host_t *src = get_interface_address(this, route->oif,
2005 msg->rtm_family, dest, candidate);
2006 if (src && src->ip_equals(src, candidate))
2007 {
2008 route->src_host->destroy(route->src_host);
2009 route->src_host = src;
2010 best = route;
2011 break;
2012 }
2013 DESTROY_IF(src);
2014 }
2015 /* no luck yet with the source address. if this is the best (first)
2016 * route we store it as fallback in case we don't find a route with
2017 * the preferred source */
2018 best = best ?: route;
2019 continue;
2020 }
2021 if (route->src.ptr)
2022 { /* no src, but a source selector, try to find a matching address */
2023 route->src_host = get_subnet_address(this, msg->rtm_family,
2024 route->src, route->src_len, dest,
2025 candidate);
2026 if (route->src_host)
2027 { /* we handle this address the same as the one above */
2028 if (!candidate ||
2029 candidate->ip_equals(candidate, route->src_host))
2030 {
2031 best = route;
2032 break;
2033 }
2034 best = best ?: route;
2035 continue;
2036 }
2037 }
2038 if (route->oif)
2039 { /* no src, but an interface - get address from it */
2040 route->src_host = get_interface_address(this, route->oif,
2041 msg->rtm_family, dest, candidate);
2042 if (route->src_host)
2043 { /* more of the same */
2044 if (!candidate ||
2045 candidate->ip_equals(candidate, route->src_host))
2046 {
2047 best = route;
2048 break;
2049 }
2050 best = best ?: route;
2051 continue;
2052 }
2053 }
2054 if (route->gtw.ptr)
2055 { /* no src, no iface, but a gateway - lookup src to reach gtw */
2056 host_t *gtw;
2057
2058 gtw = host_create_from_chunk(msg->rtm_family, route->gtw, 0);
2059 if (gtw && !gtw->ip_equals(gtw, dest))
2060 {
2061 route->src_host = get_route(this, gtw, -1, FALSE, candidate,
2062 iface, recursion + 1);
2063 }
2064 DESTROY_IF(gtw);
2065 if (route->src_host)
2066 { /* more of the same */
2067 if (!candidate ||
2068 candidate->ip_equals(candidate, route->src_host))
2069 {
2070 best = route;
2071 break;
2072 }
2073 best = best ?: route;
2074 }
2075 }
2076 }
2077 enumerator->destroy(enumerator);
2078
2079 if (nexthop)
2080 { /* nexthop lookup, return gateway and oif if any */
2081 if (iface)
2082 {
2083 *iface = NULL;
2084 }
2085 if (best || routes->get_first(routes, (void**)&best) == SUCCESS)
2086 {
2087 addr = host_create_from_chunk(msg->rtm_family, best->gtw, 0);
2088 if (iface && best->oif)
2089 {
2090 *iface = get_interface_name_by_index(this, best->oif);
2091 }
2092 }
2093 if (!addr && !match_net)
2094 { /* fallback to destination address */
2095 addr = dest->clone(dest);
2096 }
2097 }
2098 else
2099 {
2100 if (best)
2101 {
2102 addr = best->src_host->clone(best->src_host);
2103 }
2104 }
2105 this->lock->unlock(this->lock);
2106 routes->destroy_function(routes, (void*)rt_entry_destroy);
2107 free(out);
2108
2109 if (addr)
2110 {
2111 if (nexthop && iface && *iface)
2112 {
2113 DBG2(DBG_KNL, "using %H as nexthop and %s as dev to reach %H/%d",
2114 addr, *iface, dest, prefix);
2115 }
2116 else
2117 {
2118 DBG2(DBG_KNL, "using %H as %s to reach %H/%d", addr,
2119 nexthop ? "nexthop" : "address", dest, prefix);
2120 }
2121 }
2122 else if (!recursion)
2123 {
2124 DBG2(DBG_KNL, "no %s found to reach %H/%d",
2125 nexthop ? "nexthop" : "address", dest, prefix);
2126 }
2127 return addr;
2128 }
2129
2130 METHOD(kernel_net_t, get_source_addr, host_t*,
2131 private_kernel_netlink_net_t *this, host_t *dest, host_t *src)
2132 {
2133 return get_route(this, dest, -1, FALSE, src, NULL, 0);
2134 }
2135
2136 METHOD(kernel_net_t, get_nexthop, host_t*,
2137 private_kernel_netlink_net_t *this, host_t *dest, int prefix, host_t *src,
2138 char **iface)
2139 {
2140 return get_route(this, dest, prefix, TRUE, src, iface, 0);
2141 }
2142
2143 /** enumerator over subnets */
2144 typedef struct {
2145 enumerator_t public;
2146 private_kernel_netlink_net_t *private;
2147 /** message from the kernel */
2148 struct nlmsghdr *msg;
2149 /** current message from the kernel */
2150 struct nlmsghdr *current;
2151 /** remaining length */
2152 size_t len;
2153 /** last subnet enumerated */
2154 host_t *net;
2155 /** interface of current net */
2156 char ifname[IFNAMSIZ];
2157 } subnet_enumerator_t;
2158
2159 METHOD(enumerator_t, destroy_subnet_enumerator, void,
2160 subnet_enumerator_t *this)
2161 {
2162 DESTROY_IF(this->net);
2163 free(this->msg);
2164 free(this);
2165 }
2166
2167 METHOD(enumerator_t, enumerate_subnets, bool,
2168 subnet_enumerator_t *this, host_t **net, uint8_t *mask, char **ifname)
2169 {
2170 if (!this->current)
2171 {
2172 this->current = this->msg;
2173 }
2174 else
2175 {
2176 this->current = NLMSG_NEXT(this->current, this->len);
2177 DESTROY_IF(this->net);
2178 this->net = NULL;
2179 }
2180
2181 while (NLMSG_OK(this->current, this->len))
2182 {
2183 switch (this->current->nlmsg_type)
2184 {
2185 case NLMSG_DONE:
2186 break;
2187 case RTM_NEWROUTE:
2188 {
2189 struct rtmsg *msg;
2190 struct rtattr *rta;
2191 size_t rtasize;
2192 chunk_t dst = chunk_empty;
2193 uint32_t oif = 0;
2194
2195 msg = NLMSG_DATA(this->current);
2196
2197 if (!route_usable(this->current))
2198 {
2199 break;
2200 }
2201 else if (msg->rtm_table && (
2202 msg->rtm_table == RT_TABLE_LOCAL ||
2203 msg->rtm_table == this->private->routing_table))
2204 { /* ignore our own and the local routing tables */
2205 break;
2206 }
2207
2208 rta = RTM_RTA(msg);
2209 rtasize = RTM_PAYLOAD(this->current);
2210 while (RTA_OK(rta, rtasize))
2211 {
2212 switch (rta->rta_type)
2213 {
2214 case RTA_DST:
2215 dst = chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta));
2216 break;
2217 case RTA_OIF:
2218 if (RTA_PAYLOAD(rta) == sizeof(oif))
2219 {
2220 oif = *(uint32_t*)RTA_DATA(rta);
2221 }
2222 break;
2223 }
2224 rta = RTA_NEXT(rta, rtasize);
2225 }
2226
2227 if (dst.ptr && oif && if_indextoname(oif, this->ifname))
2228 {
2229 this->net = host_create_from_chunk(msg->rtm_family, dst, 0);
2230 *net = this->net;
2231 *mask = msg->rtm_dst_len;
2232 *ifname = this->ifname;
2233 return TRUE;
2234 }
2235 break;
2236 }
2237 default:
2238 break;
2239 }
2240 this->current = NLMSG_NEXT(this->current, this->len);
2241 }
2242 return FALSE;
2243 }
2244
2245 METHOD(kernel_net_t, create_local_subnet_enumerator, enumerator_t*,
2246 private_kernel_netlink_net_t *this)
2247 {
2248 netlink_buf_t request;
2249 struct nlmsghdr *hdr, *out;
2250 struct rtmsg *msg;
2251 size_t len;
2252 subnet_enumerator_t *enumerator;
2253
2254 memset(&request, 0, sizeof(request));
2255
2256 hdr = &request.hdr;
2257 hdr->nlmsg_flags = NLM_F_REQUEST;
2258 hdr->nlmsg_type = RTM_GETROUTE;
2259 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
2260 hdr->nlmsg_flags |= NLM_F_DUMP;
2261
2262 msg = NLMSG_DATA(hdr);
2263 msg->rtm_scope = RT_SCOPE_LINK;
2264
2265 if (this->socket->send(this->socket, hdr, &out, &len) != SUCCESS)
2266 {
2267 DBG2(DBG_KNL, "enumerating local subnets failed");
2268 return enumerator_create_empty();
2269 }
2270
2271 INIT(enumerator,
2272 .public = {
2273 .enumerate = (void*)_enumerate_subnets,
2274 .destroy = _destroy_subnet_enumerator,
2275 },
2276 .private = this,
2277 .msg = out,
2278 .len = len,
2279 );
2280 return &enumerator->public;
2281 }
2282
2283 /**
2284 * Manages the creation and deletion of ip addresses on an interface.
2285 * By setting the appropriate nlmsg_type, the ip will be set or unset.
2286 */
2287 static status_t manage_ipaddr(private_kernel_netlink_net_t *this, int nlmsg_type,
2288 int flags, int if_index, host_t *ip, int prefix)
2289 {
2290 netlink_buf_t request;
2291 struct nlmsghdr *hdr;
2292 struct ifaddrmsg *msg;
2293 chunk_t chunk;
2294
2295 memset(&request, 0, sizeof(request));
2296
2297 chunk = ip->get_address(ip);
2298
2299 hdr = &request.hdr;
2300 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
2301 hdr->nlmsg_type = nlmsg_type;
2302 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg));
2303
2304 msg = NLMSG_DATA(hdr);
2305 msg->ifa_family = ip->get_family(ip);
2306 msg->ifa_flags = 0;
2307 msg->ifa_prefixlen = prefix < 0 ? chunk.len * 8 : prefix;
2308 msg->ifa_scope = RT_SCOPE_UNIVERSE;
2309 msg->ifa_index = if_index;
2310
2311 netlink_add_attribute(hdr, IFA_LOCAL, chunk, sizeof(request));
2312
2313 if (ip->get_family(ip) == AF_INET6)
2314 {
2315 msg->ifa_flags |= IFA_F_NODAD;
2316 if (this->rta_prefsrc_for_ipv6)
2317 {
2318 /* if source routes are possible we let the virtual IP get
2319 * deprecated immediately (but mark it as valid forever) so it gets
2320 * only used if forced by our route, and not by the default IPv6
2321 * address selection */
2322 struct ifa_cacheinfo cache = {
2323 .ifa_valid = 0xFFFFFFFF,
2324 .ifa_prefered = 0,
2325 };
2326 netlink_add_attribute(hdr, IFA_CACHEINFO, chunk_from_thing(cache),
2327 sizeof(request));
2328 }
2329 }
2330 return this->socket->send_ack(this->socket, hdr);
2331 }
2332
2333 METHOD(kernel_net_t, add_ip, status_t,
2334 private_kernel_netlink_net_t *this, host_t *virtual_ip, int prefix,
2335 char *iface_name)
2336 {
2337 addr_map_entry_t *entry, lookup = {
2338 .ip = virtual_ip,
2339 };
2340 iface_entry_t *iface = NULL;
2341
2342 if (!this->install_virtual_ip)
2343 { /* disabled by config */
2344 return SUCCESS;
2345 }
2346
2347 this->lock->write_lock(this->lock);
2348 /* the virtual IP might actually be installed as regular IP, in which case
2349 * we don't track it as virtual IP */
2350 entry = this->addrs->get_match(this->addrs, &lookup,
2351 (void*)addr_map_entry_match);
2352 if (!entry)
2353 { /* otherwise it might already be installed as virtual IP */
2354 entry = this->vips->get_match(this->vips, &lookup,
2355 (void*)addr_map_entry_match);
2356 if (entry)
2357 { /* the vip we found can be in one of three states: 1) installed and
2358 * ready, 2) just added by another thread, but not yet confirmed to
2359 * be installed by the kernel, 3) just deleted, but not yet gone.
2360 * Then while we wait below, several things could happen (as we
2361 * release the lock). For instance, the interface could disappear,
2362 * or the IP is finally deleted, and it reappears on a different
2363 * interface. All these cases are handled by the call below. */
2364 while (!is_vip_installed_or_gone(this, virtual_ip, &entry))
2365 {
2366 this->condvar->wait(this->condvar, this->lock);
2367 }
2368 if (entry)
2369 {
2370 entry->addr->refcount++;
2371 }
2372 }
2373 }
2374 if (entry)
2375 {
2376 DBG2(DBG_KNL, "virtual IP %H is already installed on %s", virtual_ip,
2377 entry->iface->ifname);
2378 this->lock->unlock(this->lock);
2379 return SUCCESS;
2380 }
2381 /* try to find the target interface, either by config or via src ip */
2382 if (!this->install_virtual_ip_on ||
2383 this->ifaces->find_first(this->ifaces, (void*)iface_entry_by_name,
2384 (void**)&iface, this->install_virtual_ip_on) != SUCCESS)
2385 {
2386 if (this->ifaces->find_first(this->ifaces, (void*)iface_entry_by_name,
2387 (void**)&iface, iface_name) != SUCCESS)
2388 { /* if we don't find the requested interface we just use the first */
2389 this->ifaces->get_first(this->ifaces, (void**)&iface);
2390 }
2391 }
2392 if (iface)
2393 {
2394 addr_entry_t *addr;
2395 char *ifname;
2396 int ifi;
2397
2398 INIT(addr,
2399 .ip = virtual_ip->clone(virtual_ip),
2400 .refcount = 1,
2401 .scope = RT_SCOPE_UNIVERSE,
2402 );
2403 iface->addrs->insert_last(iface->addrs, addr);
2404 addr_map_entry_add(this->vips, addr, iface);
2405 ifi = iface->ifindex;
2406 this->lock->unlock(this->lock);
2407 if (manage_ipaddr(this, RTM_NEWADDR, NLM_F_CREATE | NLM_F_EXCL,
2408 ifi, virtual_ip, prefix) == SUCCESS)
2409 {
2410 this->lock->write_lock(this->lock);
2411 while (!is_vip_installed_or_gone(this, virtual_ip, &entry))
2412 { /* wait until address appears */
2413 this->condvar->wait(this->condvar, this->lock);
2414 }
2415 if (entry)
2416 { /* we fail if the interface got deleted in the meantime */
2417 ifname = strdup(entry->iface->ifname);
2418 this->lock->unlock(this->lock);
2419 DBG2(DBG_KNL, "virtual IP %H installed on %s",
2420 virtual_ip, ifname);
2421 /* during IKEv1 reauthentication, children get moved from
2422 * old the new SA before the virtual IP is available. This
2423 * kills the route for our virtual IP, reinstall. */
2424 queue_route_reinstall(this, ifname);
2425 return SUCCESS;
2426 }
2427 this->lock->unlock(this->lock);
2428 }
2429 DBG1(DBG_KNL, "adding virtual IP %H failed", virtual_ip);
2430 return FAILED;
2431 }
2432 this->lock->unlock(this->lock);
2433 DBG1(DBG_KNL, "no interface available, unable to install virtual IP %H",
2434 virtual_ip);
2435 return FAILED;
2436 }
2437
2438 METHOD(kernel_net_t, del_ip, status_t,
2439 private_kernel_netlink_net_t *this, host_t *virtual_ip, int prefix,
2440 bool wait)
2441 {
2442 addr_map_entry_t *entry, lookup = {
2443 .ip = virtual_ip,
2444 };
2445
2446 if (!this->install_virtual_ip)
2447 { /* disabled by config */
2448 return SUCCESS;
2449 }
2450
2451 DBG2(DBG_KNL, "deleting virtual IP %H", virtual_ip);
2452
2453 this->lock->write_lock(this->lock);
2454 entry = this->vips->get_match(this->vips, &lookup,
2455 (void*)addr_map_entry_match);
2456 if (!entry)
2457 { /* we didn't install this IP as virtual IP */
2458 entry = this->addrs->get_match(this->addrs, &lookup,
2459 (void*)addr_map_entry_match);
2460 if (entry)
2461 {
2462 DBG2(DBG_KNL, "not deleting existing IP %H on %s", virtual_ip,
2463 entry->iface->ifname);
2464 this->lock->unlock(this->lock);
2465 return SUCCESS;
2466 }
2467 DBG2(DBG_KNL, "virtual IP %H not cached, unable to delete", virtual_ip);
2468 this->lock->unlock(this->lock);
2469 return FAILED;
2470 }
2471 if (entry->addr->refcount == 1)
2472 {
2473 status_t status;
2474 int ifi;
2475
2476 /* we set this flag so that threads calling add_ip will block and wait
2477 * until the entry is gone, also so we can wait below */
2478 entry->addr->installed = FALSE;
2479 ifi = entry->iface->ifindex;
2480 this->lock->unlock(this->lock);
2481 status = manage_ipaddr(this, RTM_DELADDR, 0, ifi, virtual_ip, prefix);
2482 if (status == SUCCESS && wait)
2483 { /* wait until the address is really gone */
2484 this->lock->write_lock(this->lock);
2485 while (is_known_vip(this, virtual_ip))
2486 {
2487 this->condvar->wait(this->condvar, this->lock);
2488 }
2489 this->lock->unlock(this->lock);
2490 }
2491 return status;
2492 }
2493 else
2494 {
2495 entry->addr->refcount--;
2496 }
2497 DBG2(DBG_KNL, "virtual IP %H used by other SAs, not deleting",
2498 virtual_ip);
2499 this->lock->unlock(this->lock);
2500 return SUCCESS;
2501 }
2502
2503 /**
2504 * Manages source routes in the routing table.
2505 * By setting the appropriate nlmsg_type, the route gets added or removed.
2506 */
2507 static status_t manage_srcroute(private_kernel_netlink_net_t *this,
2508 int nlmsg_type, int flags, chunk_t dst_net,
2509 uint8_t prefixlen, host_t *gateway,
2510 host_t *src_ip, char *if_name)
2511 {
2512 netlink_buf_t request;
2513 struct nlmsghdr *hdr;
2514 struct rtmsg *msg;
2515 struct rtattr *rta;
2516 int ifindex;
2517 chunk_t chunk;
2518
2519 /* if route is 0.0.0.0/0, we can't install it, as it would
2520 * overwrite the default route. Instead, we add two routes:
2521 * 0.0.0.0/1 and 128.0.0.0/1 */
2522 if (this->routing_table == 0 && prefixlen == 0)
2523 {
2524 chunk_t half_net;
2525 uint8_t half_prefixlen;
2526 status_t status;
2527
2528 half_net = chunk_alloca(dst_net.len);
2529 memset(half_net.ptr, 0, half_net.len);
2530 half_prefixlen = 1;
2531
2532 status = manage_srcroute(this, nlmsg_type, flags, half_net, half_prefixlen,
2533 gateway, src_ip, if_name);
2534 half_net.ptr[0] |= 0x80;
2535 status = manage_srcroute(this, nlmsg_type, flags, half_net, half_prefixlen,
2536 gateway, src_ip, if_name);
2537 return status;
2538 }
2539
2540 memset(&request, 0, sizeof(request));
2541
2542 hdr = &request.hdr;
2543 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
2544 hdr->nlmsg_type = nlmsg_type;
2545 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
2546
2547 msg = NLMSG_DATA(hdr);
2548 msg->rtm_family = src_ip->get_family(src_ip);
2549 msg->rtm_dst_len = prefixlen;
2550 msg->rtm_table = this->routing_table;
2551 msg->rtm_protocol = RTPROT_STATIC;
2552 msg->rtm_type = RTN_UNICAST;
2553 msg->rtm_scope = RT_SCOPE_UNIVERSE;
2554
2555 netlink_add_attribute(hdr, RTA_DST, dst_net, sizeof(request));
2556 chunk = src_ip->get_address(src_ip);
2557 netlink_add_attribute(hdr, RTA_PREFSRC, chunk, sizeof(request));
2558 if (gateway && gateway->get_family(gateway) == src_ip->get_family(src_ip))
2559 {
2560 chunk = gateway->get_address(gateway);
2561 netlink_add_attribute(hdr, RTA_GATEWAY, chunk, sizeof(request));
2562 }
2563 ifindex = get_interface_index(this, if_name);
2564 chunk.ptr = (char*)&ifindex;
2565 chunk.len = sizeof(ifindex);
2566 netlink_add_attribute(hdr, RTA_OIF, chunk, sizeof(request));
2567
2568 if (this->mtu || this->mss)
2569 {
2570 chunk = chunk_alloca(RTA_LENGTH((sizeof(struct rtattr) +
2571 sizeof(uint32_t)) * 2));
2572 chunk.len = 0;
2573 rta = (struct rtattr*)chunk.ptr;
2574 if (this->mtu)
2575 {
2576 rta->rta_type = RTAX_MTU;
2577 rta->rta_len = RTA_LENGTH(sizeof(uint32_t));
2578 memcpy(RTA_DATA(rta), &this->mtu, sizeof(uint32_t));
2579 chunk.len = rta->rta_len;
2580 }
2581 if (this->mss)
2582 {
2583 rta = (struct rtattr*)(chunk.ptr + RTA_ALIGN(chunk.len));
2584 rta->rta_type = RTAX_ADVMSS;
2585 rta->rta_len = RTA_LENGTH(sizeof(uint32_t));
2586 memcpy(RTA_DATA(rta), &this->mss, sizeof(uint32_t));
2587 chunk.len = RTA_ALIGN(chunk.len) + rta->rta_len;
2588 }
2589 netlink_add_attribute(hdr, RTA_METRICS, chunk, sizeof(request));
2590 }
2591
2592 return this->socket->send_ack(this->socket, hdr);
2593 }
2594
2595 METHOD(kernel_net_t, add_route, status_t,
2596 private_kernel_netlink_net_t *this, chunk_t dst_net, uint8_t prefixlen,
2597 host_t *gateway, host_t *src_ip, char *if_name)
2598 {
2599 status_t status;
2600 route_entry_t *found, route = {
2601 .dst_net = dst_net,
2602 .prefixlen = prefixlen,
2603 .gateway = gateway,
2604 .src_ip = src_ip,
2605 .if_name = if_name,
2606 };
2607
2608 this->routes_lock->lock(this->routes_lock);
2609 found = this->routes->get(this->routes, &route);
2610 if (found)
2611 {
2612 this->routes_lock->unlock(this->routes_lock);
2613 return ALREADY_DONE;
2614 }
2615 status = manage_srcroute(this, RTM_NEWROUTE, NLM_F_CREATE | NLM_F_EXCL,
2616 dst_net, prefixlen, gateway, src_ip, if_name);
2617 if (status == SUCCESS)
2618 {
2619 found = route_entry_clone(&route);
2620 this->routes->put(this->routes, found, found);
2621 }
2622 this->routes_lock->unlock(this->routes_lock);
2623 return status;
2624 }
2625
2626 METHOD(kernel_net_t, del_route, status_t,
2627 private_kernel_netlink_net_t *this, chunk_t dst_net, uint8_t prefixlen,
2628 host_t *gateway, host_t *src_ip, char *if_name)
2629 {
2630 status_t status;
2631 route_entry_t *found, route = {
2632 .dst_net = dst_net,
2633 .prefixlen = prefixlen,
2634 .gateway = gateway,
2635 .src_ip = src_ip,
2636 .if_name = if_name,
2637 };
2638
2639 this->routes_lock->lock(this->routes_lock);
2640 found = this->routes->get(this->routes, &route);
2641 if (!found)
2642 {
2643 this->routes_lock->unlock(this->routes_lock);
2644 return NOT_FOUND;
2645 }
2646 this->routes->remove(this->routes, found);
2647 route_entry_destroy(found);
2648 status = manage_srcroute(this, RTM_DELROUTE, 0, dst_net, prefixlen,
2649 gateway, src_ip, if_name);
2650 this->routes_lock->unlock(this->routes_lock);
2651 return status;
2652 }
2653
2654 /**
2655 * Initialize a list of local addresses.
2656 */
2657 static status_t init_address_list(private_kernel_netlink_net_t *this)
2658 {
2659 netlink_buf_t request;
2660 struct nlmsghdr *out, *current, *in;
2661 struct rtgenmsg *msg;
2662 size_t len;
2663 enumerator_t *ifaces, *addrs;
2664 iface_entry_t *iface;
2665 addr_entry_t *addr;
2666
2667 DBG2(DBG_KNL, "known interfaces and IP addresses:");
2668
2669 memset(&request, 0, sizeof(request));
2670
2671 in = &request.hdr;
2672 in->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg));
2673 in->nlmsg_flags = NLM_F_REQUEST | NLM_F_MATCH | NLM_F_ROOT;
2674 msg = NLMSG_DATA(in);
2675 msg->rtgen_family = AF_UNSPEC;
2676
2677 /* get all links */
2678 in->nlmsg_type = RTM_GETLINK;
2679 if (this->socket->send(this->socket, in, &out, &len) != SUCCESS)
2680 {
2681 return FAILED;
2682 }
2683 current = out;
2684 while (NLMSG_OK(current, len))
2685 {
2686 switch (current->nlmsg_type)
2687 {
2688 case NLMSG_DONE:
2689 break;
2690 case RTM_NEWLINK:
2691 process_link(this, current, FALSE);
2692 /* fall through */
2693 default:
2694 current = NLMSG_NEXT(current, len);
2695 continue;
2696 }
2697 break;
2698 }
2699 free(out);
2700
2701 /* get all interface addresses */
2702 in->nlmsg_type = RTM_GETADDR;
2703 if (this->socket->send(this->socket, in, &out, &len) != SUCCESS)
2704 {
2705 return FAILED;
2706 }
2707 current = out;
2708 while (NLMSG_OK(current, len))
2709 {
2710 switch (current->nlmsg_type)
2711 {
2712 case NLMSG_DONE:
2713 break;
2714 case RTM_NEWADDR:
2715 process_addr(this, current, FALSE);
2716 /* fall through */
2717 default:
2718 current = NLMSG_NEXT(current, len);
2719 continue;
2720 }
2721 break;
2722 }
2723 free(out);
2724
2725 this->lock->read_lock(this->lock);
2726 ifaces = this->ifaces->create_enumerator(this->ifaces);
2727 while (ifaces->enumerate(ifaces, &iface))
2728 {
2729 if (iface_entry_up_and_usable(iface))
2730 {
2731 DBG2(DBG_KNL, " %s", iface->ifname);
2732 addrs = iface->addrs->create_enumerator(iface->addrs);
2733 while (addrs->enumerate(addrs, (void**)&addr))
2734 {
2735 DBG2(DBG_KNL, " %H", addr->ip);
2736 }
2737 addrs->destroy(addrs);
2738 }
2739 }
2740 ifaces->destroy(ifaces);
2741 this->lock->unlock(this->lock);
2742 return SUCCESS;
2743 }
2744
2745 /**
2746 * create or delete a rule to use our routing table
2747 */
2748 static status_t manage_rule(private_kernel_netlink_net_t *this, int nlmsg_type,
2749 int family, uint32_t table, uint32_t prio)
2750 {
2751 netlink_buf_t request;
2752 struct nlmsghdr *hdr;
2753 struct rtmsg *msg;
2754 chunk_t chunk;
2755 char *fwmark;
2756
2757 memset(&request, 0, sizeof(request));
2758 hdr = &request.hdr;
2759 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2760 hdr->nlmsg_type = nlmsg_type;
2761 if (nlmsg_type == RTM_NEWRULE)
2762 {
2763 hdr->nlmsg_flags |= NLM_F_CREATE | NLM_F_EXCL;
2764 }
2765 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
2766
2767 msg = NLMSG_DATA(hdr);
2768 msg->rtm_table = table;
2769 msg->rtm_family = family;
2770 msg->rtm_protocol = RTPROT_BOOT;
2771 msg->rtm_scope = RT_SCOPE_UNIVERSE;
2772 msg->rtm_type = RTN_UNICAST;
2773
2774 chunk = chunk_from_thing(prio);
2775 netlink_add_attribute(hdr, RTA_PRIORITY, chunk, sizeof(request));
2776
2777 fwmark = lib->settings->get_str(lib->settings,
2778 "%s.plugins.kernel-netlink.fwmark", NULL, lib->ns);
2779 if (fwmark)
2780 {
2781 #ifdef HAVE_LINUX_FIB_RULES_H
2782 mark_t mark;
2783
2784 if (fwmark[0] == '!')
2785 {
2786 msg->rtm_flags |= FIB_RULE_INVERT;
2787 fwmark++;
2788 }
2789 if (mark_from_string(fwmark, &mark))
2790 {
2791 chunk = chunk_from_thing(mark.value);
2792 netlink_add_attribute(hdr, FRA_FWMARK, chunk, sizeof(request));
2793 chunk = chunk_from_thing(mark.mask);
2794 netlink_add_attribute(hdr, FRA_FWMASK, chunk, sizeof(request));
2795 if (msg->rtm_flags & FIB_RULE_INVERT)
2796 {
2797 this->routing_mark = mark;
2798 }
2799 }
2800 #else
2801 DBG1(DBG_KNL, "setting firewall mark on routing rule is not supported");
2802 #endif
2803 }
2804 return this->socket->send_ack(this->socket, hdr);
2805 }
2806
2807 /**
2808 * check for kernel features (currently only via version number)
2809 */
2810 static void check_kernel_features(private_kernel_netlink_net_t *this)
2811 {
2812 struct utsname utsname;
2813 int a, b, c;
2814
2815 if (uname(&utsname) == 0)
2816 {
2817 switch(sscanf(utsname.release, "%d.%d.%d", &a, &b, &c))
2818 {
2819 case 3:
2820 if (a == 2)
2821 {
2822 if (b == 6 && c >= 36)
2823 {
2824 this->rta_mark = TRUE;
2825 }
2826 DBG2(DBG_KNL, "detected Linux %d.%d.%d, no support for "
2827 "RTA_PREFSRC for IPv6 routes", a, b, c);
2828 break;
2829 }
2830 /* fall-through */
2831 case 2:
2832 /* only 3.x+ uses two part version numbers */
2833 this->rta_prefsrc_for_ipv6 = TRUE;
2834 this->rta_mark = TRUE;
2835 break;
2836 default:
2837 break;
2838 }
2839 }
2840 }
2841
2842 /**
2843 * Destroy an address to iface map
2844 */
2845 static void addr_map_destroy(hashtable_t *map)
2846 {
2847 enumerator_t *enumerator;
2848 addr_map_entry_t *addr;
2849
2850 enumerator = map->create_enumerator(map);
2851 while (enumerator->enumerate(enumerator, NULL, (void**)&addr))
2852 {
2853 free(addr);
2854 }
2855 enumerator->destroy(enumerator);
2856 map->destroy(map);
2857 }
2858
2859 METHOD(kernel_net_t, destroy, void,
2860 private_kernel_netlink_net_t *this)
2861 {
2862 enumerator_t *enumerator;
2863 route_entry_t *route;
2864
2865 if (this->routing_table)
2866 {
2867 manage_rule(this, RTM_DELRULE