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