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