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