4abafd993413aa03ca53f838c92be666f5522a60
[strongswan.git] / src / libcharon / plugins / kernel_netlink / kernel_netlink_net.c
1 /*
2 * Copyright (C) 2008-2019 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->flags & IFA_F_DEPRECATED ||
1607 addr->scope >= RT_SCOPE_LINK)
1608 { /* skip deprecated addresses or those with an unusable scope */
1609 continue;
1610 }
1611 if (addr->ip->get_family(addr->ip) == AF_INET6)
1612 { /* handle temporary IPv6 addresses according to config */
1613 bool temporary = (addr->flags & IFA_F_TEMPORARY) == IFA_F_TEMPORARY;
1614 if (data->this->prefer_temporary_addrs != temporary)
1615 {
1616 continue;
1617 }
1618 }
1619 *out = addr->ip;
1620 return TRUE;
1621 }
1622 return FALSE;
1623 }
1624
1625 /**
1626 * enumerator constructor for interfaces
1627 */
1628 static enumerator_t *create_iface_enumerator(iface_entry_t *iface,
1629 address_enumerator_t *data)
1630 {
1631 return enumerator_create_filter(
1632 iface->addrs->create_enumerator(iface->addrs),
1633 filter_addresses, data, NULL);
1634 }
1635
1636 CALLBACK(filter_interfaces, bool,
1637 address_enumerator_t *data, enumerator_t *orig, va_list args)
1638 {
1639 iface_entry_t *iface, **out;
1640
1641 VA_ARGS_VGET(args, out);
1642
1643 while (orig->enumerate(orig, &iface))
1644 {
1645 if (!(data->which & ADDR_TYPE_IGNORED) && !iface->usable)
1646 { /* skip interfaces excluded by config */
1647 continue;
1648 }
1649 if (!(data->which & ADDR_TYPE_LOOPBACK) && (iface->flags & IFF_LOOPBACK))
1650 { /* ignore loopback devices */
1651 continue;
1652 }
1653 if (!(data->which & ADDR_TYPE_DOWN) && !(iface->flags & IFF_UP))
1654 { /* skip interfaces not up */
1655 continue;
1656 }
1657 *out = iface;
1658 return TRUE;
1659 }
1660 return FALSE;
1661 }
1662
1663 METHOD(kernel_net_t, create_address_enumerator, enumerator_t*,
1664 private_kernel_netlink_net_t *this, kernel_address_type_t which)
1665 {
1666 address_enumerator_t *data;
1667
1668 INIT(data,
1669 .this = this,
1670 .which = which,
1671 );
1672
1673 this->lock->read_lock(this->lock);
1674 return enumerator_create_nested(
1675 enumerator_create_filter(
1676 this->ifaces->create_enumerator(this->ifaces),
1677 filter_interfaces, data, NULL),
1678 (void*)create_iface_enumerator, data,
1679 address_enumerator_destroy);
1680 }
1681
1682 METHOD(kernel_net_t, get_interface_name, bool,
1683 private_kernel_netlink_net_t *this, host_t* ip, char **name)
1684 {
1685 addr_map_entry_t *entry, lookup = {
1686 .ip = ip,
1687 };
1688
1689 if (ip->is_anyaddr(ip))
1690 {
1691 return FALSE;
1692 }
1693 this->lock->read_lock(this->lock);
1694 /* first try to find it on an up and usable interface */
1695 entry = this->addrs->get_match(this->addrs, &lookup,
1696 (void*)addr_map_entry_match_up_and_usable);
1697 if (entry)
1698 {
1699 if (name)
1700 {
1701 *name = strdup(entry->iface->ifname);
1702 DBG2(DBG_KNL, "%H is on interface %s", ip, *name);
1703 }
1704 this->lock->unlock(this->lock);
1705 return TRUE;
1706 }
1707 /* in a second step, consider virtual IPs installed by us */
1708 entry = this->vips->get_match(this->vips, &lookup,
1709 (void*)addr_map_entry_match_up_and_usable);
1710 if (entry)
1711 {
1712 if (name)
1713 {
1714 *name = strdup(entry->iface->ifname);
1715 DBG2(DBG_KNL, "virtual IP %H is on interface %s", ip, *name);
1716 }
1717 this->lock->unlock(this->lock);
1718 return TRUE;
1719 }
1720 /* maybe it is installed on an ignored interface */
1721 entry = this->addrs->get_match(this->addrs, &lookup,
1722 (void*)addr_map_entry_match_up);
1723 if (!entry)
1724 {
1725 DBG2(DBG_KNL, "%H is not a local address or the interface is down", ip);
1726 }
1727 this->lock->unlock(this->lock);
1728 return FALSE;
1729 }
1730
1731 /**
1732 * get the index of an interface by name
1733 */
1734 static int get_interface_index(private_kernel_netlink_net_t *this, char* name)
1735 {
1736 iface_entry_t *iface;
1737 int ifindex = 0;
1738
1739 DBG2(DBG_KNL, "getting iface index for %s", name);
1740
1741 this->lock->read_lock(this->lock);
1742 if (this->ifaces->find_first(this->ifaces, iface_entry_by_name,
1743 (void**)&iface, name))
1744 {
1745 ifindex = iface->ifindex;
1746 }
1747 this->lock->unlock(this->lock);
1748
1749 if (ifindex == 0)
1750 {
1751 DBG1(DBG_KNL, "unable to get interface index for %s", name);
1752 }
1753 return ifindex;
1754 }
1755
1756 /**
1757 * get the name of an interface by index (allocated)
1758 */
1759 static char *get_interface_name_by_index(private_kernel_netlink_net_t *this,
1760 int index)
1761 {
1762 iface_entry_t *iface;
1763 char *name = NULL;
1764
1765 DBG2(DBG_KNL, "getting iface name for index %d", index);
1766
1767 this->lock->read_lock(this->lock);
1768 if (this->ifaces->find_first(this->ifaces, iface_entry_by_index,
1769 (void**)&iface, index))
1770 {
1771 name = strdup(iface->ifname);
1772 }
1773 this->lock->unlock(this->lock);
1774
1775 if (!name)
1776 {
1777 DBG1(DBG_KNL, "unable to get interface name for %d", index);
1778 }
1779 return name;
1780 }
1781
1782 /**
1783 * Store information about a route retrieved via RTNETLINK
1784 */
1785 typedef struct {
1786 chunk_t gtw;
1787 chunk_t pref_src;
1788 chunk_t dst;
1789 chunk_t src;
1790 host_t *src_host;
1791 uint8_t dst_len;
1792 uint8_t src_len;
1793 uint32_t table;
1794 uint32_t oif;
1795 uint32_t priority;
1796 } rt_entry_t;
1797
1798 /**
1799 * Free a route entry
1800 */
1801 static void rt_entry_destroy(rt_entry_t *this)
1802 {
1803 DESTROY_IF(this->src_host);
1804 free(this);
1805 }
1806
1807 /**
1808 * Check if the route received with RTM_NEWROUTE is usable based on its type.
1809 */
1810 static bool route_usable(struct nlmsghdr *hdr, bool allow_local)
1811 {
1812 struct rtmsg *msg;
1813
1814 msg = NLMSG_DATA(hdr);
1815 switch (msg->rtm_type)
1816 {
1817 case RTN_BLACKHOLE:
1818 case RTN_UNREACHABLE:
1819 case RTN_PROHIBIT:
1820 case RTN_THROW:
1821 return FALSE;
1822 case RTN_LOCAL:
1823 return allow_local;
1824 default:
1825 return TRUE;
1826 }
1827 }
1828
1829 /**
1830 * Parse route received with RTM_NEWROUTE. The given rt_entry_t object will be
1831 * reused if not NULL.
1832 *
1833 * Returned chunks point to internal data of the Netlink message.
1834 */
1835 static rt_entry_t *parse_route(struct nlmsghdr *hdr, rt_entry_t *route)
1836 {
1837 struct rtattr *rta;
1838 struct rtmsg *msg;
1839 size_t rtasize;
1840
1841 msg = NLMSG_DATA(hdr);
1842 rta = RTM_RTA(msg);
1843 rtasize = RTM_PAYLOAD(hdr);
1844
1845 if (route)
1846 {
1847 *route = (rt_entry_t){
1848 .dst_len = msg->rtm_dst_len,
1849 .src_len = msg->rtm_src_len,
1850 .table = msg->rtm_table,
1851 };
1852 }
1853 else
1854 {
1855 INIT(route,
1856 .dst_len = msg->rtm_dst_len,
1857 .src_len = msg->rtm_src_len,
1858 .table = msg->rtm_table,
1859 );
1860 }
1861
1862 while (RTA_OK(rta, rtasize))
1863 {
1864 switch (rta->rta_type)
1865 {
1866 case RTA_PREFSRC:
1867 route->pref_src = chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta));
1868 break;
1869 case RTA_GATEWAY:
1870 route->gtw = chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta));
1871 break;
1872 case RTA_DST:
1873 route->dst = chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta));
1874 break;
1875 case RTA_SRC:
1876 route->src = chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta));
1877 break;
1878 case RTA_OIF:
1879 if (RTA_PAYLOAD(rta) == sizeof(route->oif))
1880 {
1881 route->oif = *(uint32_t*)RTA_DATA(rta);
1882 }
1883 break;
1884 case RTA_PRIORITY:
1885 if (RTA_PAYLOAD(rta) == sizeof(route->priority))
1886 {
1887 route->priority = *(uint32_t*)RTA_DATA(rta);
1888 }
1889 break;
1890 #ifdef HAVE_RTA_TABLE
1891 case RTA_TABLE:
1892 if (RTA_PAYLOAD(rta) == sizeof(route->table))
1893 {
1894 route->table = *(uint32_t*)RTA_DATA(rta);
1895 }
1896 break;
1897 #endif /* HAVE_RTA_TABLE*/
1898 }
1899 rta = RTA_NEXT(rta, rtasize);
1900 }
1901 return route;
1902 }
1903
1904 /**
1905 * Get a route: If "nexthop", the nexthop is returned. source addr otherwise.
1906 */
1907 static host_t *get_route(private_kernel_netlink_net_t *this, host_t *dest,
1908 int prefix, bool nexthop, host_t *candidate,
1909 char **iface, u_int recursion)
1910 {
1911 netlink_buf_t request;
1912 struct nlmsghdr *hdr, *out, *current;
1913 struct rtmsg *msg;
1914 chunk_t chunk;
1915 size_t len;
1916 linked_list_t *routes;
1917 rt_entry_t *route = NULL, *best = NULL;
1918 enumerator_t *enumerator;
1919 host_t *addr = NULL;
1920 bool match_net;
1921 int family;
1922
1923 if (recursion > MAX_ROUTE_RECURSION)
1924 {
1925 return NULL;
1926 }
1927 chunk = dest->get_address(dest);
1928 len = chunk.len * 8;
1929 prefix = prefix < 0 ? len : min(prefix, len);
1930 match_net = prefix != len;
1931
1932 memset(&request, 0, sizeof(request));
1933
1934 family = dest->get_family(dest);
1935 hdr = &request.hdr;
1936 hdr->nlmsg_flags = NLM_F_REQUEST;
1937 hdr->nlmsg_type = RTM_GETROUTE;
1938 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
1939
1940 msg = NLMSG_DATA(hdr);
1941 msg->rtm_family = family;
1942 if (!match_net && this->rta_mark && this->routing_mark.value)
1943 {
1944 /* if our routing rule excludes packets with a certain mark we can
1945 * get the preferred route without having to dump all routes */
1946 chunk = chunk_from_thing(this->routing_mark.value);
1947 netlink_add_attribute(hdr, RTA_MARK, chunk, sizeof(request));
1948 }
1949 else if (family == AF_INET || this->rta_prefsrc_for_ipv6 ||
1950 this->routing_table || match_net)
1951 { /* kernels prior to 3.0 do not support RTA_PREFSRC for IPv6 routes.
1952 * as we want to ignore routes with virtual IPs we cannot use DUMP
1953 * if these routes are not installed in a separate table */
1954 if (this->install_routes)
1955 {
1956 hdr->nlmsg_flags |= NLM_F_DUMP;
1957 }
1958 }
1959 if (candidate)
1960 {
1961 chunk = candidate->get_address(candidate);
1962 if (hdr->nlmsg_flags & NLM_F_DUMP)
1963 {
1964 netlink_add_attribute(hdr, RTA_PREFSRC, chunk, sizeof(request));
1965 }
1966 else
1967 {
1968 netlink_add_attribute(hdr, RTA_SRC, chunk, sizeof(request));
1969 }
1970 }
1971 /* we use this below to match against the routes */
1972 chunk = dest->get_address(dest);
1973 if (!match_net)
1974 {
1975 netlink_add_attribute(hdr, RTA_DST, chunk, sizeof(request));
1976 }
1977
1978 if (this->socket->send(this->socket, hdr, &out, &len) != SUCCESS)
1979 {
1980 DBG2(DBG_KNL, "getting %s to reach %H/%d failed",
1981 nexthop ? "nexthop" : "address", dest, prefix);
1982 return NULL;
1983 }
1984 routes = linked_list_create();
1985 this->lock->read_lock(this->lock);
1986
1987 for (current = out; NLMSG_OK(current, len);
1988 current = NLMSG_NEXT(current, len))
1989 {
1990 switch (current->nlmsg_type)
1991 {
1992 case NLMSG_DONE:
1993 break;
1994 case RTM_NEWROUTE:
1995 {
1996 rt_entry_t *other;
1997 uintptr_t table;
1998
1999 if (!route_usable(current, TRUE))
2000 {
2001 continue;
2002 }
2003 route = parse_route(current, route);
2004
2005 table = (uintptr_t)route->table;
2006 if (this->rt_exclude->find_first(this->rt_exclude, NULL,
2007 (void**)&table))
2008 { /* route is from an excluded routing table */
2009 continue;
2010 }
2011 if (this->routing_table != 0 &&
2012 route->table == this->routing_table)
2013 { /* route is from our own ipsec routing table */
2014 continue;
2015 }
2016 if (route->oif && !is_interface_up_and_usable(this, route->oif))
2017 { /* interface is down */
2018 continue;
2019 }
2020 if (!addr_in_subnet(chunk, prefix, route->dst, route->dst_len))
2021 { /* route destination does not contain dest */
2022 continue;
2023 }
2024 if (route->pref_src.ptr)
2025 { /* verify source address, if any */
2026 host_t *src = host_create_from_chunk(msg->rtm_family,
2027 route->pref_src, 0);
2028 if (src && is_known_vip(this, src))
2029 { /* ignore routes installed by us */
2030 src->destroy(src);
2031 continue;
2032 }
2033 route->src_host = src;
2034 }
2035 /* insert route, sorted by network prefix and priority */
2036 enumerator = routes->create_enumerator(routes);
2037 while (enumerator->enumerate(enumerator, &other))
2038 {
2039 if (route->dst_len > other->dst_len)
2040 {
2041 break;
2042 }
2043 if (route->dst_len == other->dst_len &&
2044 route->priority < other->priority)
2045 {
2046 break;
2047 }
2048 }
2049 routes->insert_before(routes, enumerator, route);
2050 enumerator->destroy(enumerator);
2051 route = NULL;
2052 continue;
2053 }
2054 default:
2055 continue;
2056 }
2057 break;
2058 }
2059 if (route)
2060 {
2061 rt_entry_destroy(route);
2062 }
2063
2064 /* now we have a list of routes matching dest, sorted by net prefix.
2065 * we will look for source addresses for these routes and select the one
2066 * with the preferred source address, if possible */
2067 enumerator = routes->create_enumerator(routes);
2068 while (enumerator->enumerate(enumerator, &route))
2069 {
2070 if (route->src_host)
2071 { /* got a source address with the route, if no preferred source
2072 * is given or it matches we are done, as this is the best route */
2073 if (!candidate || candidate->ip_equals(candidate, route->src_host))
2074 {
2075 best = route;
2076 break;
2077 }
2078 else if (route->oif)
2079 { /* no match yet, maybe it is assigned to the same interface */
2080 host_t *src = get_interface_address(this, route->oif,
2081 msg->rtm_family, dest, candidate);
2082 if (src && src->ip_equals(src, candidate))
2083 {
2084 route->src_host->destroy(route->src_host);
2085 route->src_host = src;
2086 best = route;
2087 break;
2088 }
2089 DESTROY_IF(src);
2090 }
2091 /* no luck yet with the source address. if this is the best (first)
2092 * route we store it as fallback in case we don't find a route with
2093 * the preferred source */
2094 best = best ?: route;
2095 continue;
2096 }
2097 if (route->src.ptr)
2098 { /* no src, but a source selector, try to find a matching address */
2099 route->src_host = get_subnet_address(this, msg->rtm_family,
2100 route->src, route->src_len, dest,
2101 candidate);
2102 if (route->src_host)
2103 { /* we handle this address the same as the one above */
2104 if (!candidate ||
2105 candidate->ip_equals(candidate, route->src_host))
2106 {
2107 best = route;
2108 break;
2109 }
2110 best = best ?: route;
2111 continue;
2112 }
2113 }
2114 if (route->oif)
2115 { /* no src, but an interface - get address from it */
2116 route->src_host = get_interface_address(this, route->oif,
2117 msg->rtm_family, dest, candidate);
2118 if (route->src_host)
2119 { /* more of the same */
2120 if (!candidate ||
2121 candidate->ip_equals(candidate, route->src_host))
2122 {
2123 best = route;
2124 break;
2125 }
2126 best = best ?: route;
2127 continue;
2128 }
2129 }
2130 if (route->gtw.ptr)
2131 { /* no src, no iface, but a gateway - lookup src to reach gtw */
2132 host_t *gtw;
2133
2134 gtw = host_create_from_chunk(msg->rtm_family, route->gtw, 0);
2135 if (gtw && !gtw->ip_equals(gtw, dest))
2136 {
2137 route->src_host = get_route(this, gtw, -1, FALSE, candidate,
2138 iface, recursion + 1);
2139 }
2140 DESTROY_IF(gtw);
2141 if (route->src_host)
2142 { /* more of the same */
2143 if (!candidate ||
2144 candidate->ip_equals(candidate, route->src_host))
2145 {
2146 best = route;
2147 break;
2148 }
2149 best = best ?: route;
2150 }
2151 }
2152 }
2153 enumerator->destroy(enumerator);
2154
2155 if (nexthop)
2156 { /* nexthop lookup, return gateway and oif if any */
2157 if (iface)
2158 {
2159 *iface = NULL;
2160 }
2161 if (best || routes->get_first(routes, (void**)&best) == SUCCESS)
2162 {
2163 addr = host_create_from_chunk(msg->rtm_family, best->gtw, 0);
2164 if (iface && best->oif)
2165 {
2166 *iface = get_interface_name_by_index(this, best->oif);
2167 }
2168 }
2169 if (!addr && !match_net)
2170 { /* fallback to destination address */
2171 addr = dest->clone(dest);
2172 }
2173 }
2174 else
2175 {
2176 if (best)
2177 {
2178 addr = best->src_host->clone(best->src_host);
2179 }
2180 }
2181 this->lock->unlock(this->lock);
2182 routes->destroy_function(routes, (void*)rt_entry_destroy);
2183 free(out);
2184
2185 if (addr)
2186 {
2187 if (nexthop && iface && *iface)
2188 {
2189 DBG2(DBG_KNL, "using %H as nexthop and %s as dev to reach %H/%d",
2190 addr, *iface, dest, prefix);
2191 }
2192 else
2193 {
2194 DBG2(DBG_KNL, "using %H as %s to reach %H/%d", addr,
2195 nexthop ? "nexthop" : "address", dest, prefix);
2196 }
2197 }
2198 else if (!recursion)
2199 {
2200 DBG2(DBG_KNL, "no %s found to reach %H/%d",
2201 nexthop ? "nexthop" : "address", dest, prefix);
2202 }
2203 return addr;
2204 }
2205
2206 METHOD(kernel_net_t, get_source_addr, host_t*,
2207 private_kernel_netlink_net_t *this, host_t *dest, host_t *src)
2208 {
2209 return get_route(this, dest, -1, FALSE, src, NULL, 0);
2210 }
2211
2212 METHOD(kernel_net_t, get_nexthop, host_t*,
2213 private_kernel_netlink_net_t *this, host_t *dest, int prefix, host_t *src,
2214 char **iface)
2215 {
2216 return get_route(this, dest, prefix, TRUE, src, iface, 0);
2217 }
2218
2219 /** enumerator over subnets */
2220 typedef struct {
2221 enumerator_t public;
2222 private_kernel_netlink_net_t *private;
2223 /** message from the kernel */
2224 struct nlmsghdr *msg;
2225 /** current message from the kernel */
2226 struct nlmsghdr *current;
2227 /** remaining length */
2228 size_t len;
2229 /** last subnet enumerated */
2230 host_t *net;
2231 /** interface of current net */
2232 char ifname[IFNAMSIZ];
2233 } subnet_enumerator_t;
2234
2235 METHOD(enumerator_t, destroy_subnet_enumerator, void,
2236 subnet_enumerator_t *this)
2237 {
2238 DESTROY_IF(this->net);
2239 free(this->msg);
2240 free(this);
2241 }
2242
2243 METHOD(enumerator_t, enumerate_subnets, bool,
2244 subnet_enumerator_t *this, va_list args)
2245 {
2246 host_t **net;
2247 uint8_t *mask;
2248 char **ifname;
2249
2250 VA_ARGS_VGET(args, net, mask, ifname);
2251
2252 if (!this->current)
2253 {
2254 this->current = this->msg;
2255 }
2256 else
2257 {
2258 this->current = NLMSG_NEXT(this->current, this->len);
2259 DESTROY_IF(this->net);
2260 this->net = NULL;
2261 }
2262
2263 while (NLMSG_OK(this->current, this->len))
2264 {
2265 switch (this->current->nlmsg_type)
2266 {
2267 case NLMSG_DONE:
2268 break;
2269 case RTM_NEWROUTE:
2270 {
2271 rt_entry_t route;
2272
2273 if (!route_usable(this->current, FALSE))
2274 {
2275 break;
2276 }
2277 parse_route(this->current, &route);
2278
2279 if (route.table && (
2280 route.table == RT_TABLE_LOCAL ||
2281 route.table == this->private->routing_table))
2282 { /* ignore our own and the local routing tables */
2283 break;
2284 }
2285 else if (route.gtw.ptr)
2286 { /* ignore routes via gateway/next hop */
2287 break;
2288 }
2289
2290 if (route.dst.ptr && route.oif &&
2291 if_indextoname(route.oif, this->ifname))
2292 {
2293 this->net = host_create_from_chunk(AF_UNSPEC, route.dst, 0);
2294 *net = this->net;
2295 *mask = route.dst_len;
2296 *ifname = this->ifname;
2297 return TRUE;
2298 }
2299 break;
2300 }
2301 default:
2302 break;
2303 }
2304 this->current = NLMSG_NEXT(this->current, this->len);
2305 }
2306 return FALSE;
2307 }
2308
2309 METHOD(kernel_net_t, create_local_subnet_enumerator, enumerator_t*,
2310 private_kernel_netlink_net_t *this)
2311 {
2312 netlink_buf_t request;
2313 struct nlmsghdr *hdr, *out;
2314 struct rtmsg *msg;
2315 size_t len;
2316 subnet_enumerator_t *enumerator;
2317
2318 memset(&request, 0, sizeof(request));
2319
2320 hdr = &request.hdr;
2321 hdr->nlmsg_flags = NLM_F_REQUEST;
2322 hdr->nlmsg_type = RTM_GETROUTE;
2323 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
2324 hdr->nlmsg_flags |= NLM_F_DUMP;
2325
2326 msg = NLMSG_DATA(hdr);
2327 msg->rtm_scope = RT_SCOPE_LINK;
2328
2329 if (this->socket->send(this->socket, hdr, &out, &len) != SUCCESS)
2330 {
2331 DBG2(DBG_KNL, "enumerating local subnets failed");
2332 return enumerator_create_empty();
2333 }
2334
2335 INIT(enumerator,
2336 .public = {
2337 .enumerate = enumerator_enumerate_default,
2338 .venumerate = _enumerate_subnets,
2339 .destroy = _destroy_subnet_enumerator,
2340 },
2341 .private = this,
2342 .msg = out,
2343 .len = len,
2344 );
2345 return &enumerator->public;
2346 }
2347
2348 /**
2349 * Manages the creation and deletion of IPv6 address labels for virtual IPs.
2350 * By setting the appropriate nlmsg_type the label is either added or removed.
2351 */
2352 static status_t manage_addrlabel(private_kernel_netlink_net_t *this,
2353 int nlmsg_type, host_t *ip)
2354 {
2355 netlink_buf_t request;
2356 struct nlmsghdr *hdr;
2357 struct ifaddrlblmsg *msg;
2358 chunk_t chunk;
2359 uint32_t label;
2360
2361 memset(&request, 0, sizeof(request));
2362
2363 chunk = ip->get_address(ip);
2364
2365 hdr = &request.hdr;
2366 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2367 if (nlmsg_type == RTM_NEWADDRLABEL)
2368 {
2369 hdr->nlmsg_flags |= NLM_F_CREATE | NLM_F_EXCL;
2370 }
2371 hdr->nlmsg_type = nlmsg_type;
2372 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrlblmsg));
2373
2374 msg = NLMSG_DATA(hdr);
2375 msg->ifal_family = ip->get_family(ip);
2376 msg->ifal_prefixlen = chunk.len * 8;
2377
2378 netlink_add_attribute(hdr, IFAL_ADDRESS, chunk, sizeof(request));
2379 /* doesn't really matter as default labels are < 20 but this makes it kinda
2380 * recognizable */
2381 label = 220;
2382 netlink_add_attribute(hdr, IFAL_LABEL, chunk_from_thing(label),
2383 sizeof(request));
2384
2385 return this->socket->send_ack(this->socket, hdr);
2386 }
2387
2388 /**
2389 * Manages the creation and deletion of ip addresses on an interface.
2390 * By setting the appropriate nlmsg_type, the ip will be set or unset.
2391 */
2392 static status_t manage_ipaddr(private_kernel_netlink_net_t *this, int nlmsg_type,
2393 int flags, int if_index, host_t *ip, int prefix)
2394 {
2395 netlink_buf_t request;
2396 struct nlmsghdr *hdr;
2397 struct ifaddrmsg *msg;
2398 chunk_t chunk;
2399
2400 memset(&request, 0, sizeof(request));
2401
2402 chunk = ip->get_address(ip);
2403
2404 hdr = &request.hdr;
2405 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
2406 hdr->nlmsg_type = nlmsg_type;
2407 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg));
2408
2409 msg = NLMSG_DATA(hdr);
2410 msg->ifa_family = ip->get_family(ip);
2411 msg->ifa_flags = 0;
2412 msg->ifa_prefixlen = prefix < 0 ? chunk.len * 8 : prefix;
2413 msg->ifa_scope = RT_SCOPE_UNIVERSE;
2414 msg->ifa_index = if_index;
2415
2416 netlink_add_attribute(hdr, IFA_LOCAL, chunk, sizeof(request));
2417
2418 if (ip->get_family(ip) == AF_INET6)
2419 {
2420 #ifdef IFA_F_NODAD
2421 msg->ifa_flags |= IFA_F_NODAD;
2422 #endif
2423 if (this->rta_prefsrc_for_ipv6)
2424 {
2425 /* if source routes are possible we set a label for this virtual IP
2426 * so it gets only used if forced by our route, and not by the
2427 * default IPv6 address selection */
2428 int labelop = nlmsg_type == RTM_NEWADDR ? RTM_NEWADDRLABEL
2429 : RTM_DELADDRLABEL;
2430 if (manage_addrlabel(this, labelop, ip) != SUCCESS)
2431 {
2432 /* if we can't use address labels we let the virtual IP get
2433 * deprecated immediately (but mark it as valid forever), which
2434 * should also avoid that it gets used by the default address
2435 * selection */
2436 struct ifa_cacheinfo cache = {
2437 .ifa_valid = 0xFFFFFFFF,
2438 .ifa_prefered = 0,
2439 };
2440 netlink_add_attribute(hdr, IFA_CACHEINFO,
2441 chunk_from_thing(cache), sizeof(request));
2442 }
2443 }
2444 }
2445 return this->socket->send_ack(this->socket, hdr);
2446 }
2447
2448 METHOD(kernel_net_t, add_ip, status_t,
2449 private_kernel_netlink_net_t *this, host_t *virtual_ip, int prefix,
2450 char *iface_name)
2451 {
2452 addr_map_entry_t *entry, lookup = {
2453 .ip = virtual_ip,
2454 };
2455 iface_entry_t *iface = NULL;
2456
2457 if (!this->install_virtual_ip)
2458 { /* disabled by config */
2459 return SUCCESS;
2460 }
2461
2462 this->lock->write_lock(this->lock);
2463 /* the virtual IP might actually be installed as regular IP, in which case
2464 * we don't track it as virtual IP */
2465 entry = this->addrs->get_match(this->addrs, &lookup,
2466 (void*)addr_map_entry_match);
2467 if (!entry)
2468 { /* otherwise it might already be installed as virtual IP */
2469 entry = this->vips->get_match(this->vips, &lookup,
2470 (void*)addr_map_entry_match);
2471 if (entry)
2472 { /* the vip we found can be in one of three states: 1) installed and
2473 * ready, 2) just added by another thread, but not yet confirmed to
2474 * be installed by the kernel, 3) just deleted, but not yet gone.
2475 * Then while we wait below, several things could happen (as we
2476 * release the lock). For instance, the interface could disappear,
2477 * or the IP is finally deleted, and it reappears on a different
2478 * interface. All these cases are handled by the call below. */
2479 while (!is_vip_installed_or_gone(this, virtual_ip, &entry))
2480 {
2481 this->condvar->wait(this->condvar, this->lock);
2482 }
2483 if (entry)
2484 {
2485 entry->addr->refcount++;
2486 }
2487 }
2488 }
2489 if (entry)
2490 {
2491 DBG2(DBG_KNL, "virtual IP %H is already installed on %s", virtual_ip,
2492 entry->iface->ifname);
2493 this->lock->unlock(this->lock);
2494 return SUCCESS;
2495 }
2496 /* try to find the target interface, either by config or via src ip */
2497 if (!this->install_virtual_ip_on ||
2498 !this->ifaces->find_first(this->ifaces, iface_entry_by_name,
2499 (void**)&iface, this->install_virtual_ip_on))
2500 {
2501 if (!this->ifaces->find_first(this->ifaces, iface_entry_by_name,
2502 (void**)&iface, iface_name))
2503 { /* if we don't find the requested interface we just use the first */
2504 this->ifaces->get_first(this->ifaces, (void**)&iface);
2505 }
2506 }
2507 if (iface)
2508 {
2509 addr_entry_t *addr;
2510 char *ifname;
2511 int ifi;
2512
2513 INIT(addr,
2514 .ip = virtual_ip->clone(virtual_ip),
2515 .refcount = 1,
2516 .scope = RT_SCOPE_UNIVERSE,
2517 );
2518 iface->addrs->insert_last(iface->addrs, addr);
2519 addr_map_entry_add(this->vips, addr, iface);
2520 ifi = iface->ifindex;
2521 this->lock->unlock(this->lock);
2522 if (manage_ipaddr(this, RTM_NEWADDR, NLM_F_CREATE | NLM_F_EXCL,
2523 ifi, virtual_ip, prefix) == SUCCESS)
2524 {
2525 this->lock->write_lock(this->lock);
2526 while (!is_vip_installed_or_gone(this, virtual_ip, &entry))
2527 { /* wait until address appears */
2528 this->condvar->wait(this->condvar, this->lock);
2529 }
2530 if (entry)
2531 { /* we fail if the interface got deleted in the meantime */
2532 ifname = strdup(entry->iface->ifname);
2533 this->lock->unlock(this->lock);
2534 DBG2(DBG_KNL, "virtual IP %H installed on %s",
2535 virtual_ip, ifname);
2536 /* during IKEv1 reauthentication, children get moved from
2537 * old the new SA before the virtual IP is available. This
2538 * kills the route for our virtual IP, reinstall. */
2539 queue_route_reinstall(this, ifname);
2540 return SUCCESS;
2541 }
2542 this->lock->unlock(this->lock);
2543 }
2544 DBG1(DBG_KNL, "adding virtual IP %H failed", virtual_ip);
2545 return FAILED;
2546 }
2547 this->lock->unlock(this->lock);
2548 DBG1(DBG_KNL, "no interface available, unable to install virtual IP %H",
2549 virtual_ip);
2550 return FAILED;
2551 }
2552
2553 METHOD(kernel_net_t, del_ip, status_t,
2554 private_kernel_netlink_net_t *this, host_t *virtual_ip, int prefix,
2555 bool wait)
2556 {
2557 addr_map_entry_t *entry, lookup = {
2558 .ip = virtual_ip,
2559 };
2560
2561 if (!this->install_virtual_ip)
2562 { /* disabled by config */
2563 return SUCCESS;
2564 }
2565
2566 DBG2(DBG_KNL, "deleting virtual IP %H", virtual_ip);
2567
2568 this->lock->write_lock(this->lock);
2569 entry = this->vips->get_match(this->vips, &lookup,
2570 (void*)addr_map_entry_match);
2571 if (!entry)
2572 { /* we didn't install this IP as virtual IP */
2573 entry = this->addrs->get_match(this->addrs, &lookup,
2574 (void*)addr_map_entry_match);
2575 if (entry)
2576 {
2577 DBG2(DBG_KNL, "not deleting existing IP %H on %s", virtual_ip,
2578 entry->iface->ifname);
2579 this->lock->unlock(this->lock);
2580 return SUCCESS;
2581 }
2582 DBG2(DBG_KNL, "virtual IP %H not cached, unable to delete", virtual_ip);
2583 this->lock->unlock(this->lock);
2584 return FAILED;
2585 }
2586 if (entry->addr->refcount == 1)
2587 {
2588 status_t status;
2589 int ifi;
2590
2591 /* we set this flag so that threads calling add_ip will block and wait
2592 * until the entry is gone, also so we can wait below */
2593 entry->addr->installed = FALSE;
2594 ifi = entry->iface->ifindex;
2595 this->lock->unlock(this->lock);
2596 status = manage_ipaddr(this, RTM_DELADDR, 0, ifi, virtual_ip, prefix);
2597 if (status == SUCCESS && wait)
2598 { /* wait until the address is really gone */
2599 this->lock->write_lock(this->lock);
2600 while (is_known_vip(this, virtual_ip))
2601 {
2602 this->condvar->wait(this->condvar, this->lock);
2603 }
2604 this->lock->unlock(this->lock);
2605 }
2606 return status;
2607 }
2608 else
2609 {
2610 entry->addr->refcount--;
2611 }
2612 DBG2(DBG_KNL, "virtual IP %H used by other SAs, not deleting",
2613 virtual_ip);
2614 this->lock->unlock(this->lock);
2615 return SUCCESS;
2616 }
2617
2618 /**
2619 * Manages source routes in the routing table.
2620 * By setting the appropriate nlmsg_type, the route gets added or removed.
2621 */
2622 static status_t manage_srcroute(private_kernel_netlink_net_t *this,
2623 int nlmsg_type, int flags, chunk_t dst_net,
2624 uint8_t prefixlen, host_t *gateway,
2625 host_t *src_ip, char *if_name)
2626 {
2627 netlink_buf_t request;
2628 struct nlmsghdr *hdr;
2629 struct rtmsg *msg;
2630 struct rtattr *rta;
2631 int ifindex;
2632 chunk_t chunk;
2633
2634 /* if route is 0.0.0.0/0, we can't install it, as it would
2635 * overwrite the default route. Instead, we add two routes:
2636 * 0.0.0.0/1 and 128.0.0.0/1 */
2637 if (this->routing_table == 0 && prefixlen == 0)
2638 {
2639 chunk_t half_net;
2640 uint8_t half_prefixlen;
2641 status_t status;
2642
2643 half_net = chunk_alloca(dst_net.len);
2644 memset(half_net.ptr, 0, half_net.len);
2645 half_prefixlen = 1;
2646
2647 status = manage_srcroute(this, nlmsg_type, flags, half_net,
2648 half_prefixlen, gateway, src_ip, if_name);
2649 half_net.ptr[0] |= 0x80;
2650 status |= manage_srcroute(this, nlmsg_type, flags, half_net,
2651 half_prefixlen, gateway, src_ip, if_name);
2652 return status;
2653 }
2654
2655 memset(&request, 0, sizeof(request));
2656
2657 hdr = &request.hdr;
2658 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
2659 hdr->nlmsg_type = nlmsg_type;
2660 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
2661
2662 msg = NLMSG_DATA(hdr);
2663 msg->rtm_family = src_ip->get_family(src_ip);
2664 msg->rtm_dst_len = prefixlen;
2665 msg->rtm_table = this->routing_table;
2666 msg->rtm_protocol = RTPROT_STATIC;
2667 msg->rtm_type = RTN_UNICAST;
2668 msg->rtm_scope = RT_SCOPE_UNIVERSE;
2669
2670 netlink_add_attribute(hdr, RTA_DST, dst_net, sizeof(request));
2671 chunk = src_ip->get_address(src_ip);
2672 netlink_add_attribute(hdr, RTA_PREFSRC, chunk, sizeof(request));
2673 if (gateway && gateway->get_family(gateway) == src_ip->get_family(src_ip))
2674 {
2675 chunk = gateway->get_address(gateway);
2676 netlink_add_attribute(hdr, RTA_GATEWAY, chunk, sizeof(request));
2677 }
2678 ifindex = get_interface_index(this, if_name);
2679 chunk.ptr = (char*)&ifindex;
2680 chunk.len = sizeof(ifindex);
2681 netlink_add_attribute(hdr, RTA_OIF, chunk, sizeof(request));
2682
2683 if (this->mtu || this->mss)
2684 {
2685 chunk = chunk_alloca(RTA_LENGTH((sizeof(struct rtattr) +
2686 sizeof(uint32_t)) * 2));
2687 chunk.len = 0;
2688 rta = (struct rtattr*)chunk.ptr;
2689 if (this->mtu)
2690 {
2691 rta->rta_type = RTAX_MTU;
2692 rta->rta_len = RTA_LENGTH(sizeof(uint32_t));
2693 memcpy(RTA_DATA(rta), &this->mtu, sizeof(uint32_t));
2694 chunk.len = rta->rta_len;
2695 }
2696 if (this->mss)
2697 {
2698 rta = (struct rtattr*)(chunk.ptr + RTA_ALIGN(chunk.len));
2699 rta->rta_type = RTAX_ADVMSS;
2700 rta->rta_len = RTA_LENGTH(sizeof(uint32_t));
2701 memcpy(RTA_DATA(rta), &this->mss, sizeof(uint32_t));
2702 chunk.len = RTA_ALIGN(chunk.len) + rta->rta_len;
2703 }
2704 netlink_add_attribute(hdr, RTA_METRICS, chunk, sizeof(request));
2705 }
2706
2707 return this->socket->send_ack(this->socket, hdr);
2708 }
2709
2710 /**
2711 * Helper struct used to check routes
2712 */
2713 typedef struct {
2714 /** the entry we look for */
2715 route_entry_t route;
2716 /** kernel interface */
2717 private_kernel_netlink_net_t *this;
2718 } route_entry_lookup_t;
2719
2720 /**
2721 * Check if a matching route entry has a VIP associated
2722 */
2723 static bool route_with_vip(route_entry_lookup_t *a, route_entry_t *b)
2724 {
2725 if (chunk_equals(a->route.dst_net, b->dst_net) &&
2726 a->route.prefixlen == b->prefixlen &&
2727 is_known_vip(a->this, b->src_ip))
2728 {
2729 return TRUE;
2730 }
2731 return FALSE;
2732 }
2733
2734 /**
2735 * Check if there is any route entry with a matching destination
2736 */
2737 static bool route_with_dst(route_entry_lookup_t *a, route_entry_t *b)
2738 {
2739 if (chunk_equals(a->route.dst_net, b->dst_net) &&
2740 a->route.prefixlen == b->prefixlen)
2741 {
2742 return TRUE;
2743 }
2744 return FALSE;
2745 }
2746
2747 METHOD(kernel_net_t, add_route, status_t,
2748 private_kernel_netlink_net_t *this, chunk_t dst_net, uint8_t prefixlen,
2749 host_t *gateway, host_t *src_ip, char *if_name)
2750 {
2751 status_t status;
2752 route_entry_t *found;
2753 route_entry_lookup_t lookup = {
2754 .route = {
2755 .dst_net = dst_net,
2756 .prefixlen = prefixlen,
2757 .gateway = gateway,
2758 .src_ip = src_ip,
2759 .if_name = if_name,
2760 },
2761 .this = this,
2762 };
2763
2764 this->routes_lock->lock(this->routes_lock);
2765 found = this->routes->get(this->routes, &lookup.route);
2766 if (found)
2767 {
2768 this->routes_lock->unlock(this->routes_lock);
2769 return ALREADY_DONE;
2770 }
2771
2772 /* don't replace the route if we already have one with a VIP installed,
2773 * but keep track of it in case that other route is uninstalled */
2774 this->lock->read_lock(this->lock);
2775 if (!is_known_vip(this, src_ip))
2776 {
2777 found = this->routes->get_match(this->routes, &lookup,
2778 (void*)route_with_vip);
2779 }
2780 this->lock->unlock(this->lock);
2781 if (found)
2782 {
2783 status = SUCCESS;
2784 }
2785 else
2786 {
2787 status = manage_srcroute(this, RTM_NEWROUTE, NLM_F_CREATE|NLM_F_REPLACE,
2788 dst_net, prefixlen, gateway, src_ip, if_name);
2789 }
2790 if (status == SUCCESS)
2791 {
2792 found = route_entry_clone(&lookup.route);
2793 this->routes->put(this->routes, found, found);
2794 }
2795 this->routes_lock->unlock(this->routes_lock);
2796 return status;
2797 }
2798
2799 METHOD(kernel_net_t, del_route, status_t,
2800 private_kernel_netlink_net_t *this, chunk_t dst_net, uint8_t prefixlen,
2801 host_t *gateway, host_t *src_ip, char *if_name)
2802 {
2803 status_t status;
2804 route_entry_t *found;
2805 route_entry_lookup_t lookup = {
2806 .route = {
2807 .dst_net = dst_net,
2808 .prefixlen = prefixlen,
2809 .gateway = gateway,
2810 .src_ip = src_ip,
2811 .if_name = if_name,
2812 },
2813 .this = this,
2814 };
2815
2816 this->routes_lock->lock(this->routes_lock);
2817 found = this->routes->remove(this->routes, &lookup.route);
2818 if (!found)
2819 {
2820 this->routes_lock->unlock(this->routes_lock);
2821 return NOT_FOUND;
2822 }
2823 route_entry_destroy(found);
2824
2825 /* check if there are any other routes for the same destination and if
2826 * so update the route, otherwise uninstall it */
2827 this->lock->read_lock(this->lock);
2828 found = this->routes->get_match(this->routes, &lookup,
2829 (void*)route_with_vip);
2830 this->lock->unlock(this->lock);
2831 if (!found)
2832 {
2833 found = this->routes->get_match(this->routes, &lookup,
2834 (void*)route_with_dst);
2835 }
2836 if (found)
2837 {
2838 status = manage_srcroute(this, RTM_NEWROUTE, NLM_F_CREATE|NLM_F_REPLACE,
2839 found->dst_net, found->prefixlen, found->gateway,
2840 found->src_ip, found->if_name);
2841 }
2842 else
2843 {
2844 status = manage_srcroute(this, RTM_DELROUTE, 0, dst_net, prefixlen,
2845 gateway, src_ip, if_name);
2846 }
2847 this->routes_lock->unlock(this->routes_lock);
2848 return status;
2849 }
2850
2851 /**
2852 * Initialize a list of local addresses.
2853 */
2854 static status_t init_address_list(private_kernel_netlink_net_t *this)
2855 {
2856 netlink_buf_t request;
2857 struct nlmsghdr *out, *current, *in;
2858 struct rtgenmsg *msg;
2859 size_t len;
2860 enumerator_t *ifaces, *addrs;
2861 iface_entry_t *iface;
2862 addr_entry_t *addr;
2863
2864 DBG2(DBG_KNL, "known interfaces and IP addresses:");
2865
2866 memset(&request, 0, sizeof(request));
2867
2868 in = &request.hdr;
2869 in->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg));
2870 in->nlmsg_flags = NLM_F_REQUEST | NLM_F_MATCH | NLM_F_ROOT;
2871 msg = NLMSG_DATA(in);
2872 msg->rtgen_family = AF_UNSPEC;
2873
2874 /* get all links */
2875 in->nlmsg_type = RTM_GETLINK;
2876 if (this->socket->send(this->socket, in, &out, &len) != SUCCESS)
2877 {
2878