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