]> git.ipfire.org Git - thirdparty/strongswan.git/blob - src/libcharon/plugins/kernel_netlink/kernel_netlink_net.c
libhydra: Move kernel interface to libcharon
[thirdparty/strongswan.git] / src / libcharon / 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 <daemon.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 marks can be used in route lookups
495 */
496 bool rta_mark;
497
498 /**
499 * the mark excluded from the routing rule used for virtual IPs
500 */
501 mark_t routing_mark;
502
503 /**
504 * whether to prefer temporary IPv6 addresses over public ones
505 */
506 bool prefer_temporary_addrs;
507
508 /**
509 * list with routing tables to be excluded from route lookup
510 */
511 linked_list_t *rt_exclude;
512
513 /**
514 * MTU to set on installed routes
515 */
516 u_int32_t mtu;
517
518 /**
519 * MSS to set on installed routes
520 */
521 u_int32_t mss;
522 };
523
524 /**
525 * Forward declaration
526 */
527 static status_t manage_srcroute(private_kernel_netlink_net_t *this,
528 int nlmsg_type, int flags, chunk_t dst_net,
529 u_int8_t prefixlen, host_t *gateway,
530 host_t *src_ip, char *if_name);
531
532 /**
533 * Clear the queued network changes.
534 */
535 static void net_changes_clear(private_kernel_netlink_net_t *this)
536 {
537 enumerator_t *enumerator;
538 net_change_t *change;
539
540 enumerator = this->net_changes->create_enumerator(this->net_changes);
541 while (enumerator->enumerate(enumerator, NULL, (void**)&change))
542 {
543 this->net_changes->remove_at(this->net_changes, enumerator);
544 net_change_destroy(change);
545 }
546 enumerator->destroy(enumerator);
547 }
548
549 /**
550 * Act upon queued network changes.
551 */
552 static job_requeue_t reinstall_routes(private_kernel_netlink_net_t *this)
553 {
554 enumerator_t *enumerator;
555 route_entry_t *route;
556
557 this->net_changes_lock->lock(this->net_changes_lock);
558 this->routes_lock->lock(this->routes_lock);
559
560 enumerator = this->routes->create_enumerator(this->routes);
561 while (enumerator->enumerate(enumerator, NULL, (void**)&route))
562 {
563 net_change_t *change, lookup = {
564 .if_name = route->if_name,
565 };
566 /* check if a change for the outgoing interface is queued */
567 change = this->net_changes->get(this->net_changes, &lookup);
568 if (!change)
569 { /* in case src_ip is not on the outgoing interface */
570 if (this->public.interface.get_interface(&this->public.interface,
571 route->src_ip, &lookup.if_name))
572 {
573 if (!streq(lookup.if_name, route->if_name))
574 {
575 change = this->net_changes->get(this->net_changes, &lookup);
576 }
577 free(lookup.if_name);
578 }
579 }
580 if (change)
581 {
582 manage_srcroute(this, RTM_NEWROUTE, NLM_F_CREATE | NLM_F_EXCL,
583 route->dst_net, route->prefixlen, route->gateway,
584 route->src_ip, route->if_name);
585 }
586 }
587 enumerator->destroy(enumerator);
588 this->routes_lock->unlock(this->routes_lock);
589
590 net_changes_clear(this);
591 this->net_changes_lock->unlock(this->net_changes_lock);
592 return JOB_REQUEUE_NONE;
593 }
594
595 /**
596 * Queue route reinstallation caused by network changes for a given interface.
597 *
598 * The route reinstallation is delayed for a while and only done once for
599 * several calls during this delay, in order to avoid doing it too often.
600 * The interface name is freed.
601 */
602 static void queue_route_reinstall(private_kernel_netlink_net_t *this,
603 char *if_name)
604 {
605 net_change_t *update, *found;
606 timeval_t now;
607 job_t *job;
608
609 INIT(update,
610 .if_name = if_name
611 );
612
613 this->net_changes_lock->lock(this->net_changes_lock);
614 found = this->net_changes->put(this->net_changes, update, update);
615 if (found)
616 {
617 net_change_destroy(found);
618 }
619 time_monotonic(&now);
620 if (timercmp(&now, &this->last_route_reinstall, >))
621 {
622 timeval_add_ms(&now, ROUTE_DELAY);
623 this->last_route_reinstall = now;
624
625 job = (job_t*)callback_job_create((callback_job_cb_t)reinstall_routes,
626 this, NULL, NULL);
627 lib->scheduler->schedule_job_ms(lib->scheduler, job, ROUTE_DELAY);
628 }
629 this->net_changes_lock->unlock(this->net_changes_lock);
630 }
631
632 /**
633 * check if the given IP is known as virtual IP and currently installed
634 *
635 * this function will also return TRUE if the virtual IP entry disappeared.
636 * in that case the returned entry will be NULL.
637 *
638 * this->lock must be held when calling this function
639 */
640 static bool is_vip_installed_or_gone(private_kernel_netlink_net_t *this,
641 host_t *ip, addr_map_entry_t **entry)
642 {
643 addr_map_entry_t lookup = {
644 .ip = ip,
645 };
646
647 *entry = this->vips->get_match(this->vips, &lookup,
648 (void*)addr_map_entry_match);
649 if (*entry == NULL)
650 { /* the virtual IP disappeared */
651 return TRUE;
652 }
653 return (*entry)->addr->installed;
654 }
655
656 /**
657 * check if the given IP is known as virtual IP
658 *
659 * this->lock must be held when calling this function
660 */
661 static bool is_known_vip(private_kernel_netlink_net_t *this, host_t *ip)
662 {
663 addr_map_entry_t lookup = {
664 .ip = ip,
665 };
666
667 return this->vips->get_match(this->vips, &lookup,
668 (void*)addr_map_entry_match) != NULL;
669 }
670
671 /**
672 * Add an address map entry
673 */
674 static void addr_map_entry_add(hashtable_t *map, addr_entry_t *addr,
675 iface_entry_t *iface)
676 {
677 addr_map_entry_t *entry;
678
679 INIT(entry,
680 .ip = addr->ip,
681 .addr = addr,
682 .iface = iface,
683 );
684 entry = map->put(map, entry, entry);
685 free(entry);
686 }
687
688 /**
689 * Remove an address map entry
690 */
691 static void addr_map_entry_remove(hashtable_t *map, addr_entry_t *addr,
692 iface_entry_t *iface)
693 {
694 addr_map_entry_t *entry, lookup = {
695 .ip = addr->ip,
696 .addr = addr,
697 .iface = iface,
698 };
699
700 entry = map->remove(map, &lookup);
701 free(entry);
702 }
703
704 /**
705 * Determine the type or scope of the given unicast IP address. This is not
706 * the same thing returned in rtm_scope/ifa_scope.
707 *
708 * We use return values as defined in RFC 6724 (referring to RFC 4291).
709 */
710 static u_char get_scope(host_t *ip)
711 {
712 chunk_t addr;
713
714 addr = ip->get_address(ip);
715 switch (addr.len)
716 {
717 case 4:
718 /* we use the mapping defined in RFC 6724, 3.2 */
719 if (addr.ptr[0] == 127)
720 { /* link-local, same as the IPv6 loopback address */
721 return 2;
722 }
723 if (addr.ptr[0] == 169 && addr.ptr[1] == 254)
724 { /* link-local */
725 return 2;
726 }
727 break;
728 case 16:
729 if (IN6_IS_ADDR_LOOPBACK((struct in6_addr*)addr.ptr))
730 { /* link-local, according to RFC 4291, 2.5.3 */
731 return 2;
732 }
733 if (IN6_IS_ADDR_LINKLOCAL((struct in6_addr*)addr.ptr))
734 {
735 return 2;
736 }
737 if (IN6_IS_ADDR_SITELOCAL((struct in6_addr*)addr.ptr))
738 { /* deprecated, according to RFC 4291, 2.5.7 */
739 return 5;
740 }
741 break;
742 default:
743 break;
744 }
745 /* global */
746 return 14;
747 }
748
749 /**
750 * Returns the length of the common prefix in bits up to the length of a's
751 * prefix, defined by RFC 6724 as the portion of the address not including the
752 * interface ID, which is 64-bit for most unicast addresses (see RFC 4291).
753 */
754 static u_char common_prefix(host_t *a, host_t *b)
755 {
756 chunk_t aa, ba;
757 u_char byte, bits = 0, match;
758
759 aa = a->get_address(a);
760 ba = b->get_address(b);
761 for (byte = 0; byte < 8; byte++)
762 {
763 if (aa.ptr[byte] != ba.ptr[byte])
764 {
765 match = aa.ptr[byte] ^ ba.ptr[byte];
766 for (bits = 8; match; match >>= 1)
767 {
768 bits--;
769 }
770 break;
771 }
772 }
773 return byte * 8 + bits;
774 }
775
776 /**
777 * Compare two IP addresses and return TRUE if the second address is the better
778 * choice of the two to reach the destination.
779 * For IPv6 we approximately follow RFC 6724.
780 */
781 static bool is_address_better(private_kernel_netlink_net_t *this,
782 addr_entry_t *a, addr_entry_t *b, host_t *d)
783 {
784 u_char sa, sb, sd, pa, pb;
785
786 /* rule 2: prefer appropriate scope */
787 if (d)
788 {
789 sa = get_scope(a->ip);
790 sb = get_scope(b->ip);
791 sd = get_scope(d);
792 if (sa < sb)
793 {
794 return sa < sd;
795 }
796 else if (sb < sa)
797 {
798 return sb >= sd;
799 }
800 }
801 if (a->ip->get_family(a->ip) == AF_INET)
802 { /* stop here for IPv4, default to addresses found earlier */
803 return FALSE;
804 }
805 /* rule 3: avoid deprecated addresses (RFC 4862) */
806 if ((a->flags & IFA_F_DEPRECATED) != (b->flags & IFA_F_DEPRECATED))
807 {
808 return a->flags & IFA_F_DEPRECATED;
809 }
810 /* rule 4 is not applicable as we don't know if an address is a home or
811 * care-of addresses.
812 * rule 5 does not apply as we only compare addresses from one interface
813 * rule 6 requires a policy table (optionally configurable) to match
814 * configurable labels
815 */
816 /* rule 7: prefer temporary addresses (WE REVERSE THIS BY DEFAULT!) */
817 if ((a->flags & IFA_F_TEMPORARY) != (b->flags & IFA_F_TEMPORARY))
818 {
819 if (this->prefer_temporary_addrs)
820 {
821 return b->flags & IFA_F_TEMPORARY;
822 }
823 return a->flags & IFA_F_TEMPORARY;
824 }
825 /* rule 8: use longest matching prefix */
826 if (d)
827 {
828 pa = common_prefix(a->ip, d);
829 pb = common_prefix(b->ip, d);
830 if (pa != pb)
831 {
832 return pb > pa;
833 }
834 }
835 /* default to addresses found earlier */
836 return FALSE;
837 }
838
839 /**
840 * Get a non-virtual IP address on the given interface.
841 *
842 * If a candidate address is given, we first search for that address and if not
843 * found return the address as above.
844 * Returned host is a clone, has to be freed by caller.
845 *
846 * this->lock must be held when calling this function.
847 */
848 static host_t *get_interface_address(private_kernel_netlink_net_t *this,
849 int ifindex, int family, host_t *dest,
850 host_t *candidate)
851 {
852 iface_entry_t *iface;
853 enumerator_t *addrs;
854 addr_entry_t *addr, *best = NULL;
855
856 if (this->ifaces->find_first(this->ifaces, (void*)iface_entry_by_index,
857 (void**)&iface, &ifindex) == SUCCESS)
858 {
859 if (iface->usable)
860 { /* only use interfaces not excluded by config */
861 addrs = iface->addrs->create_enumerator(iface->addrs);
862 while (addrs->enumerate(addrs, &addr))
863 {
864 if (addr->refcount ||
865 addr->ip->get_family(addr->ip) != family)
866 { /* ignore virtual IP addresses and ensure family matches */
867 continue;
868 }
869 if (candidate && candidate->ip_equals(candidate, addr->ip))
870 { /* stop if we find the candidate */
871 best = addr;
872 break;
873 }
874 else if (!best || is_address_better(this, best, addr, dest))
875 {
876 best = addr;
877 }
878 }
879 addrs->destroy(addrs);
880 }
881 }
882 return best ? best->ip->clone(best->ip) : NULL;
883 }
884
885 /**
886 * callback function that raises the delayed roam event
887 */
888 static job_requeue_t roam_event(private_kernel_netlink_net_t *this)
889 {
890 bool address;
891
892 this->roam_lock->lock(this->roam_lock);
893 address = this->roam_address;
894 this->roam_address = FALSE;
895 this->roam_lock->unlock(this->roam_lock);
896 charon->kernel->roam(charon->kernel, address);
897 return JOB_REQUEUE_NONE;
898 }
899
900 /**
901 * fire a roaming event. we delay it for a bit and fire only one event
902 * for multiple calls. otherwise we would create too many events.
903 */
904 static void fire_roam_event(private_kernel_netlink_net_t *this, bool address)
905 {
906 timeval_t now;
907 job_t *job;
908
909 if (!this->roam_events)
910 {
911 return;
912 }
913
914 time_monotonic(&now);
915 this->roam_lock->lock(this->roam_lock);
916 this->roam_address |= address;
917 if (!timercmp(&now, &this->next_roam, >))
918 {
919 this->roam_lock->unlock(this->roam_lock);
920 return;
921 }
922 timeval_add_ms(&now, ROAM_DELAY);
923 this->next_roam = now;
924 this->roam_lock->unlock(this->roam_lock);
925
926 job = (job_t*)callback_job_create((callback_job_cb_t)roam_event,
927 this, NULL, NULL);
928 lib->scheduler->schedule_job_ms(lib->scheduler, job, ROAM_DELAY);
929 }
930
931 /**
932 * check if an interface with a given index is up and usable
933 *
934 * this->lock must be locked when calling this function
935 */
936 static bool is_interface_up_and_usable(private_kernel_netlink_net_t *this,
937 int index)
938 {
939 iface_entry_t *iface;
940
941 if (this->ifaces->find_first(this->ifaces, (void*)iface_entry_by_index,
942 (void**)&iface, &index) == SUCCESS)
943 {
944 return iface_entry_up_and_usable(iface);
945 }
946 return FALSE;
947 }
948
949 /**
950 * unregister the current addr_entry_t from the hashtable it is stored in
951 *
952 * this->lock must be locked when calling this function
953 */
954 static void addr_entry_unregister(addr_entry_t *addr, iface_entry_t *iface,
955 private_kernel_netlink_net_t *this)
956 {
957 if (addr->refcount)
958 {
959 addr_map_entry_remove(this->vips, addr, iface);
960 this->condvar->broadcast(this->condvar);
961 return;
962 }
963 addr_map_entry_remove(this->addrs, addr, iface);
964 }
965
966 /**
967 * process RTM_NEWLINK/RTM_DELLINK from kernel
968 */
969 static void process_link(private_kernel_netlink_net_t *this,
970 struct nlmsghdr *hdr, bool event)
971 {
972 struct ifinfomsg* msg = NLMSG_DATA(hdr);
973 struct rtattr *rta = IFLA_RTA(msg);
974 size_t rtasize = IFLA_PAYLOAD (hdr);
975 enumerator_t *enumerator;
976 iface_entry_t *current, *entry = NULL;
977 char *name = NULL;
978 bool update = FALSE, update_routes = FALSE;
979
980 while (RTA_OK(rta, rtasize))
981 {
982 switch (rta->rta_type)
983 {
984 case IFLA_IFNAME:
985 name = RTA_DATA(rta);
986 break;
987 }
988 rta = RTA_NEXT(rta, rtasize);
989 }
990 if (!name)
991 {
992 name = "(unknown)";
993 }
994
995 this->lock->write_lock(this->lock);
996 switch (hdr->nlmsg_type)
997 {
998 case RTM_NEWLINK:
999 {
1000 if (this->ifaces->find_first(this->ifaces,
1001 (void*)iface_entry_by_index, (void**)&entry,
1002 &msg->ifi_index) != SUCCESS)
1003 {
1004 INIT(entry,
1005 .ifindex = msg->ifi_index,
1006 .addrs = linked_list_create(),
1007 .usable = charon->kernel->is_interface_usable(
1008 charon->kernel, name),
1009 );
1010 this->ifaces->insert_last(this->ifaces, entry);
1011 }
1012 strncpy(entry->ifname, name, IFNAMSIZ);
1013 entry->ifname[IFNAMSIZ-1] = '\0';
1014 if (event && entry->usable)
1015 {
1016 if (!(entry->flags & IFF_UP) && (msg->ifi_flags & IFF_UP))
1017 {
1018 update = update_routes = TRUE;
1019 DBG1(DBG_KNL, "interface %s activated", name);
1020 }
1021 if ((entry->flags & IFF_UP) && !(msg->ifi_flags & IFF_UP))
1022 {
1023 update = TRUE;
1024 DBG1(DBG_KNL, "interface %s deactivated", name);
1025 }
1026 }
1027 entry->flags = msg->ifi_flags;
1028 break;
1029 }
1030 case RTM_DELLINK:
1031 {
1032 enumerator = this->ifaces->create_enumerator(this->ifaces);
1033 while (enumerator->enumerate(enumerator, &current))
1034 {
1035 if (current->ifindex == msg->ifi_index)
1036 {
1037 if (event && current->usable)
1038 {
1039 update = TRUE;
1040 DBG1(DBG_KNL, "interface %s deleted", current->ifname);
1041 }
1042 /* TODO: move virtual IPs installed on this interface to
1043 * another interface? */
1044 this->ifaces->remove_at(this->ifaces, enumerator);
1045 current->addrs->invoke_function(current->addrs,
1046 (void*)addr_entry_unregister, current, this);
1047 iface_entry_destroy(current);
1048 break;
1049 }
1050 }
1051 enumerator->destroy(enumerator);
1052 break;
1053 }
1054 }
1055 this->lock->unlock(this->lock);
1056
1057 if (update_routes && event)
1058 {
1059 queue_route_reinstall(this, strdup(name));
1060 }
1061
1062 if (update && event)
1063 {
1064 fire_roam_event(this, TRUE);
1065 }
1066 }
1067
1068 /**
1069 * process RTM_NEWADDR/RTM_DELADDR from kernel
1070 */
1071 static void process_addr(private_kernel_netlink_net_t *this,
1072 struct nlmsghdr *hdr, bool event)
1073 {
1074 struct ifaddrmsg* msg = NLMSG_DATA(hdr);
1075 struct rtattr *rta = IFA_RTA(msg);
1076 size_t rtasize = IFA_PAYLOAD (hdr);
1077 host_t *host = NULL;
1078 iface_entry_t *iface;
1079 chunk_t local = chunk_empty, address = chunk_empty;
1080 char *route_ifname = NULL;
1081 bool update = FALSE, found = FALSE, changed = FALSE;
1082
1083 while (RTA_OK(rta, rtasize))
1084 {
1085 switch (rta->rta_type)
1086 {
1087 case IFA_LOCAL:
1088 local.ptr = RTA_DATA(rta);
1089 local.len = RTA_PAYLOAD(rta);
1090 break;
1091 case IFA_ADDRESS:
1092 address.ptr = RTA_DATA(rta);
1093 address.len = RTA_PAYLOAD(rta);
1094 break;
1095 }
1096 rta = RTA_NEXT(rta, rtasize);
1097 }
1098
1099 /* For PPP interfaces, we need the IFA_LOCAL address,
1100 * IFA_ADDRESS is the peers address. But IFA_LOCAL is
1101 * not included in all cases (IPv6?), so fallback to IFA_ADDRESS. */
1102 if (local.ptr)
1103 {
1104 host = host_create_from_chunk(msg->ifa_family, local, 0);
1105 }
1106 else if (address.ptr)
1107 {
1108 host = host_create_from_chunk(msg->ifa_family, address, 0);
1109 }
1110
1111 if (host == NULL)
1112 { /* bad family? */
1113 return;
1114 }
1115
1116 this->lock->write_lock(this->lock);
1117 if (this->ifaces->find_first(this->ifaces, (void*)iface_entry_by_index,
1118 (void**)&iface, &msg->ifa_index) == SUCCESS)
1119 {
1120 addr_map_entry_t *entry, lookup = {
1121 .ip = host,
1122 .iface = iface,
1123 };
1124 addr_entry_t *addr;
1125
1126 entry = this->vips->get(this->vips, &lookup);
1127 if (entry)
1128 {
1129 if (hdr->nlmsg_type == RTM_NEWADDR)
1130 { /* mark as installed and signal waiting threads */
1131 entry->addr->installed = TRUE;
1132 }
1133 else
1134 { /* the address was already marked as uninstalled */
1135 addr = entry->addr;
1136 iface->addrs->remove(iface->addrs, addr, NULL);
1137 addr_map_entry_remove(this->vips, addr, iface);
1138 addr_entry_destroy(addr);
1139 }
1140 /* no roam events etc. for virtual IPs */
1141 this->condvar->broadcast(this->condvar);
1142 this->lock->unlock(this->lock);
1143 host->destroy(host);
1144 return;
1145 }
1146 entry = this->addrs->get(this->addrs, &lookup);
1147 if (entry)
1148 {
1149 if (hdr->nlmsg_type == RTM_DELADDR)
1150 {
1151 found = TRUE;
1152 addr = entry->addr;
1153 iface->addrs->remove(iface->addrs, addr, NULL);
1154 if (iface->usable)
1155 {
1156 changed = TRUE;
1157 DBG1(DBG_KNL, "%H disappeared from %s", host,
1158 iface->ifname);
1159 }
1160 addr_map_entry_remove(this->addrs, addr, iface);
1161 addr_entry_destroy(addr);
1162 }
1163 }
1164 else
1165 {
1166 if (hdr->nlmsg_type == RTM_NEWADDR)
1167 {
1168 found = TRUE;
1169 changed = TRUE;
1170 route_ifname = strdup(iface->ifname);
1171 INIT(addr,
1172 .ip = host->clone(host),
1173 .flags = msg->ifa_flags,
1174 .scope = msg->ifa_scope,
1175 );
1176 iface->addrs->insert_last(iface->addrs, addr);
1177 addr_map_entry_add(this->addrs, addr, iface);
1178 if (event && iface->usable)
1179 {
1180 DBG1(DBG_KNL, "%H appeared on %s", host, iface->ifname);
1181 }
1182 }
1183 }
1184 if (found && (iface->flags & IFF_UP))
1185 {
1186 update = TRUE;
1187 }
1188 if (!iface->usable)
1189 { /* ignore events for interfaces excluded by config */
1190 update = changed = FALSE;
1191 }
1192 }
1193 this->lock->unlock(this->lock);
1194
1195 if (update && event && route_ifname)
1196 {
1197 queue_route_reinstall(this, route_ifname);
1198 }
1199 else
1200 {
1201 free(route_ifname);
1202 }
1203 host->destroy(host);
1204
1205 /* send an update to all IKE_SAs */
1206 if (update && event && changed)
1207 {
1208 fire_roam_event(this, TRUE);
1209 }
1210 }
1211
1212 /**
1213 * process RTM_NEWROUTE and RTM_DELROUTE from kernel
1214 */
1215 static void process_route(private_kernel_netlink_net_t *this, struct nlmsghdr *hdr)
1216 {
1217 struct rtmsg* msg = NLMSG_DATA(hdr);
1218 struct rtattr *rta = RTM_RTA(msg);
1219 size_t rtasize = RTM_PAYLOAD(hdr);
1220 u_int32_t rta_oif = 0;
1221 host_t *host = NULL;
1222
1223 /* ignore routes added by us or in the local routing table (local addrs) */
1224 if (msg->rtm_table && (msg->rtm_table == this->routing_table ||
1225 msg->rtm_table == RT_TABLE_LOCAL))
1226 {
1227 return;
1228 }
1229 else if (msg->rtm_flags & RTM_F_CLONED)
1230 { /* ignore cached routes, seem to be created a lot for IPv6 */
1231 return;
1232 }
1233
1234 while (RTA_OK(rta, rtasize))
1235 {
1236 switch (rta->rta_type)
1237 {
1238 case RTA_PREFSRC:
1239 DESTROY_IF(host);
1240 host = host_create_from_chunk(msg->rtm_family,
1241 chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta)), 0);
1242 break;
1243 case RTA_OIF:
1244 if (RTA_PAYLOAD(rta) == sizeof(rta_oif))
1245 {
1246 rta_oif = *(u_int32_t*)RTA_DATA(rta);
1247 }
1248 break;
1249 }
1250 rta = RTA_NEXT(rta, rtasize);
1251 }
1252 this->lock->read_lock(this->lock);
1253 if (rta_oif && !is_interface_up_and_usable(this, rta_oif))
1254 { /* ignore route changes for interfaces that are ignored or down */
1255 this->lock->unlock(this->lock);
1256 DESTROY_IF(host);
1257 return;
1258 }
1259 if (!host && rta_oif)
1260 {
1261 host = get_interface_address(this, rta_oif, msg->rtm_family,
1262 NULL, NULL);
1263 }
1264 if (!host || is_known_vip(this, host))
1265 { /* ignore routes added for virtual IPs */
1266 this->lock->unlock(this->lock);
1267 DESTROY_IF(host);
1268 return;
1269 }
1270 this->lock->unlock(this->lock);
1271 fire_roam_event(this, FALSE);
1272 host->destroy(host);
1273 }
1274
1275 /**
1276 * Receives events from kernel
1277 */
1278 static bool receive_events(private_kernel_netlink_net_t *this, int fd,
1279 watcher_event_t event)
1280 {
1281 char response[1536];
1282 struct nlmsghdr *hdr = (struct nlmsghdr*)response;
1283 struct sockaddr_nl addr;
1284 socklen_t addr_len = sizeof(addr);
1285 int len;
1286
1287 len = recvfrom(this->socket_events, response, sizeof(response),
1288 MSG_DONTWAIT, (struct sockaddr*)&addr, &addr_len);
1289 if (len < 0)
1290 {
1291 switch (errno)
1292 {
1293 case EINTR:
1294 /* interrupted, try again */
1295 return TRUE;
1296 case EAGAIN:
1297 /* no data ready, select again */
1298 return TRUE;
1299 default:
1300 DBG1(DBG_KNL, "unable to receive from rt event socket");
1301 sleep(1);
1302 return TRUE;
1303 }
1304 }
1305
1306 if (addr.nl_pid != 0)
1307 { /* not from kernel. not interested, try another one */
1308 return TRUE;
1309 }
1310
1311 while (NLMSG_OK(hdr, len))
1312 {
1313 /* looks good so far, dispatch netlink message */
1314 switch (hdr->nlmsg_type)
1315 {
1316 case RTM_NEWADDR:
1317 case RTM_DELADDR:
1318 process_addr(this, hdr, TRUE);
1319 break;
1320 case RTM_NEWLINK:
1321 case RTM_DELLINK:
1322 process_link(this, hdr, TRUE);
1323 break;
1324 case RTM_NEWROUTE:
1325 case RTM_DELROUTE:
1326 if (this->process_route)
1327 {
1328 process_route(this, hdr);
1329 }
1330 break;
1331 default:
1332 break;
1333 }
1334 hdr = NLMSG_NEXT(hdr, len);
1335 }
1336 return TRUE;
1337 }
1338
1339 /** enumerator over addresses */
1340 typedef struct {
1341 private_kernel_netlink_net_t* this;
1342 /** which addresses to enumerate */
1343 kernel_address_type_t which;
1344 } address_enumerator_t;
1345
1346 /**
1347 * cleanup function for address enumerator
1348 */
1349 static void address_enumerator_destroy(address_enumerator_t *data)
1350 {
1351 data->this->lock->unlock(data->this->lock);
1352 free(data);
1353 }
1354
1355 /**
1356 * filter for addresses
1357 */
1358 static bool filter_addresses(address_enumerator_t *data,
1359 addr_entry_t** in, host_t** out)
1360 {
1361 if (!(data->which & ADDR_TYPE_VIRTUAL) && (*in)->refcount)
1362 { /* skip virtual interfaces added by us */
1363 return FALSE;
1364 }
1365 if (!(data->which & ADDR_TYPE_REGULAR) && !(*in)->refcount)
1366 { /* address is regular, but not requested */
1367 return FALSE;
1368 }
1369 if ((*in)->scope >= RT_SCOPE_LINK)
1370 { /* skip addresses with a unusable scope */
1371 return FALSE;
1372 }
1373 *out = (*in)->ip;
1374 return TRUE;
1375 }
1376
1377 /**
1378 * enumerator constructor for interfaces
1379 */
1380 static enumerator_t *create_iface_enumerator(iface_entry_t *iface,
1381 address_enumerator_t *data)
1382 {
1383 return enumerator_create_filter(
1384 iface->addrs->create_enumerator(iface->addrs),
1385 (void*)filter_addresses, data, NULL);
1386 }
1387
1388 /**
1389 * filter for interfaces
1390 */
1391 static bool filter_interfaces(address_enumerator_t *data, iface_entry_t** in,
1392 iface_entry_t** out)
1393 {
1394 if (!(data->which & ADDR_TYPE_IGNORED) && !(*in)->usable)
1395 { /* skip interfaces excluded by config */
1396 return FALSE;
1397 }
1398 if (!(data->which & ADDR_TYPE_LOOPBACK) && ((*in)->flags & IFF_LOOPBACK))
1399 { /* ignore loopback devices */
1400 return FALSE;
1401 }
1402 if (!(data->which & ADDR_TYPE_DOWN) && !((*in)->flags & IFF_UP))
1403 { /* skip interfaces not up */
1404 return FALSE;
1405 }
1406 *out = *in;
1407 return TRUE;
1408 }
1409
1410 METHOD(kernel_net_t, create_address_enumerator, enumerator_t*,
1411 private_kernel_netlink_net_t *this, kernel_address_type_t which)
1412 {
1413 address_enumerator_t *data;
1414
1415 INIT(data,
1416 .this = this,
1417 .which = which,
1418 );
1419
1420 this->lock->read_lock(this->lock);
1421 return enumerator_create_nested(
1422 enumerator_create_filter(
1423 this->ifaces->create_enumerator(this->ifaces),
1424 (void*)filter_interfaces, data, NULL),
1425 (void*)create_iface_enumerator, data,
1426 (void*)address_enumerator_destroy);
1427 }
1428
1429 METHOD(kernel_net_t, get_interface_name, bool,
1430 private_kernel_netlink_net_t *this, host_t* ip, char **name)
1431 {
1432 addr_map_entry_t *entry, lookup = {
1433 .ip = ip,
1434 };
1435
1436 if (ip->is_anyaddr(ip))
1437 {
1438 return FALSE;
1439 }
1440 this->lock->read_lock(this->lock);
1441 /* first try to find it on an up and usable interface */
1442 entry = this->addrs->get_match(this->addrs, &lookup,
1443 (void*)addr_map_entry_match_up_and_usable);
1444 if (entry)
1445 {
1446 if (name)
1447 {
1448 *name = strdup(entry->iface->ifname);
1449 DBG2(DBG_KNL, "%H is on interface %s", ip, *name);
1450 }
1451 this->lock->unlock(this->lock);
1452 return TRUE;
1453 }
1454 /* in a second step, consider virtual IPs installed by us */
1455 entry = this->vips->get_match(this->vips, &lookup,
1456 (void*)addr_map_entry_match_up_and_usable);
1457 if (entry)
1458 {
1459 if (name)
1460 {
1461 *name = strdup(entry->iface->ifname);
1462 DBG2(DBG_KNL, "virtual IP %H is on interface %s", ip, *name);
1463 }
1464 this->lock->unlock(this->lock);
1465 return TRUE;
1466 }
1467 /* maybe it is installed on an ignored interface */
1468 entry = this->addrs->get_match(this->addrs, &lookup,
1469 (void*)addr_map_entry_match_up);
1470 if (!entry)
1471 {
1472 DBG2(DBG_KNL, "%H is not a local address or the interface is down", ip);
1473 }
1474 this->lock->unlock(this->lock);
1475 return FALSE;
1476 }
1477
1478 /**
1479 * get the index of an interface by name
1480 */
1481 static int get_interface_index(private_kernel_netlink_net_t *this, char* name)
1482 {
1483 iface_entry_t *iface;
1484 int ifindex = 0;
1485
1486 DBG2(DBG_KNL, "getting iface index for %s", name);
1487
1488 this->lock->read_lock(this->lock);
1489 if (this->ifaces->find_first(this->ifaces, (void*)iface_entry_by_name,
1490 (void**)&iface, name) == SUCCESS)
1491 {
1492 ifindex = iface->ifindex;
1493 }
1494 this->lock->unlock(this->lock);
1495
1496 if (ifindex == 0)
1497 {
1498 DBG1(DBG_KNL, "unable to get interface index for %s", name);
1499 }
1500 return ifindex;
1501 }
1502
1503 /**
1504 * check if an address or net (addr with prefix net bits) is in
1505 * subnet (net with net_len net bits)
1506 */
1507 static bool addr_in_subnet(chunk_t addr, int prefix, chunk_t net, int net_len)
1508 {
1509 static const u_char mask[] = { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
1510 int byte = 0;
1511
1512 if (net_len == 0)
1513 { /* any address matches a /0 network */
1514 return TRUE;
1515 }
1516 if (addr.len != net.len || net_len > 8 * net.len || prefix < net_len)
1517 {
1518 return FALSE;
1519 }
1520 /* scan through all bytes in network order */
1521 while (net_len > 0)
1522 {
1523 if (net_len < 8)
1524 {
1525 return (mask[net_len] & addr.ptr[byte]) == (mask[net_len] & net.ptr[byte]);
1526 }
1527 else
1528 {
1529 if (addr.ptr[byte] != net.ptr[byte])
1530 {
1531 return FALSE;
1532 }
1533 byte++;
1534 net_len -= 8;
1535 }
1536 }
1537 return TRUE;
1538 }
1539
1540 /**
1541 * Store information about a route retrieved via RTNETLINK
1542 */
1543 typedef struct {
1544 chunk_t gtw;
1545 chunk_t src;
1546 chunk_t dst;
1547 host_t *src_host;
1548 u_int8_t dst_len;
1549 u_int32_t table;
1550 u_int32_t oif;
1551 u_int32_t priority;
1552 } rt_entry_t;
1553
1554 /**
1555 * Free a route entry
1556 */
1557 static void rt_entry_destroy(rt_entry_t *this)
1558 {
1559 DESTROY_IF(this->src_host);
1560 free(this);
1561 }
1562
1563 /**
1564 * Check if the route received with RTM_NEWROUTE is usable based on its type.
1565 */
1566 static bool route_usable(struct nlmsghdr *hdr)
1567 {
1568 struct rtmsg *msg;
1569
1570 msg = NLMSG_DATA(hdr);
1571 switch (msg->rtm_type)
1572 {
1573 case RTN_BLACKHOLE:
1574 case RTN_UNREACHABLE:
1575 case RTN_PROHIBIT:
1576 case RTN_THROW:
1577 return FALSE;
1578 default:
1579 return TRUE;
1580 }
1581 }
1582
1583 /**
1584 * Parse route received with RTM_NEWROUTE. The given rt_entry_t object will be
1585 * reused if not NULL.
1586 *
1587 * Returned chunks point to internal data of the Netlink message.
1588 */
1589 static rt_entry_t *parse_route(struct nlmsghdr *hdr, rt_entry_t *route)
1590 {
1591 struct rtattr *rta;
1592 struct rtmsg *msg;
1593 size_t rtasize;
1594
1595 msg = NLMSG_DATA(hdr);
1596 rta = RTM_RTA(msg);
1597 rtasize = RTM_PAYLOAD(hdr);
1598
1599 if (route)
1600 {
1601 route->gtw = chunk_empty;
1602 route->src = chunk_empty;
1603 route->dst = chunk_empty;
1604 route->dst_len = msg->rtm_dst_len;
1605 route->table = msg->rtm_table;
1606 route->oif = 0;
1607 route->priority = 0;
1608 }
1609 else
1610 {
1611 INIT(route,
1612 .dst_len = msg->rtm_dst_len,
1613 .table = msg->rtm_table,
1614 );
1615 }
1616
1617 while (RTA_OK(rta, rtasize))
1618 {
1619 switch (rta->rta_type)
1620 {
1621 case RTA_PREFSRC:
1622 route->src = chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta));
1623 break;
1624 case RTA_GATEWAY:
1625 route->gtw = chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta));
1626 break;
1627 case RTA_DST:
1628 route->dst = chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta));
1629 break;
1630 case RTA_OIF:
1631 if (RTA_PAYLOAD(rta) == sizeof(route->oif))
1632 {
1633 route->oif = *(u_int32_t*)RTA_DATA(rta);
1634 }
1635 break;
1636 case RTA_PRIORITY:
1637 if (RTA_PAYLOAD(rta) == sizeof(route->priority))
1638 {
1639 route->priority = *(u_int32_t*)RTA_DATA(rta);
1640 }
1641 break;
1642 #ifdef HAVE_RTA_TABLE
1643 case RTA_TABLE:
1644 if (RTA_PAYLOAD(rta) == sizeof(route->table))
1645 {
1646 route->table = *(u_int32_t*)RTA_DATA(rta);
1647 }
1648 break;
1649 #endif /* HAVE_RTA_TABLE*/
1650 }
1651 rta = RTA_NEXT(rta, rtasize);
1652 }
1653 return route;
1654 }
1655
1656 /**
1657 * Get a route: If "nexthop", the nexthop is returned. source addr otherwise.
1658 */
1659 static host_t *get_route(private_kernel_netlink_net_t *this, host_t *dest,
1660 int prefix, bool nexthop, host_t *candidate,
1661 u_int recursion)
1662 {
1663 netlink_buf_t request;
1664 struct nlmsghdr *hdr, *out, *current;
1665 struct rtmsg *msg;
1666 chunk_t chunk;
1667 size_t len;
1668 linked_list_t *routes;
1669 rt_entry_t *route = NULL, *best = NULL;
1670 enumerator_t *enumerator;
1671 host_t *addr = NULL;
1672 bool match_net;
1673 int family;
1674
1675 if (recursion > MAX_ROUTE_RECURSION)
1676 {
1677 return NULL;
1678 }
1679 chunk = dest->get_address(dest);
1680 len = chunk.len * 8;
1681 prefix = prefix < 0 ? len : min(prefix, len);
1682 match_net = prefix != len;
1683
1684 memset(&request, 0, sizeof(request));
1685
1686 family = dest->get_family(dest);
1687 hdr = &request.hdr;
1688 hdr->nlmsg_flags = NLM_F_REQUEST;
1689 hdr->nlmsg_type = RTM_GETROUTE;
1690 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
1691
1692 msg = NLMSG_DATA(hdr);
1693 msg->rtm_family = family;
1694 if (!match_net && this->rta_mark && this->routing_mark.value)
1695 {
1696 /* if our routing rule excludes packets with a certain mark we can
1697 * get the preferred route without having to dump all routes */
1698 chunk = chunk_from_thing(this->routing_mark.value);
1699 netlink_add_attribute(hdr, RTA_MARK, chunk, sizeof(request));
1700 }
1701 else if (family == AF_INET || this->rta_prefsrc_for_ipv6 ||
1702 this->routing_table || match_net)
1703 { /* kernels prior to 3.0 do not support RTA_PREFSRC for IPv6 routes.
1704 * as we want to ignore routes with virtual IPs we cannot use DUMP
1705 * if these routes are not installed in a separate table */
1706 hdr->nlmsg_flags |= NLM_F_DUMP;
1707 }
1708 if (candidate)
1709 {
1710 chunk = candidate->get_address(candidate);
1711 netlink_add_attribute(hdr, RTA_PREFSRC, chunk, sizeof(request));
1712 }
1713 if (!match_net)
1714 {
1715 chunk = dest->get_address(dest);
1716 netlink_add_attribute(hdr, RTA_DST, chunk, sizeof(request));
1717 }
1718
1719 if (this->socket->send(this->socket, hdr, &out, &len) != SUCCESS)
1720 {
1721 DBG2(DBG_KNL, "getting %s to reach %H/%d failed",
1722 nexthop ? "nexthop" : "address", dest, prefix);
1723 return NULL;
1724 }
1725 routes = linked_list_create();
1726 this->lock->read_lock(this->lock);
1727
1728 for (current = out; NLMSG_OK(current, len);
1729 current = NLMSG_NEXT(current, len))
1730 {
1731 switch (current->nlmsg_type)
1732 {
1733 case NLMSG_DONE:
1734 break;
1735 case RTM_NEWROUTE:
1736 {
1737 rt_entry_t *other;
1738 uintptr_t table;
1739
1740 if (!route_usable(current))
1741 {
1742 continue;
1743 }
1744 route = parse_route(current, route);
1745
1746 table = (uintptr_t)route->table;
1747 if (this->rt_exclude->find_first(this->rt_exclude, NULL,
1748 (void**)&table) == SUCCESS)
1749 { /* route is from an excluded routing table */
1750 continue;
1751 }
1752 if (this->routing_table != 0 &&
1753 route->table == this->routing_table)
1754 { /* route is from our own ipsec routing table */
1755 continue;
1756 }
1757 if (route->oif && !is_interface_up_and_usable(this, route->oif))
1758 { /* interface is down */
1759 continue;
1760 }
1761 if (!addr_in_subnet(chunk, prefix, route->dst, route->dst_len))
1762 { /* route destination does not contain dest */
1763 continue;
1764 }
1765 if (route->src.ptr)
1766 { /* verify source address, if any */
1767 host_t *src = host_create_from_chunk(msg->rtm_family,
1768 route->src, 0);
1769 if (src && is_known_vip(this, src))
1770 { /* ignore routes installed by us */
1771 src->destroy(src);
1772 continue;
1773 }
1774 route->src_host = src;
1775 }
1776 /* insert route, sorted by priority and network prefix */
1777 enumerator = routes->create_enumerator(routes);
1778 while (enumerator->enumerate(enumerator, &other))
1779 {
1780 if (route->priority < other->priority)
1781 {
1782 break;
1783 }
1784 if (route->priority == other->priority &&
1785 route->dst_len > other->dst_len)
1786 {
1787 break;
1788 }
1789 }
1790 routes->insert_before(routes, enumerator, route);
1791 enumerator->destroy(enumerator);
1792 route = NULL;
1793 continue;
1794 }
1795 default:
1796 continue;
1797 }
1798 break;
1799 }
1800 if (route)
1801 {
1802 rt_entry_destroy(route);
1803 }
1804
1805 /* now we have a list of routes matching dest, sorted by net prefix.
1806 * we will look for source addresses for these routes and select the one
1807 * with the preferred source address, if possible */
1808 enumerator = routes->create_enumerator(routes);
1809 while (enumerator->enumerate(enumerator, &route))
1810 {
1811 if (route->src_host)
1812 { /* got a source address with the route, if no preferred source
1813 * is given or it matches we are done, as this is the best route */
1814 if (!candidate || candidate->ip_equals(candidate, route->src_host))
1815 {
1816 best = route;
1817 break;
1818 }
1819 else if (route->oif)
1820 { /* no match yet, maybe it is assigned to the same interface */
1821 host_t *src = get_interface_address(this, route->oif,
1822 msg->rtm_family, dest, candidate);
1823 if (src && src->ip_equals(src, candidate))
1824 {
1825 route->src_host->destroy(route->src_host);
1826 route->src_host = src;
1827 best = route;
1828 break;
1829 }
1830 DESTROY_IF(src);
1831 }
1832 /* no luck yet with the source address. if this is the best (first)
1833 * route we store it as fallback in case we don't find a route with
1834 * the preferred source */
1835 best = best ?: route;
1836 continue;
1837 }
1838 if (route->oif)
1839 { /* no src, but an interface - get address from it */
1840 route->src_host = get_interface_address(this, route->oif,
1841 msg->rtm_family, dest, candidate);
1842 if (route->src_host)
1843 { /* we handle this address the same as the one above */
1844 if (!candidate ||
1845 candidate->ip_equals(candidate, route->src_host))
1846 {
1847 best = route;
1848 break;
1849 }
1850 best = best ?: route;
1851 continue;
1852 }
1853 }
1854 if (route->gtw.ptr)
1855 { /* no src, no iface, but a gateway - lookup src to reach gtw */
1856 host_t *gtw;
1857
1858 gtw = host_create_from_chunk(msg->rtm_family, route->gtw, 0);
1859 if (gtw && !gtw->ip_equals(gtw, dest))
1860 {
1861 route->src_host = get_route(this, gtw, -1, FALSE, candidate,
1862 recursion + 1);
1863 }
1864 DESTROY_IF(gtw);
1865 if (route->src_host)
1866 { /* more of the same */
1867 if (!candidate ||
1868 candidate->ip_equals(candidate, route->src_host))
1869 {
1870 best = route;
1871 break;
1872 }
1873 best = best ?: route;
1874 }
1875 }
1876 }
1877 enumerator->destroy(enumerator);
1878
1879 if (nexthop)
1880 { /* nexthop lookup, return gateway if any */
1881 if (best || routes->get_first(routes, (void**)&best) == SUCCESS)
1882 {
1883 addr = host_create_from_chunk(msg->rtm_family, best->gtw, 0);
1884 }
1885 if (!addr && !match_net)
1886 { /* fallback to destination address */
1887 addr = dest->clone(dest);
1888 }
1889 }
1890 else
1891 {
1892 if (best)
1893 {
1894 addr = best->src_host->clone(best->src_host);
1895 }
1896 }
1897 this->lock->unlock(this->lock);
1898 routes->destroy_function(routes, (void*)rt_entry_destroy);
1899 free(out);
1900
1901 if (addr)
1902 {
1903 DBG2(DBG_KNL, "using %H as %s to reach %H/%d", addr,
1904 nexthop ? "nexthop" : "address", dest, prefix);
1905 }
1906 else if (!recursion)
1907 {
1908 DBG2(DBG_KNL, "no %s found to reach %H/%d",
1909 nexthop ? "nexthop" : "address", dest, prefix);
1910 }
1911 return addr;
1912 }
1913
1914 METHOD(kernel_net_t, get_source_addr, host_t*,
1915 private_kernel_netlink_net_t *this, host_t *dest, host_t *src)
1916 {
1917 return get_route(this, dest, -1, FALSE, src, 0);
1918 }
1919
1920 METHOD(kernel_net_t, get_nexthop, host_t*,
1921 private_kernel_netlink_net_t *this, host_t *dest, int prefix, host_t *src)
1922 {
1923 return get_route(this, dest, prefix, TRUE, src, 0);
1924 }
1925
1926 /**
1927 * Manages the creation and deletion of ip addresses on an interface.
1928 * By setting the appropriate nlmsg_type, the ip will be set or unset.
1929 */
1930 static status_t manage_ipaddr(private_kernel_netlink_net_t *this, int nlmsg_type,
1931 int flags, int if_index, host_t *ip, int prefix)
1932 {
1933 netlink_buf_t request;
1934 struct nlmsghdr *hdr;
1935 struct ifaddrmsg *msg;
1936 chunk_t chunk;
1937
1938 memset(&request, 0, sizeof(request));
1939
1940 chunk = ip->get_address(ip);
1941
1942 hdr = &request.hdr;
1943 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
1944 hdr->nlmsg_type = nlmsg_type;
1945 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg));
1946
1947 msg = NLMSG_DATA(hdr);
1948 msg->ifa_family = ip->get_family(ip);
1949 msg->ifa_flags = 0;
1950 msg->ifa_prefixlen = prefix < 0 ? chunk.len * 8 : prefix;
1951 msg->ifa_scope = RT_SCOPE_UNIVERSE;
1952 msg->ifa_index = if_index;
1953
1954 netlink_add_attribute(hdr, IFA_LOCAL, chunk, sizeof(request));
1955
1956 if (ip->get_family(ip) == AF_INET6 && this->rta_prefsrc_for_ipv6)
1957 { /* if source routes are possible we let the virtual IP get deprecated
1958 * immediately (but mark it as valid forever) so it gets only used if
1959 * forced by our route, and not by the default IPv6 address selection */
1960 struct ifa_cacheinfo cache = {
1961 .ifa_valid = 0xFFFFFFFF,
1962 .ifa_prefered = 0,
1963 };
1964 netlink_add_attribute(hdr, IFA_CACHEINFO, chunk_from_thing(cache),
1965 sizeof(request));
1966 }
1967 return this->socket->send_ack(this->socket, hdr);
1968 }
1969
1970 METHOD(kernel_net_t, add_ip, status_t,
1971 private_kernel_netlink_net_t *this, host_t *virtual_ip, int prefix,
1972 char *iface_name)
1973 {
1974 addr_map_entry_t *entry, lookup = {
1975 .ip = virtual_ip,
1976 };
1977 iface_entry_t *iface = NULL;
1978
1979 if (!this->install_virtual_ip)
1980 { /* disabled by config */
1981 return SUCCESS;
1982 }
1983
1984 this->lock->write_lock(this->lock);
1985 /* the virtual IP might actually be installed as regular IP, in which case
1986 * we don't track it as virtual IP */
1987 entry = this->addrs->get_match(this->addrs, &lookup,
1988 (void*)addr_map_entry_match);
1989 if (!entry)
1990 { /* otherwise it might already be installed as virtual IP */
1991 entry = this->vips->get_match(this->vips, &lookup,
1992 (void*)addr_map_entry_match);
1993 if (entry)
1994 { /* the vip we found can be in one of three states: 1) installed and
1995 * ready, 2) just added by another thread, but not yet confirmed to
1996 * be installed by the kernel, 3) just deleted, but not yet gone.
1997 * Then while we wait below, several things could happen (as we
1998 * release the lock). For instance, the interface could disappear,
1999 * or the IP is finally deleted, and it reappears on a different
2000 * interface. All these cases are handled by the call below. */
2001 while (!is_vip_installed_or_gone(this, virtual_ip, &entry))
2002 {
2003 this->condvar->wait(this->condvar, this->lock);
2004 }
2005 if (entry)
2006 {
2007 entry->addr->refcount++;
2008 }
2009 }
2010 }
2011 if (entry)
2012 {
2013 DBG2(DBG_KNL, "virtual IP %H is already installed on %s", virtual_ip,
2014 entry->iface->ifname);
2015 this->lock->unlock(this->lock);
2016 return SUCCESS;
2017 }
2018 /* try to find the target interface, either by config or via src ip */
2019 if (!this->install_virtual_ip_on ||
2020 this->ifaces->find_first(this->ifaces, (void*)iface_entry_by_name,
2021 (void**)&iface, this->install_virtual_ip_on) != SUCCESS)
2022 {
2023 if (this->ifaces->find_first(this->ifaces, (void*)iface_entry_by_name,
2024 (void**)&iface, iface_name) != SUCCESS)
2025 { /* if we don't find the requested interface we just use the first */
2026 this->ifaces->get_first(this->ifaces, (void**)&iface);
2027 }
2028 }
2029 if (iface)
2030 {
2031 addr_entry_t *addr;
2032 char *ifname;
2033 int ifi;
2034
2035 INIT(addr,
2036 .ip = virtual_ip->clone(virtual_ip),
2037 .refcount = 1,
2038 .scope = RT_SCOPE_UNIVERSE,
2039 );
2040 iface->addrs->insert_last(iface->addrs, addr);
2041 addr_map_entry_add(this->vips, addr, iface);
2042 ifi = iface->ifindex;
2043 this->lock->unlock(this->lock);
2044 if (manage_ipaddr(this, RTM_NEWADDR, NLM_F_CREATE | NLM_F_EXCL,
2045 ifi, virtual_ip, prefix) == SUCCESS)
2046 {
2047 this->lock->write_lock(this->lock);
2048 while (!is_vip_installed_or_gone(this, virtual_ip, &entry))
2049 { /* wait until address appears */
2050 this->condvar->wait(this->condvar, this->lock);
2051 }
2052 if (entry)
2053 { /* we fail if the interface got deleted in the meantime */
2054 ifname = strdup(entry->iface->ifname);
2055 this->lock->unlock(this->lock);
2056 DBG2(DBG_KNL, "virtual IP %H installed on %s",
2057 virtual_ip, ifname);
2058 /* during IKEv1 reauthentication, children get moved from
2059 * old the new SA before the virtual IP is available. This
2060 * kills the route for our virtual IP, reinstall. */
2061 queue_route_reinstall(this, ifname);
2062 return SUCCESS;
2063 }
2064 this->lock->unlock(this->lock);
2065 }
2066 DBG1(DBG_KNL, "adding virtual IP %H failed", virtual_ip);
2067 return FAILED;
2068 }
2069 this->lock->unlock(this->lock);
2070 DBG1(DBG_KNL, "no interface available, unable to install virtual IP %H",
2071 virtual_ip);
2072 return FAILED;
2073 }
2074
2075 METHOD(kernel_net_t, del_ip, status_t,
2076 private_kernel_netlink_net_t *this, host_t *virtual_ip, int prefix,
2077 bool wait)
2078 {
2079 addr_map_entry_t *entry, lookup = {
2080 .ip = virtual_ip,
2081 };
2082
2083 if (!this->install_virtual_ip)
2084 { /* disabled by config */
2085 return SUCCESS;
2086 }
2087
2088 DBG2(DBG_KNL, "deleting virtual IP %H", virtual_ip);
2089
2090 this->lock->write_lock(this->lock);
2091 entry = this->vips->get_match(this->vips, &lookup,
2092 (void*)addr_map_entry_match);
2093 if (!entry)
2094 { /* we didn't install this IP as virtual IP */
2095 entry = this->addrs->get_match(this->addrs, &lookup,
2096 (void*)addr_map_entry_match);
2097 if (entry)
2098 {
2099 DBG2(DBG_KNL, "not deleting existing IP %H on %s", virtual_ip,
2100 entry->iface->ifname);
2101 this->lock->unlock(this->lock);
2102 return SUCCESS;
2103 }
2104 DBG2(DBG_KNL, "virtual IP %H not cached, unable to delete", virtual_ip);
2105 this->lock->unlock(this->lock);
2106 return FAILED;
2107 }
2108 if (entry->addr->refcount == 1)
2109 {
2110 status_t status;
2111 int ifi;
2112
2113 /* we set this flag so that threads calling add_ip will block and wait
2114 * until the entry is gone, also so we can wait below */
2115 entry->addr->installed = FALSE;
2116 ifi = entry->iface->ifindex;
2117 this->lock->unlock(this->lock);
2118 status = manage_ipaddr(this, RTM_DELADDR, 0, ifi, virtual_ip, prefix);
2119 if (status == SUCCESS && wait)
2120 { /* wait until the address is really gone */
2121 this->lock->write_lock(this->lock);
2122 while (is_known_vip(this, virtual_ip))
2123 {
2124 this->condvar->wait(this->condvar, this->lock);
2125 }
2126 this->lock->unlock(this->lock);
2127 }
2128 return status;
2129 }
2130 else
2131 {
2132 entry->addr->refcount--;
2133 }
2134 DBG2(DBG_KNL, "virtual IP %H used by other SAs, not deleting",
2135 virtual_ip);
2136 this->lock->unlock(this->lock);
2137 return SUCCESS;
2138 }
2139
2140 /**
2141 * Manages source routes in the routing table.
2142 * By setting the appropriate nlmsg_type, the route gets added or removed.
2143 */
2144 static status_t manage_srcroute(private_kernel_netlink_net_t *this,
2145 int nlmsg_type, int flags, chunk_t dst_net,
2146 u_int8_t prefixlen, host_t *gateway,
2147 host_t *src_ip, char *if_name)
2148 {
2149 netlink_buf_t request;
2150 struct nlmsghdr *hdr;
2151 struct rtmsg *msg;
2152 struct rtattr *rta;
2153 int ifindex;
2154 chunk_t chunk;
2155
2156 /* if route is 0.0.0.0/0, we can't install it, as it would
2157 * overwrite the default route. Instead, we add two routes:
2158 * 0.0.0.0/1 and 128.0.0.0/1 */
2159 if (this->routing_table == 0 && prefixlen == 0)
2160 {
2161 chunk_t half_net;
2162 u_int8_t half_prefixlen;
2163 status_t status;
2164
2165 half_net = chunk_alloca(dst_net.len);
2166 memset(half_net.ptr, 0, half_net.len);
2167 half_prefixlen = 1;
2168
2169 status = manage_srcroute(this, nlmsg_type, flags, half_net, half_prefixlen,
2170 gateway, src_ip, if_name);
2171 half_net.ptr[0] |= 0x80;
2172 status = manage_srcroute(this, nlmsg_type, flags, half_net, half_prefixlen,
2173 gateway, src_ip, if_name);
2174 return status;
2175 }
2176
2177 memset(&request, 0, sizeof(request));
2178
2179 hdr = &request.hdr;
2180 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
2181 hdr->nlmsg_type = nlmsg_type;
2182 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
2183
2184 msg = NLMSG_DATA(hdr);
2185 msg->rtm_family = src_ip->get_family(src_ip);
2186 msg->rtm_dst_len = prefixlen;
2187 msg->rtm_table = this->routing_table;
2188 msg->rtm_protocol = RTPROT_STATIC;
2189 msg->rtm_type = RTN_UNICAST;
2190 msg->rtm_scope = RT_SCOPE_UNIVERSE;
2191
2192 netlink_add_attribute(hdr, RTA_DST, dst_net, sizeof(request));
2193 chunk = src_ip->get_address(src_ip);
2194 netlink_add_attribute(hdr, RTA_PREFSRC, chunk, sizeof(request));
2195 if (gateway && gateway->get_family(gateway) == src_ip->get_family(src_ip))
2196 {
2197 chunk = gateway->get_address(gateway);
2198 netlink_add_attribute(hdr, RTA_GATEWAY, chunk, sizeof(request));
2199 }
2200 ifindex = get_interface_index(this, if_name);
2201 chunk.ptr = (char*)&ifindex;
2202 chunk.len = sizeof(ifindex);
2203 netlink_add_attribute(hdr, RTA_OIF, chunk, sizeof(request));
2204
2205 if (this->mtu || this->mss)
2206 {
2207 chunk = chunk_alloca(RTA_LENGTH((sizeof(struct rtattr) +
2208 sizeof(u_int32_t)) * 2));
2209 chunk.len = 0;
2210 rta = (struct rtattr*)chunk.ptr;
2211 if (this->mtu)
2212 {
2213 rta->rta_type = RTAX_MTU;
2214 rta->rta_len = RTA_LENGTH(sizeof(u_int32_t));
2215 memcpy(RTA_DATA(rta), &this->mtu, sizeof(u_int32_t));
2216 chunk.len = rta->rta_len;
2217 }
2218 if (this->mss)
2219 {
2220 rta = (struct rtattr*)(chunk.ptr + RTA_ALIGN(chunk.len));
2221 rta->rta_type = RTAX_ADVMSS;
2222 rta->rta_len = RTA_LENGTH(sizeof(u_int32_t));
2223 memcpy(RTA_DATA(rta), &this->mss, sizeof(u_int32_t));
2224 chunk.len = RTA_ALIGN(chunk.len) + rta->rta_len;
2225 }
2226 netlink_add_attribute(hdr, RTA_METRICS, chunk, sizeof(request));
2227 }
2228
2229 return this->socket->send_ack(this->socket, hdr);
2230 }
2231
2232 METHOD(kernel_net_t, add_route, status_t,
2233 private_kernel_netlink_net_t *this, chunk_t dst_net, u_int8_t prefixlen,
2234 host_t *gateway, host_t *src_ip, char *if_name)
2235 {
2236 status_t status;
2237 route_entry_t *found, route = {
2238 .dst_net = dst_net,
2239 .prefixlen = prefixlen,
2240 .gateway = gateway,
2241 .src_ip = src_ip,
2242 .if_name = if_name,
2243 };
2244
2245 this->routes_lock->lock(this->routes_lock);
2246 found = this->routes->get(this->routes, &route);
2247 if (found)
2248 {
2249 this->routes_lock->unlock(this->routes_lock);
2250 return ALREADY_DONE;
2251 }
2252 status = manage_srcroute(this, RTM_NEWROUTE, NLM_F_CREATE | NLM_F_EXCL,
2253 dst_net, prefixlen, gateway, src_ip, if_name);
2254 if (status == SUCCESS)
2255 {
2256 found = route_entry_clone(&route);
2257 this->routes->put(this->routes, found, found);
2258 }
2259 this->routes_lock->unlock(this->routes_lock);
2260 return status;
2261 }
2262
2263 METHOD(kernel_net_t, del_route, status_t,
2264 private_kernel_netlink_net_t *this, chunk_t dst_net, u_int8_t prefixlen,
2265 host_t *gateway, host_t *src_ip, char *if_name)
2266 {
2267 status_t status;
2268 route_entry_t *found, route = {
2269 .dst_net = dst_net,
2270 .prefixlen = prefixlen,
2271 .gateway = gateway,
2272 .src_ip = src_ip,
2273 .if_name = if_name,
2274 };
2275
2276 this->routes_lock->lock(this->routes_lock);
2277 found = this->routes->get(this->routes, &route);
2278 if (!found)
2279 {
2280 this->routes_lock->unlock(this->routes_lock);
2281 return NOT_FOUND;
2282 }
2283 this->routes->remove(this->routes, found);
2284 route_entry_destroy(found);
2285 status = manage_srcroute(this, RTM_DELROUTE, 0, dst_net, prefixlen,
2286 gateway, src_ip, if_name);
2287 this->routes_lock->unlock(this->routes_lock);
2288 return status;
2289 }
2290
2291 /**
2292 * Initialize a list of local addresses.
2293 */
2294 static status_t init_address_list(private_kernel_netlink_net_t *this)
2295 {
2296 netlink_buf_t request;
2297 struct nlmsghdr *out, *current, *in;
2298 struct rtgenmsg *msg;
2299 size_t len;
2300 enumerator_t *ifaces, *addrs;
2301 iface_entry_t *iface;
2302 addr_entry_t *addr;
2303
2304 DBG2(DBG_KNL, "known interfaces and IP addresses:");
2305
2306 memset(&request, 0, sizeof(request));
2307
2308 in = &request.hdr;
2309 in->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg));
2310 in->nlmsg_flags = NLM_F_REQUEST | NLM_F_MATCH | NLM_F_ROOT;
2311 msg = NLMSG_DATA(in);
2312 msg->rtgen_family = AF_UNSPEC;
2313
2314 /* get all links */
2315 in->nlmsg_type = RTM_GETLINK;
2316 if (this->socket->send(this->socket, in, &out, &len) != SUCCESS)
2317 {
2318 return FAILED;
2319 }
2320 current = out;
2321 while (NLMSG_OK(current, len))
2322 {
2323 switch (current->nlmsg_type)
2324 {
2325 case NLMSG_DONE:
2326 break;
2327 case RTM_NEWLINK:
2328 process_link(this, current, FALSE);
2329 /* fall through */
2330 default:
2331 current = NLMSG_NEXT(current, len);
2332 continue;
2333 }
2334 break;
2335 }
2336 free(out);
2337
2338 /* get all interface addresses */
2339 in->nlmsg_type = RTM_GETADDR;
2340 if (this->socket->send(this->socket, in, &out, &len) != SUCCESS)
2341 {
2342 return FAILED;
2343 }
2344 current = out;
2345 while (NLMSG_OK(current, len))
2346 {
2347 switch (current->nlmsg_type)
2348 {
2349 case NLMSG_DONE:
2350 break;
2351 case RTM_NEWADDR:
2352 process_addr(this, current, FALSE);
2353 /* fall through */
2354 default:
2355 current = NLMSG_NEXT(current, len);
2356 continue;
2357 }
2358 break;
2359 }
2360 free(out);
2361
2362 this->lock->read_lock(this->lock);
2363 ifaces = this->ifaces->create_enumerator(this->ifaces);
2364 while (ifaces->enumerate(ifaces, &iface))
2365 {
2366 if (iface_entry_up_and_usable(iface))
2367 {
2368 DBG2(DBG_KNL, " %s", iface->ifname);
2369 addrs = iface->addrs->create_enumerator(iface->addrs);
2370 while (addrs->enumerate(addrs, (void**)&addr))
2371 {
2372 DBG2(DBG_KNL, " %H", addr->ip);
2373 }
2374 addrs->destroy(addrs);
2375 }
2376 }
2377 ifaces->destroy(ifaces);
2378 this->lock->unlock(this->lock);
2379 return SUCCESS;
2380 }
2381
2382 /**
2383 * create or delete a rule to use our routing table
2384 */
2385 static status_t manage_rule(private_kernel_netlink_net_t *this, int nlmsg_type,
2386 int family, u_int32_t table, u_int32_t prio)
2387 {
2388 netlink_buf_t request;
2389 struct nlmsghdr *hdr;
2390 struct rtmsg *msg;
2391 chunk_t chunk;
2392 char *fwmark;
2393
2394 memset(&request, 0, sizeof(request));
2395 hdr = &request.hdr;
2396 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2397 hdr->nlmsg_type = nlmsg_type;
2398 if (nlmsg_type == RTM_NEWRULE)
2399 {
2400 hdr->nlmsg_flags |= NLM_F_CREATE | NLM_F_EXCL;
2401 }
2402 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
2403
2404 msg = NLMSG_DATA(hdr);
2405 msg->rtm_table = table;
2406 msg->rtm_family = family;
2407 msg->rtm_protocol = RTPROT_BOOT;
2408 msg->rtm_scope = RT_SCOPE_UNIVERSE;
2409 msg->rtm_type = RTN_UNICAST;
2410
2411 chunk = chunk_from_thing(prio);
2412 netlink_add_attribute(hdr, RTA_PRIORITY, chunk, sizeof(request));
2413
2414 fwmark = lib->settings->get_str(lib->settings,
2415 "%s.plugins.kernel-netlink.fwmark", NULL, lib->ns);
2416 if (fwmark)
2417 {
2418 #ifdef HAVE_LINUX_FIB_RULES_H
2419 mark_t mark;
2420
2421 if (fwmark[0] == '!')
2422 {
2423 msg->rtm_flags |= FIB_RULE_INVERT;
2424 fwmark++;
2425 }
2426 if (mark_from_string(fwmark, &mark))
2427 {
2428 chunk = chunk_from_thing(mark.value);
2429 netlink_add_attribute(hdr, FRA_FWMARK, chunk, sizeof(request));
2430 chunk = chunk_from_thing(mark.mask);
2431 netlink_add_attribute(hdr, FRA_FWMASK, chunk, sizeof(request));
2432 if (msg->rtm_flags & FIB_RULE_INVERT)
2433 {
2434 this->routing_mark = mark;
2435 }
2436 }
2437 #else
2438 DBG1(DBG_KNL, "setting firewall mark on routing rule is not supported");
2439 #endif
2440 }
2441 return this->socket->send_ack(this->socket, hdr);
2442 }
2443
2444 /**
2445 * check for kernel features (currently only via version number)
2446 */
2447 static void check_kernel_features(private_kernel_netlink_net_t *this)
2448 {
2449 struct utsname utsname;
2450 int a, b, c;
2451
2452 if (uname(&utsname) == 0)
2453 {
2454 switch(sscanf(utsname.release, "%d.%d.%d", &a, &b, &c))
2455 {
2456 case 3:
2457 if (a == 2)
2458 {
2459 if (b == 6 && c >= 36)
2460 {
2461 this->rta_mark = TRUE;
2462 }
2463 DBG2(DBG_KNL, "detected Linux %d.%d.%d, no support for "
2464 "RTA_PREFSRC for IPv6 routes", a, b, c);
2465 break;
2466 }
2467 /* fall-through */
2468 case 2:
2469 /* only 3.x+ uses two part version numbers */
2470 this->rta_prefsrc_for_ipv6 = TRUE;
2471 this->rta_mark = TRUE;
2472 break;
2473 default:
2474 break;
2475 }
2476 }
2477 }
2478
2479 /**
2480 * Destroy an address to iface map
2481 */
2482 static void addr_map_destroy(hashtable_t *map)
2483 {
2484 enumerator_t *enumerator;
2485 addr_map_entry_t *addr;
2486
2487 enumerator = map->create_enumerator(map);
2488 while (enumerator->enumerate(enumerator, NULL, (void**)&addr))
2489 {
2490 free(addr);
2491 }
2492 enumerator->destroy(enumerator);
2493 map->destroy(map);
2494 }
2495
2496 METHOD(kernel_net_t, destroy, void,
2497 private_kernel_netlink_net_t *this)
2498 {
2499 enumerator_t *enumerator;
2500 route_entry_t *route;
2501
2502 if (this->routing_table)
2503 {
2504 manage_rule(this, RTM_DELRULE, AF_INET, this->routing_table,
2505 this->routing_table_prio);
2506 manage_rule(this, RTM_DELRULE, AF_INET6, this->routing_table,
2507 this->routing_table_prio);
2508 }
2509 if (this->socket_events > 0)
2510 {
2511 lib->watcher->remove(lib->watcher, this->socket_events);
2512 close(this->socket_events);
2513 }
2514 enumerator = this->routes->create_enumerator(this->routes);
2515 while (enumerator->enumerate(enumerator, NULL, (void**)&route))
2516 {
2517 manage_srcroute(this, RTM_DELROUTE, 0, route->dst_net, route->prefixlen,
2518 route->gateway, route->src_ip, route->if_name);
2519 route_entry_destroy(route);
2520 }
2521 enumerator->destroy(enumerator);
2522 this->routes->destroy(this->routes);
2523 this->routes_lock->destroy(this->routes_lock);
2524 DESTROY_IF(this->socket);
2525
2526 net_changes_clear(this);
2527 this->net_changes->destroy(this->net_changes);
2528 this->net_changes_lock->destroy(this->net_changes_lock);
2529
2530 addr_map_destroy(this->addrs);
2531 addr_map_destroy(this->vips);
2532
2533 this->ifaces->destroy_function(this->ifaces, (void*)iface_entry_destroy);
2534 this->rt_exclude->destroy(this->rt_exclude);
2535 this->roam_lock->destroy(this->roam_lock);
2536 this->condvar->destroy(this->condvar);
2537 this->lock->destroy(this->lock);
2538 free(this);
2539 }
2540
2541 /*
2542 * Described in header.
2543 */
2544 kernel_netlink_net_t *kernel_netlink_net_create()
2545 {
2546 private_kernel_netlink_net_t *this;
2547 enumerator_t *enumerator;
2548 bool register_for_events = TRUE;
2549 char *exclude;
2550
2551 INIT(this,
2552 .public = {
2553 .interface = {
2554 .get_interface = _get_interface_name,
2555 .create_address_enumerator = _create_address_enumerator,
2556 .get_source_addr = _get_source_addr,
2557 .get_nexthop = _get_nexthop,
2558 .add_ip = _add_ip,
2559 .del_ip = _del_ip,
2560 .add_route = _add_route,
2561 .del_route = _del_route,
2562 .destroy = _destroy,
2563 },
2564 },
2565 .socket = netlink_socket_create(NETLINK_ROUTE, rt_msg_names,
2566 lib->settings->get_bool(lib->settings,
2567 "%s.plugins.kernel-netlink.parallel_route", FALSE, lib->ns)),
2568 .rt_exclude = linked_list_create(),
2569 .routes = hashtable_create((hashtable_hash_t)route_entry_hash,
2570 (hashtable_equals_t)route_entry_equals, 16),
2571 .net_changes = hashtable_create(
2572 (hashtable_hash_t)net_change_hash,
2573 (hashtable_equals_t)net_change_equals, 16),
2574 .addrs = hashtable_create(
2575 (hashtable_hash_t)addr_map_entry_hash,
2576 (hashtable_equals_t)addr_map_entry_equals, 16),
2577 .vips = hashtable_create((hashtable_hash_t)addr_map_entry_hash,
2578 (hashtable_equals_t)addr_map_entry_equals, 16),
2579 .routes_lock = mutex_create(MUTEX_TYPE_DEFAULT),
2580 .net_changes_lock = mutex_create(MUTEX_TYPE_DEFAULT),
2581 .ifaces = linked_list_create(),
2582 .lock = rwlock_create(RWLOCK_TYPE_DEFAULT),
2583 .condvar = rwlock_condvar_create(),
2584 .roam_lock = spinlock_create(),
2585 .routing_table = lib->settings->get_int(lib->settings,
2586 "%s.routing_table", ROUTING_TABLE, lib->ns),
2587 .routing_table_prio = lib->settings->get_int(lib->settings,
2588 "%s.routing_table_prio", ROUTING_TABLE_PRIO, lib->ns),
2589 .process_route = lib->settings->get_bool(lib->settings,
2590 "%s.process_route", TRUE, lib->ns),
2591 .install_virtual_ip = lib->settings->get_bool(lib->settings,
2592 "%s.install_virtual_ip", TRUE, lib->ns),
2593 .install_virtual_ip_on = lib->settings->get_str(lib->settings,
2594 "%s.install_virtual_ip_on", NULL, lib->ns),
2595 .prefer_temporary_addrs = lib->settings->get_bool(lib->settings,
2596 "%s.prefer_temporary_addrs", FALSE, lib->ns),
2597 .roam_events = lib->settings->get_bool(lib->settings,
2598 "%s.plugins.kernel-netlink.roam_events", TRUE, lib->ns),
2599 .mtu = lib->settings->get_int(lib->settings,
2600 "%s.plugins.kernel-netlink.mtu", 0, lib->ns),
2601 .mss = lib->settings->get_int(lib->settings,
2602 "%s.plugins.kernel-netlink.mss", 0, lib->ns),
2603 );
2604 timerclear(&this->last_route_reinstall);
2605 timerclear(&this->next_roam);
2606
2607 check_kernel_features(this);
2608
2609 if (streq(lib->ns, "starter"))
2610 { /* starter has no threads, so we do not register for kernel events */
2611 register_for_events = FALSE;
2612 }
2613
2614 exclude = lib->settings->get_str(lib->settings,
2615 "%s.ignore_routing_tables", NULL, lib->ns);
2616 if (exclude)
2617 {
2618 char *token;
2619 uintptr_t table;
2620
2621 enumerator = enumerator_create_token(exclude, " ", " ");
2622 while (enumerator->enumerate(enumerator, &token))
2623 {
2624 errno = 0;
2625 table = strtoul(token, NULL, 10);
2626
2627 if (errno == 0)
2628 {
2629 this->rt_exclude->insert_last(this->rt_exclude, (void*)table);
2630 }
2631 }
2632 enumerator->destroy(enumerator);
2633 }
2634
2635 if (register_for_events)
2636 {
2637 struct sockaddr_nl addr;
2638
2639 memset(&addr, 0, sizeof(addr));
2640 addr.nl_family = AF_NETLINK;
2641
2642 /* create and bind RT socket for events (address/interface/route changes) */
2643 this->socket_events = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
2644 if (this->socket_events < 0)
2645 {
2646 DBG1(DBG_KNL, "unable to create RT event socket");
2647 destroy(this);
2648 return NULL;
2649 }
2650 addr.nl_groups = RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR |
2651 RTMGRP_IPV4_ROUTE | RTMGRP_IPV6_ROUTE | RTMGRP_LINK;
2652 if (bind(this->socket_events, (struct sockaddr*)&addr, sizeof(addr)))
2653 {
2654 DBG1(DBG_KNL, "unable to bind RT event socket");
2655 destroy(this);
2656 return NULL;
2657 }
2658
2659 lib->watcher->add(lib->watcher, this->socket_events, WATCHER_READ,
2660 (watcher_cb_t)receive_events, this);
2661 }
2662
2663 if (init_address_list(this) != SUCCESS)
2664 {
2665 DBG1(DBG_KNL, "unable to get interface list");
2666 destroy(this);
2667 return NULL;
2668 }
2669
2670 if (this->routing_table)
2671 {
2672 if (manage_rule(this, RTM_NEWRULE, AF_INET, this->routing_table,
2673 this->routing_table_prio) != SUCCESS)
2674 {
2675 DBG1(DBG_KNL, "unable to create IPv4 routing table rule");
2676 }
2677 if (manage_rule(this, RTM_NEWRULE, AF_INET6, this->routing_table,
2678 this->routing_table_prio) != SUCCESS)
2679 {
2680 DBG1(DBG_KNL, "unable to create IPv6 routing table rule");
2681 }
2682 }
2683
2684 return &this->public;
2685 }