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