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