Make it easy to check if an address is locally usable via changed get_interface(...
[strongswan.git] / src / libhydra / plugins / kernel_netlink / kernel_netlink_net.c
1 /*
2 * Copyright (C) 2008-2012 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
48 #include "kernel_netlink_net.h"
49 #include "kernel_netlink_shared.h"
50
51 #include <hydra.h>
52 #include <debug.h>
53 #include <threading/thread.h>
54 #include <threading/condvar.h>
55 #include <threading/mutex.h>
56 #include <utils/hashtable.h>
57 #include <utils/linked_list.h>
58 #include <processing/jobs/callback_job.h>
59
60 /** delay before firing roam events (ms) */
61 #define ROAM_DELAY 100
62
63 /** delay before reinstalling routes (ms) */
64 #define ROUTE_DELAY 100
65
66 typedef struct addr_entry_t addr_entry_t;
67
68 /**
69 * IP address in an inface_entry_t
70 */
71 struct addr_entry_t {
72
73 /** The ip address */
74 host_t *ip;
75
76 /** virtual IP managed by us */
77 bool virtual;
78
79 /** scope of the address */
80 u_char scope;
81
82 /** Number of times this IP is used, if virtual */
83 u_int refcount;
84 };
85
86 /**
87 * destroy a addr_entry_t object
88 */
89 static void addr_entry_destroy(addr_entry_t *this)
90 {
91 this->ip->destroy(this->ip);
92 free(this);
93 }
94
95 typedef struct iface_entry_t iface_entry_t;
96
97 /**
98 * A network interface on this system, containing addr_entry_t's
99 */
100 struct iface_entry_t {
101
102 /** interface index */
103 int ifindex;
104
105 /** name of the interface */
106 char ifname[IFNAMSIZ];
107
108 /** interface flags, as in netdevice(7) SIOCGIFFLAGS */
109 u_int flags;
110
111 /** list of addresses as host_t */
112 linked_list_t *addrs;
113 };
114
115 /**
116 * destroy an interface entry
117 */
118 static void iface_entry_destroy(iface_entry_t *this)
119 {
120 this->addrs->destroy_function(this->addrs, (void*)addr_entry_destroy);
121 free(this);
122 }
123
124 typedef struct route_entry_t route_entry_t;
125
126 /**
127 * Installed routing entry
128 */
129 struct route_entry_t {
130 /** Name of the interface the route is bound to */
131 char *if_name;
132
133 /** Source ip of the route */
134 host_t *src_ip;
135
136 /** Gateway for this route */
137 host_t *gateway;
138
139 /** Destination net */
140 chunk_t dst_net;
141
142 /** Destination net prefixlen */
143 u_int8_t prefixlen;
144 };
145
146 /**
147 * Clone a route_entry_t object.
148 */
149 static route_entry_t *route_entry_clone(route_entry_t *this)
150 {
151 route_entry_t *route;
152
153 INIT(route,
154 .if_name = strdup(this->if_name),
155 .src_ip = this->src_ip->clone(this->src_ip),
156 .gateway = this->gateway->clone(this->gateway),
157 .dst_net = chunk_clone(this->dst_net),
158 .prefixlen = this->prefixlen,
159 );
160 return route;
161 }
162
163 /**
164 * Destroy a route_entry_t object
165 */
166 static void route_entry_destroy(route_entry_t *this)
167 {
168 free(this->if_name);
169 DESTROY_IF(this->src_ip);
170 DESTROY_IF(this->gateway);
171 chunk_free(&this->dst_net);
172 free(this);
173 }
174
175 /**
176 * Hash a route_entry_t object
177 */
178 static u_int route_entry_hash(route_entry_t *this)
179 {
180 return chunk_hash_inc(chunk_from_thing(this->prefixlen),
181 chunk_hash(this->dst_net));
182 }
183
184 /**
185 * Compare two route_entry_t objects
186 */
187 static bool route_entry_equals(route_entry_t *a, route_entry_t *b)
188 {
189 return a->if_name && b->if_name && streq(a->if_name, b->if_name) &&
190 a->src_ip->ip_equals(a->src_ip, b->src_ip) &&
191 a->gateway->ip_equals(a->gateway, b->gateway) &&
192 chunk_equals(a->dst_net, b->dst_net) && a->prefixlen == b->prefixlen;
193 }
194
195 typedef struct net_change_t net_change_t;
196
197 /**
198 * Queued network changes
199 */
200 struct net_change_t {
201 /** Name of the interface that got activated (or an IP appeared on) */
202 char *if_name;
203 };
204
205 /**
206 * Destroy a net_change_t object
207 */
208 static void net_change_destroy(net_change_t *this)
209 {
210 free(this->if_name);
211 free(this);
212 }
213
214 /**
215 * Hash a net_change_t object
216 */
217 static u_int net_change_hash(net_change_t *this)
218 {
219 return chunk_hash(chunk_create(this->if_name, strlen(this->if_name)));
220 }
221
222 /**
223 * Compare two net_change_t objects
224 */
225 static bool net_change_equals(net_change_t *a, net_change_t *b)
226 {
227 return streq(a->if_name, b->if_name);
228 }
229
230 typedef struct private_kernel_netlink_net_t private_kernel_netlink_net_t;
231
232 /**
233 * Private variables and functions of kernel_netlink_net class.
234 */
235 struct private_kernel_netlink_net_t {
236 /**
237 * Public part of the kernel_netlink_net_t object.
238 */
239 kernel_netlink_net_t public;
240
241 /**
242 * mutex to lock access to various lists
243 */
244 mutex_t *mutex;
245
246 /**
247 * condition variable to signal virtual IP add/removal
248 */
249 condvar_t *condvar;
250
251 /**
252 * Cached list of interfaces and its addresses (iface_entry_t)
253 */
254 linked_list_t *ifaces;
255
256 /**
257 * netlink rt socket (routing)
258 */
259 netlink_socket_t *socket;
260
261 /**
262 * Netlink rt socket to receive address change events
263 */
264 int socket_events;
265
266 /**
267 * time of the last roam event
268 */
269 timeval_t last_roam;
270
271 /**
272 * routing table to install routes
273 */
274 int routing_table;
275
276 /**
277 * priority of used routing table
278 */
279 int routing_table_prio;
280
281 /**
282 * installed routes
283 */
284 hashtable_t *routes;
285
286 /**
287 * interface changes which may trigger route reinstallation
288 */
289 hashtable_t *net_changes;
290
291 /**
292 * mutex for route reinstallation triggers
293 */
294 mutex_t *net_changes_lock;
295
296 /**
297 * time of last route reinstallation
298 */
299 timeval_t last_route_reinstall;
300
301 /**
302 * whether to react to RTM_NEWROUTE or RTM_DELROUTE events
303 */
304 bool process_route;
305
306 /**
307 * whether to actually install virtual IPs
308 */
309 bool install_virtual_ip;
310
311 /**
312 * whether preferred source addresses can be specified for IPv6 routes
313 */
314 bool rta_prefsrc_for_ipv6;
315
316 /**
317 * list with routing tables to be excluded from route lookup
318 */
319 linked_list_t *rt_exclude;
320 };
321
322 /**
323 * Forward declaration
324 */
325 static status_t manage_srcroute(private_kernel_netlink_net_t *this,
326 int nlmsg_type, int flags, chunk_t dst_net,
327 u_int8_t prefixlen, host_t *gateway,
328 host_t *src_ip, char *if_name);
329
330 /**
331 * Clear the queued network changes.
332 */
333 static void net_changes_clear(private_kernel_netlink_net_t *this)
334 {
335 enumerator_t *enumerator;
336 net_change_t *change;
337
338 enumerator = this->net_changes->create_enumerator(this->net_changes);
339 while (enumerator->enumerate(enumerator, NULL, (void**)&change))
340 {
341 this->net_changes->remove_at(this->net_changes, enumerator);
342 net_change_destroy(change);
343 }
344 enumerator->destroy(enumerator);
345 }
346
347 /**
348 * Act upon queued network changes.
349 */
350 static job_requeue_t reinstall_routes(private_kernel_netlink_net_t *this)
351 {
352 enumerator_t *enumerator;
353 route_entry_t *route;
354
355 this->net_changes_lock->lock(this->net_changes_lock);
356 this->mutex->lock(this->mutex);
357
358 enumerator = this->routes->create_enumerator(this->routes);
359 while (enumerator->enumerate(enumerator, NULL, (void**)&route))
360 {
361 net_change_t *change, lookup = {
362 .if_name = route->if_name,
363 };
364 /* check if a change for the outgoing interface is queued */
365 change = this->net_changes->get(this->net_changes, &lookup);
366 if (!change)
367 { /* in case src_ip is not on the outgoing interface */
368 if (this->public.interface.get_interface(&this->public.interface,
369 route->src_ip, &lookup.if_name))
370 {
371 if (!streq(lookup.if_name, route->if_name))
372 {
373 change = this->net_changes->get(this->net_changes, &lookup);
374 }
375 free(lookup.if_name);
376 }
377 }
378 if (change)
379 {
380 manage_srcroute(this, RTM_NEWROUTE, NLM_F_CREATE | NLM_F_EXCL,
381 route->dst_net, route->prefixlen, route->gateway,
382 route->src_ip, route->if_name);
383 }
384 }
385 enumerator->destroy(enumerator);
386 this->mutex->unlock(this->mutex);
387
388 net_changes_clear(this);
389 this->net_changes_lock->unlock(this->net_changes_lock);
390 return JOB_REQUEUE_NONE;
391 }
392
393 /**
394 * Queue route reinstallation caused by network changes for a given interface.
395 *
396 * The route reinstallation is delayed for a while and only done once for
397 * several calls during this delay, in order to avoid doing it too often.
398 * The interface name is freed.
399 */
400 static void queue_route_reinstall(private_kernel_netlink_net_t *this,
401 char *if_name)
402 {
403 net_change_t *update, *found;
404 timeval_t now;
405 job_t *job;
406
407 INIT(update,
408 .if_name = if_name
409 );
410
411 this->net_changes_lock->lock(this->net_changes_lock);
412 found = this->net_changes->put(this->net_changes, update, update);
413 if (found)
414 {
415 net_change_destroy(found);
416 }
417 time_monotonic(&now);
418 if (timercmp(&now, &this->last_route_reinstall, >))
419 {
420 now.tv_usec += ROUTE_DELAY * 1000;
421 while (now.tv_usec > 1000000)
422 {
423 now.tv_sec++;
424 now.tv_usec -= 1000000;
425 }
426 this->last_route_reinstall = now;
427
428 job = (job_t*)callback_job_create((callback_job_cb_t)reinstall_routes,
429 this, NULL, NULL);
430 lib->scheduler->schedule_job_ms(lib->scheduler, job, ROUTE_DELAY);
431 }
432 this->net_changes_lock->unlock(this->net_changes_lock);
433 }
434
435 /**
436 * get the refcount of a virtual ip
437 */
438 static int get_vip_refcount(private_kernel_netlink_net_t *this, host_t* ip)
439 {
440 enumerator_t *ifaces, *addrs;
441 iface_entry_t *iface;
442 addr_entry_t *addr;
443 int refcount = 0;
444
445 ifaces = this->ifaces->create_enumerator(this->ifaces);
446 while (ifaces->enumerate(ifaces, (void**)&iface))
447 {
448 addrs = iface->addrs->create_enumerator(iface->addrs);
449 while (addrs->enumerate(addrs, (void**)&addr))
450 {
451 if (addr->virtual && (iface->flags & IFF_UP) &&
452 ip->ip_equals(ip, addr->ip))
453 {
454 refcount = addr->refcount;
455 break;
456 }
457 }
458 addrs->destroy(addrs);
459 if (refcount)
460 {
461 break;
462 }
463 }
464 ifaces->destroy(ifaces);
465
466 return refcount;
467 }
468
469 /**
470 * get the first non-virtual ip address on the given interface.
471 * if a candidate address is given, we first search for that address and if not
472 * found return the address as above.
473 * returned host is a clone, has to be freed by caller.
474 */
475 static host_t *get_interface_address(private_kernel_netlink_net_t *this,
476 int ifindex, int family, host_t *candidate)
477 {
478 enumerator_t *ifaces, *addrs;
479 iface_entry_t *iface;
480 addr_entry_t *addr;
481 host_t *ip = NULL;
482
483 this->mutex->lock(this->mutex);
484 ifaces = this->ifaces->create_enumerator(this->ifaces);
485 while (ifaces->enumerate(ifaces, &iface))
486 {
487 if (iface->ifindex == ifindex)
488 {
489 addrs = iface->addrs->create_enumerator(iface->addrs);
490 while (addrs->enumerate(addrs, &addr))
491 {
492 if (addr->virtual)
493 {
494 continue;
495 }
496 if (addr->ip->get_family(addr->ip) == family)
497 {
498 if (!candidate || candidate->ip_equals(candidate, addr->ip))
499 { /* stop at the first address if we don't search for a
500 * candidate or if the candidate matches */
501 ip = addr->ip;
502 break;
503 }
504 else if (!ip)
505 { /* store the first address as fallback if candidate is
506 * not found */
507 ip = addr->ip;
508 }
509 }
510 }
511 addrs->destroy(addrs);
512 break;
513 }
514 }
515 ifaces->destroy(ifaces);
516 if (ip)
517 {
518 ip = ip->clone(ip);
519 }
520 this->mutex->unlock(this->mutex);
521 return ip;
522 }
523
524 /**
525 * callback function that raises the delayed roam event
526 */
527 static job_requeue_t roam_event(uintptr_t address)
528 {
529 hydra->kernel_interface->roam(hydra->kernel_interface, address != 0);
530 return JOB_REQUEUE_NONE;
531 }
532
533 /**
534 * fire a roaming event. we delay it for a bit and fire only one event
535 * for multiple calls. otherwise we would create too many events.
536 */
537 static void fire_roam_event(private_kernel_netlink_net_t *this, bool address)
538 {
539 timeval_t now;
540 job_t *job;
541
542 time_monotonic(&now);
543 if (timercmp(&now, &this->last_roam, >))
544 {
545 now.tv_usec += ROAM_DELAY * 1000;
546 while (now.tv_usec > 1000000)
547 {
548 now.tv_sec++;
549 now.tv_usec -= 1000000;
550 }
551 this->last_roam = now;
552
553 job = (job_t*)callback_job_create((callback_job_cb_t)roam_event,
554 (void*)(uintptr_t)(address ? 1 : 0),
555 NULL, NULL);
556 lib->scheduler->schedule_job_ms(lib->scheduler, job, ROAM_DELAY);
557 }
558 }
559
560 /**
561 * process RTM_NEWLINK/RTM_DELLINK from kernel
562 */
563 static void process_link(private_kernel_netlink_net_t *this,
564 struct nlmsghdr *hdr, bool event)
565 {
566 struct ifinfomsg* msg = (struct ifinfomsg*)(NLMSG_DATA(hdr));
567 struct rtattr *rta = IFLA_RTA(msg);
568 size_t rtasize = IFLA_PAYLOAD (hdr);
569 enumerator_t *enumerator;
570 iface_entry_t *current, *entry = NULL;
571 char *name = NULL;
572 bool update = FALSE, update_routes = FALSE;
573
574 while (RTA_OK(rta, rtasize))
575 {
576 switch (rta->rta_type)
577 {
578 case IFLA_IFNAME:
579 name = RTA_DATA(rta);
580 break;
581 }
582 rta = RTA_NEXT(rta, rtasize);
583 }
584 if (!name)
585 {
586 name = "(unknown)";
587 }
588
589 this->mutex->lock(this->mutex);
590 switch (hdr->nlmsg_type)
591 {
592 case RTM_NEWLINK:
593 {
594 enumerator = this->ifaces->create_enumerator(this->ifaces);
595 while (enumerator->enumerate(enumerator, &current))
596 {
597 if (current->ifindex == msg->ifi_index)
598 {
599 entry = current;
600 break;
601 }
602 }
603 enumerator->destroy(enumerator);
604 if (!entry)
605 {
606 entry = malloc_thing(iface_entry_t);
607 entry->ifindex = msg->ifi_index;
608 entry->flags = 0;
609 entry->addrs = linked_list_create();
610 this->ifaces->insert_last(this->ifaces, entry);
611 }
612 strncpy(entry->ifname, name, IFNAMSIZ);
613 entry->ifname[IFNAMSIZ-1] = '\0';
614 if (event)
615 {
616 if (!(entry->flags & IFF_UP) && (msg->ifi_flags & IFF_UP))
617 {
618 update = update_routes = TRUE;
619 DBG1(DBG_KNL, "interface %s activated", name);
620 }
621 if ((entry->flags & IFF_UP) && !(msg->ifi_flags & IFF_UP))
622 {
623 update = TRUE;
624 DBG1(DBG_KNL, "interface %s deactivated", name);
625 }
626 }
627 entry->flags = msg->ifi_flags;
628 break;
629 }
630 case RTM_DELLINK:
631 {
632 enumerator = this->ifaces->create_enumerator(this->ifaces);
633 while (enumerator->enumerate(enumerator, &current))
634 {
635 if (current->ifindex == msg->ifi_index)
636 {
637 if (event)
638 {
639 update = TRUE;
640 DBG1(DBG_KNL, "interface %s deleted", current->ifname);
641 }
642 this->ifaces->remove_at(this->ifaces, enumerator);
643 iface_entry_destroy(current);
644 break;
645 }
646 }
647 enumerator->destroy(enumerator);
648 break;
649 }
650 }
651 this->mutex->unlock(this->mutex);
652
653 if (update_routes && event)
654 {
655 queue_route_reinstall(this, strdup(name));
656 }
657
658 /* send an update to all IKE_SAs */
659 if (update && event)
660 {
661 fire_roam_event(this, TRUE);
662 }
663 }
664
665 /**
666 * process RTM_NEWADDR/RTM_DELADDR from kernel
667 */
668 static void process_addr(private_kernel_netlink_net_t *this,
669 struct nlmsghdr *hdr, bool event)
670 {
671 struct ifaddrmsg* msg = (struct ifaddrmsg*)(NLMSG_DATA(hdr));
672 struct rtattr *rta = IFA_RTA(msg);
673 size_t rtasize = IFA_PAYLOAD (hdr);
674 host_t *host = NULL;
675 enumerator_t *ifaces, *addrs;
676 iface_entry_t *iface;
677 addr_entry_t *addr;
678 chunk_t local = chunk_empty, address = chunk_empty;
679 char *route_ifname = NULL;
680 bool update = FALSE, found = FALSE, changed = FALSE;
681
682 while (RTA_OK(rta, rtasize))
683 {
684 switch (rta->rta_type)
685 {
686 case IFA_LOCAL:
687 local.ptr = RTA_DATA(rta);
688 local.len = RTA_PAYLOAD(rta);
689 break;
690 case IFA_ADDRESS:
691 address.ptr = RTA_DATA(rta);
692 address.len = RTA_PAYLOAD(rta);
693 break;
694 }
695 rta = RTA_NEXT(rta, rtasize);
696 }
697
698 /* For PPP interfaces, we need the IFA_LOCAL address,
699 * IFA_ADDRESS is the peers address. But IFA_LOCAL is
700 * not included in all cases (IPv6?), so fallback to IFA_ADDRESS. */
701 if (local.ptr)
702 {
703 host = host_create_from_chunk(msg->ifa_family, local, 0);
704 }
705 else if (address.ptr)
706 {
707 host = host_create_from_chunk(msg->ifa_family, address, 0);
708 }
709
710 if (host == NULL)
711 { /* bad family? */
712 return;
713 }
714
715 this->mutex->lock(this->mutex);
716 ifaces = this->ifaces->create_enumerator(this->ifaces);
717 while (ifaces->enumerate(ifaces, &iface))
718 {
719 if (iface->ifindex == msg->ifa_index)
720 {
721 addrs = iface->addrs->create_enumerator(iface->addrs);
722 while (addrs->enumerate(addrs, &addr))
723 {
724 if (host->ip_equals(host, addr->ip))
725 {
726 found = TRUE;
727 if (hdr->nlmsg_type == RTM_DELADDR)
728 {
729 iface->addrs->remove_at(iface->addrs, addrs);
730 if (!addr->virtual)
731 {
732 changed = TRUE;
733 DBG1(DBG_KNL, "%H disappeared from %s",
734 host, iface->ifname);
735 }
736 addr_entry_destroy(addr);
737 }
738 else if (hdr->nlmsg_type == RTM_NEWADDR && addr->virtual)
739 {
740 addr->refcount = 1;
741 }
742 }
743 }
744 addrs->destroy(addrs);
745
746 if (hdr->nlmsg_type == RTM_NEWADDR)
747 {
748 if (!found)
749 {
750 found = TRUE;
751 changed = TRUE;
752 route_ifname = strdup(iface->ifname);
753 addr = malloc_thing(addr_entry_t);
754 addr->ip = host->clone(host);
755 addr->virtual = FALSE;
756 addr->refcount = 1;
757 addr->scope = msg->ifa_scope;
758
759 iface->addrs->insert_last(iface->addrs, addr);
760 if (event)
761 {
762 DBG1(DBG_KNL, "%H appeared on %s", host, iface->ifname);
763 }
764 }
765 }
766 if (found && (iface->flags & IFF_UP))
767 {
768 update = TRUE;
769 }
770 break;
771 }
772 }
773 ifaces->destroy(ifaces);
774 this->mutex->unlock(this->mutex);
775
776 if (update && event && route_ifname)
777 {
778 queue_route_reinstall(this, route_ifname);
779 }
780 else
781 {
782 free(route_ifname);
783 }
784 host->destroy(host);
785
786 /* send an update to all IKE_SAs */
787 if (update && event && changed)
788 {
789 fire_roam_event(this, TRUE);
790 }
791 }
792
793 /**
794 * process RTM_NEWROUTE and RTM_DELROUTE from kernel
795 */
796 static void process_route(private_kernel_netlink_net_t *this, struct nlmsghdr *hdr)
797 {
798 struct rtmsg* msg = (struct rtmsg*)(NLMSG_DATA(hdr));
799 struct rtattr *rta = RTM_RTA(msg);
800 size_t rtasize = RTM_PAYLOAD(hdr);
801 u_int32_t rta_oif = 0;
802 host_t *host = NULL;
803
804 /* ignore routes added by us or in the local routing table (local addrs) */
805 if (msg->rtm_table && (msg->rtm_table == this->routing_table ||
806 msg->rtm_table == RT_TABLE_LOCAL))
807 {
808 return;
809 }
810 else if (msg->rtm_flags & RTM_F_CLONED)
811 { /* ignore cached routes, seem to be created a lot for IPv6 */
812 return;
813 }
814
815 while (RTA_OK(rta, rtasize))
816 {
817 switch (rta->rta_type)
818 {
819 case RTA_PREFSRC:
820 DESTROY_IF(host);
821 host = host_create_from_chunk(msg->rtm_family,
822 chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta)), 0);
823 break;
824 case RTA_OIF:
825 if (RTA_PAYLOAD(rta) == sizeof(rta_oif))
826 {
827 rta_oif = *(u_int32_t*)RTA_DATA(rta);
828 }
829 break;
830 }
831 rta = RTA_NEXT(rta, rtasize);
832 }
833 if (!host && rta_oif)
834 {
835 host = get_interface_address(this, rta_oif, msg->rtm_family, NULL);
836 }
837 if (host)
838 {
839 this->mutex->lock(this->mutex);
840 if (!get_vip_refcount(this, host))
841 { /* ignore routes added for virtual IPs */
842 fire_roam_event(this, FALSE);
843 }
844 this->mutex->unlock(this->mutex);
845 host->destroy(host);
846 }
847 }
848
849 /**
850 * Receives events from kernel
851 */
852 static job_requeue_t receive_events(private_kernel_netlink_net_t *this)
853 {
854 char response[1024];
855 struct nlmsghdr *hdr = (struct nlmsghdr*)response;
856 struct sockaddr_nl addr;
857 socklen_t addr_len = sizeof(addr);
858 int len;
859 bool oldstate;
860
861 oldstate = thread_cancelability(TRUE);
862 len = recvfrom(this->socket_events, response, sizeof(response), 0,
863 (struct sockaddr*)&addr, &addr_len);
864 thread_cancelability(oldstate);
865
866 if (len < 0)
867 {
868 switch (errno)
869 {
870 case EINTR:
871 /* interrupted, try again */
872 return JOB_REQUEUE_DIRECT;
873 case EAGAIN:
874 /* no data ready, select again */
875 return JOB_REQUEUE_DIRECT;
876 default:
877 DBG1(DBG_KNL, "unable to receive from rt event socket");
878 sleep(1);
879 return JOB_REQUEUE_FAIR;
880 }
881 }
882
883 if (addr.nl_pid != 0)
884 { /* not from kernel. not interested, try another one */
885 return JOB_REQUEUE_DIRECT;
886 }
887
888 while (NLMSG_OK(hdr, len))
889 {
890 /* looks good so far, dispatch netlink message */
891 switch (hdr->nlmsg_type)
892 {
893 case RTM_NEWADDR:
894 case RTM_DELADDR:
895 process_addr(this, hdr, TRUE);
896 this->condvar->broadcast(this->condvar);
897 break;
898 case RTM_NEWLINK:
899 case RTM_DELLINK:
900 process_link(this, hdr, TRUE);
901 this->condvar->broadcast(this->condvar);
902 break;
903 case RTM_NEWROUTE:
904 case RTM_DELROUTE:
905 if (this->process_route)
906 {
907 process_route(this, hdr);
908 }
909 break;
910 default:
911 break;
912 }
913 hdr = NLMSG_NEXT(hdr, len);
914 }
915 return JOB_REQUEUE_DIRECT;
916 }
917
918 /** enumerator over addresses */
919 typedef struct {
920 private_kernel_netlink_net_t* this;
921 /** whether to enumerate down interfaces */
922 bool include_down_ifaces;
923 /** whether to enumerate virtual ip addresses */
924 bool include_virtual_ips;
925 /** whether to enumerate loopback interfaces */
926 bool include_loopback;
927 } address_enumerator_t;
928
929 /**
930 * cleanup function for address enumerator
931 */
932 static void address_enumerator_destroy(address_enumerator_t *data)
933 {
934 data->this->mutex->unlock(data->this->mutex);
935 free(data);
936 }
937
938 /**
939 * filter for addresses
940 */
941 static bool filter_addresses(address_enumerator_t *data,
942 addr_entry_t** in, host_t** out)
943 {
944 if (!data->include_virtual_ips && (*in)->virtual)
945 { /* skip virtual interfaces added by us */
946 return FALSE;
947 }
948 if ((*in)->scope >= RT_SCOPE_LINK)
949 { /* skip addresses with a unusable scope */
950 return FALSE;
951 }
952 *out = (*in)->ip;
953 return TRUE;
954 }
955
956 /**
957 * enumerator constructor for interfaces
958 */
959 static enumerator_t *create_iface_enumerator(iface_entry_t *iface,
960 address_enumerator_t *data)
961 {
962 return enumerator_create_filter(
963 iface->addrs->create_enumerator(iface->addrs),
964 (void*)filter_addresses, data, NULL);
965 }
966
967 /**
968 * filter for interfaces
969 */
970 static bool filter_interfaces(address_enumerator_t *data, iface_entry_t** in,
971 iface_entry_t** out)
972 {
973 if (!data->include_loopback && ((*in)->flags & IFF_LOOPBACK))
974 { /* ignore loopback devices */
975 return FALSE;
976 }
977 if (!data->include_down_ifaces && !((*in)->flags & IFF_UP))
978 { /* skip interfaces not up */
979 return FALSE;
980 }
981 *out = *in;
982 return TRUE;
983 }
984
985 METHOD(kernel_net_t, create_address_enumerator, enumerator_t*,
986 private_kernel_netlink_net_t *this,
987 bool include_down_ifaces, bool include_virtual_ips, bool include_loopback)
988 {
989 address_enumerator_t *data = malloc_thing(address_enumerator_t);
990 data->this = this;
991 data->include_down_ifaces = include_down_ifaces;
992 data->include_virtual_ips = include_virtual_ips;
993 data->include_loopback = include_loopback;
994
995 this->mutex->lock(this->mutex);
996 return enumerator_create_nested(
997 enumerator_create_filter(
998 this->ifaces->create_enumerator(this->ifaces),
999 (void*)filter_interfaces, data, NULL),
1000 (void*)create_iface_enumerator, data,
1001 (void*)address_enumerator_destroy);
1002 }
1003
1004 METHOD(kernel_net_t, get_interface_name, bool,
1005 private_kernel_netlink_net_t *this, host_t* ip, char **name)
1006 {
1007 enumerator_t *ifaces, *addrs;
1008 iface_entry_t *iface;
1009 addr_entry_t *addr;
1010 bool found = FALSE;
1011
1012 this->mutex->lock(this->mutex);
1013 ifaces = this->ifaces->create_enumerator(this->ifaces);
1014 while (ifaces->enumerate(ifaces, &iface))
1015 {
1016 addrs = iface->addrs->create_enumerator(iface->addrs);
1017 while (addrs->enumerate(addrs, &addr))
1018 {
1019 if (ip->ip_equals(ip, addr->ip))
1020 {
1021 found = TRUE;
1022 if (name)
1023 {
1024 *name = strdup(iface->ifname);
1025 }
1026 break;
1027 }
1028 }
1029 addrs->destroy(addrs);
1030 if (found)
1031 {
1032 break;
1033 }
1034 }
1035 ifaces->destroy(ifaces);
1036 this->mutex->unlock(this->mutex);
1037
1038 if (!found)
1039 {
1040 DBG2(DBG_KNL, "%H is not a local address", ip);
1041 }
1042 else if (name)
1043 {
1044 DBG2(DBG_KNL, "%H is on interface %s", ip, *name);
1045 }
1046 return found;
1047 }
1048
1049 /**
1050 * get the index of an interface by name
1051 */
1052 static int get_interface_index(private_kernel_netlink_net_t *this, char* name)
1053 {
1054 enumerator_t *ifaces;
1055 iface_entry_t *iface;
1056 int ifindex = 0;
1057
1058 DBG2(DBG_KNL, "getting iface index for %s", name);
1059
1060 this->mutex->lock(this->mutex);
1061 ifaces = this->ifaces->create_enumerator(this->ifaces);
1062 while (ifaces->enumerate(ifaces, &iface))
1063 {
1064 if (streq(name, iface->ifname))
1065 {
1066 ifindex = iface->ifindex;
1067 break;
1068 }
1069 }
1070 ifaces->destroy(ifaces);
1071 this->mutex->unlock(this->mutex);
1072
1073 if (ifindex == 0)
1074 {
1075 DBG1(DBG_KNL, "unable to get interface index for %s", name);
1076 }
1077 return ifindex;
1078 }
1079
1080 /**
1081 * Check if an interface with a given index is up
1082 */
1083 static bool is_interface_up(private_kernel_netlink_net_t *this, int index)
1084 {
1085 enumerator_t *ifaces;
1086 iface_entry_t *iface;
1087 /* default to TRUE for interface we do not monitor (e.g. lo) */
1088 bool up = TRUE;
1089
1090 ifaces = this->ifaces->create_enumerator(this->ifaces);
1091 while (ifaces->enumerate(ifaces, &iface))
1092 {
1093 if (iface->ifindex == index)
1094 {
1095 up = iface->flags & IFF_UP;
1096 break;
1097 }
1098 }
1099 ifaces->destroy(ifaces);
1100 return up;
1101 }
1102
1103 /**
1104 * check if an address (chunk) addr is in subnet (net with net_len net bits)
1105 */
1106 static bool addr_in_subnet(chunk_t addr, chunk_t net, int net_len)
1107 {
1108 static const u_char mask[] = { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
1109 int byte = 0;
1110
1111 if (net_len == 0)
1112 { /* any address matches a /0 network */
1113 return TRUE;
1114 }
1115 if (addr.len != net.len || net_len > 8 * net.len )
1116 {
1117 return FALSE;
1118 }
1119 /* scan through all bytes in network order */
1120 while (net_len > 0)
1121 {
1122 if (net_len < 8)
1123 {
1124 return (mask[net_len] & addr.ptr[byte]) == (mask[net_len] & net.ptr[byte]);
1125 }
1126 else
1127 {
1128 if (addr.ptr[byte] != net.ptr[byte])
1129 {
1130 return FALSE;
1131 }
1132 byte++;
1133 net_len -= 8;
1134 }
1135 }
1136 return TRUE;
1137 }
1138
1139 /**
1140 * Store information about a route retrieved via RTNETLINK
1141 */
1142 typedef struct {
1143 chunk_t gtw;
1144 chunk_t src;
1145 chunk_t dst;
1146 host_t *src_host;
1147 u_int8_t dst_len;
1148 u_int32_t table;
1149 u_int32_t oif;
1150 } rt_entry_t;
1151
1152 /**
1153 * Free a route entry
1154 */
1155 static void rt_entry_destroy(rt_entry_t *this)
1156 {
1157 DESTROY_IF(this->src_host);
1158 free(this);
1159 }
1160
1161 /**
1162 * Parse route received with RTM_NEWROUTE. The given rt_entry_t object will be
1163 * reused if not NULL.
1164 *
1165 * Returned chunks point to internal data of the Netlink message.
1166 */
1167 static rt_entry_t *parse_route(struct nlmsghdr *hdr, rt_entry_t *route)
1168 {
1169 struct rtattr *rta;
1170 struct rtmsg *msg;
1171 size_t rtasize;
1172
1173 msg = (struct rtmsg*)(NLMSG_DATA(hdr));
1174 rta = RTM_RTA(msg);
1175 rtasize = RTM_PAYLOAD(hdr);
1176
1177 if (route)
1178 {
1179 route->gtw = chunk_empty;
1180 route->src = chunk_empty;
1181 route->dst = chunk_empty;
1182 route->dst_len = msg->rtm_dst_len;
1183 route->table = msg->rtm_table;
1184 route->oif = 0;
1185 }
1186 else
1187 {
1188 INIT(route,
1189 .dst_len = msg->rtm_dst_len,
1190 .table = msg->rtm_table,
1191 );
1192 }
1193
1194 while (RTA_OK(rta, rtasize))
1195 {
1196 switch (rta->rta_type)
1197 {
1198 case RTA_PREFSRC:
1199 route->src = chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta));
1200 break;
1201 case RTA_GATEWAY:
1202 route->gtw = chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta));
1203 break;
1204 case RTA_DST:
1205 route->dst = chunk_create(RTA_DATA(rta), RTA_PAYLOAD(rta));
1206 break;
1207 case RTA_OIF:
1208 if (RTA_PAYLOAD(rta) == sizeof(route->oif))
1209 {
1210 route->oif = *(u_int32_t*)RTA_DATA(rta);
1211 }
1212 break;
1213 #ifdef HAVE_RTA_TABLE
1214 case RTA_TABLE:
1215 if (RTA_PAYLOAD(rta) == sizeof(route->table))
1216 {
1217 route->table = *(u_int32_t*)RTA_DATA(rta);
1218 }
1219 break;
1220 #endif /* HAVE_RTA_TABLE*/
1221 }
1222 rta = RTA_NEXT(rta, rtasize);
1223 }
1224 return route;
1225 }
1226
1227 /**
1228 * Get a route: If "nexthop", the nexthop is returned. source addr otherwise.
1229 */
1230 static host_t *get_route(private_kernel_netlink_net_t *this, host_t *dest,
1231 bool nexthop, host_t *candidate)
1232 {
1233 netlink_buf_t request;
1234 struct nlmsghdr *hdr, *out, *current;
1235 struct rtmsg *msg;
1236 chunk_t chunk;
1237 size_t len;
1238 linked_list_t *routes;
1239 rt_entry_t *route = NULL, *best = NULL;
1240 enumerator_t *enumerator;
1241 host_t *addr = NULL;
1242
1243 memset(&request, 0, sizeof(request));
1244
1245 hdr = (struct nlmsghdr*)request;
1246 hdr->nlmsg_flags = NLM_F_REQUEST;
1247 if (dest->get_family(dest) == AF_INET || this->rta_prefsrc_for_ipv6 ||
1248 this->routing_table)
1249 { /* kernels prior to 3.0 do not support RTA_PREFSRC for IPv6 routes.
1250 * as we want to ignore routes with virtual IPs we cannot use DUMP
1251 * if these routes are not installed in a separate table */
1252 hdr->nlmsg_flags |= NLM_F_DUMP;
1253 }
1254 hdr->nlmsg_type = RTM_GETROUTE;
1255 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
1256
1257 msg = (struct rtmsg*)NLMSG_DATA(hdr);
1258 msg->rtm_family = dest->get_family(dest);
1259 if (candidate)
1260 {
1261 chunk = candidate->get_address(candidate);
1262 netlink_add_attribute(hdr, RTA_PREFSRC, chunk, sizeof(request));
1263 }
1264 chunk = dest->get_address(dest);
1265 netlink_add_attribute(hdr, RTA_DST, chunk, sizeof(request));
1266
1267 if (this->socket->send(this->socket, hdr, &out, &len) != SUCCESS)
1268 {
1269 DBG2(DBG_KNL, "getting %s to reach %H failed",
1270 nexthop ? "nexthop" : "address", dest);
1271 return NULL;
1272 }
1273 routes = linked_list_create();
1274 this->mutex->lock(this->mutex);
1275
1276 for (current = out; NLMSG_OK(current, len);
1277 current = NLMSG_NEXT(current, len))
1278 {
1279 switch (current->nlmsg_type)
1280 {
1281 case NLMSG_DONE:
1282 break;
1283 case RTM_NEWROUTE:
1284 {
1285 rt_entry_t *other;
1286 uintptr_t table;
1287
1288 route = parse_route(current, route);
1289
1290 table = (uintptr_t)route->table;
1291 if (this->rt_exclude->find_first(this->rt_exclude, NULL,
1292 (void**)&table) == SUCCESS)
1293 { /* route is from an excluded routing table */
1294 continue;
1295 }
1296 if (this->routing_table != 0 &&
1297 route->table == this->routing_table)
1298 { /* route is from our own ipsec routing table */
1299 continue;
1300 }
1301 if (route->oif && !is_interface_up(this, route->oif))
1302 { /* interface is down */
1303 continue;
1304 }
1305 if (!addr_in_subnet(chunk, route->dst, route->dst_len))
1306 { /* route destination does not contain dest */
1307 continue;
1308 }
1309 if (route->src.ptr)
1310 { /* verify source address, if any */
1311 host_t *src = host_create_from_chunk(msg->rtm_family,
1312 route->src, 0);
1313 if (src && get_vip_refcount(this, src))
1314 { /* ignore routes installed by us */
1315 src->destroy(src);
1316 continue;
1317 }
1318 route->src_host = src;
1319 }
1320 /* insert route, sorted by decreasing network prefix */
1321 enumerator = routes->create_enumerator(routes);
1322 while (enumerator->enumerate(enumerator, &other))
1323 {
1324 if (route->dst_len > other->dst_len)
1325 {
1326 break;
1327 }
1328 }
1329 routes->insert_before(routes, enumerator, route);
1330 enumerator->destroy(enumerator);
1331 route = NULL;
1332 continue;
1333 }
1334 default:
1335 continue;
1336 }
1337 break;
1338 }
1339 if (route)
1340 {
1341 rt_entry_destroy(route);
1342 }
1343
1344 /* now we have a list of routes matching dest, sorted by net prefix.
1345 * we will look for source addresses for these routes and select the one
1346 * with the preferred source address, if possible */
1347 enumerator = routes->create_enumerator(routes);
1348 while (enumerator->enumerate(enumerator, &route))
1349 {
1350 if (route->src_host)
1351 { /* got a source address with the route, if no preferred source
1352 * is given or it matches we are done, as this is the best route */
1353 if (!candidate || candidate->ip_equals(candidate, route->src_host))
1354 {
1355 best = route;
1356 break;
1357 }
1358 else if (route->oif)
1359 { /* no match yet, maybe it is assigned to the same interface */
1360 host_t *src = get_interface_address(this, route->oif,
1361 msg->rtm_family, candidate);
1362 if (src && src->ip_equals(src, candidate))
1363 {
1364 route->src_host->destroy(route->src_host);
1365 route->src_host = src;
1366 best = route;
1367 break;
1368 }
1369 DESTROY_IF(src);
1370 }
1371 /* no luck yet with the source address. if this is the best (first)
1372 * route we store it as fallback in case we don't find a route with
1373 * the preferred source */
1374 best = best ?: route;
1375 continue;
1376 }
1377 if (route->oif)
1378 { /* no src, but an interface - get address from it */
1379 route->src_host = get_interface_address(this, route->oif,
1380 msg->rtm_family, candidate);
1381 if (route->src_host)
1382 { /* we handle this address the same as the one above */
1383 if (!candidate ||
1384 candidate->ip_equals(candidate, route->src_host))
1385 {
1386 best = route;
1387 break;
1388 }
1389 best = best ?: route;
1390 continue;
1391 }
1392 }
1393 if (route->gtw.ptr)
1394 { /* no src, no iface, but a gateway - lookup src to reach gtw */
1395 host_t *gtw;
1396
1397 gtw = host_create_from_chunk(msg->rtm_family, route->gtw, 0);
1398 route->src_host = get_route(this, gtw, FALSE, candidate);
1399 gtw->destroy(gtw);
1400 if (route->src_host)
1401 { /* more of the same */
1402 if (!candidate ||
1403 candidate->ip_equals(candidate, route->src_host))
1404 {
1405 best = route;
1406 break;
1407 }
1408 best = best ?: route;
1409 }
1410 }
1411 }
1412 enumerator->destroy(enumerator);
1413
1414 if (nexthop)
1415 { /* nexthop lookup, return gateway if any */
1416 if (best || routes->get_first(routes, (void**)&best) == SUCCESS)
1417 {
1418 addr = host_create_from_chunk(msg->rtm_family, best->gtw, 0);
1419 }
1420 addr = addr ?: dest->clone(dest);
1421 }
1422 else
1423 {
1424 if (best)
1425 {
1426 addr = best->src_host->clone(best->src_host);
1427 }
1428 }
1429 this->mutex->unlock(this->mutex);
1430 routes->destroy_function(routes, (void*)rt_entry_destroy);
1431 free(out);
1432
1433 if (addr)
1434 {
1435 DBG2(DBG_KNL, "using %H as %s to reach %H", addr,
1436 nexthop ? "nexthop" : "address", dest);
1437 }
1438 else
1439 {
1440 DBG2(DBG_KNL, "no %s found to reach %H",
1441 nexthop ? "nexthop" : "address", dest);
1442 }
1443 return addr;
1444 }
1445
1446 METHOD(kernel_net_t, get_source_addr, host_t*,
1447 private_kernel_netlink_net_t *this, host_t *dest, host_t *src)
1448 {
1449 return get_route(this, dest, FALSE, src);
1450 }
1451
1452 METHOD(kernel_net_t, get_nexthop, host_t*,
1453 private_kernel_netlink_net_t *this, host_t *dest, host_t *src)
1454 {
1455 return get_route(this, dest, TRUE, src);
1456 }
1457
1458 /**
1459 * Manages the creation and deletion of ip addresses on an interface.
1460 * By setting the appropriate nlmsg_type, the ip will be set or unset.
1461 */
1462 static status_t manage_ipaddr(private_kernel_netlink_net_t *this, int nlmsg_type,
1463 int flags, int if_index, host_t *ip)
1464 {
1465 netlink_buf_t request;
1466 struct nlmsghdr *hdr;
1467 struct ifaddrmsg *msg;
1468 chunk_t chunk;
1469
1470 memset(&request, 0, sizeof(request));
1471
1472 chunk = ip->get_address(ip);
1473
1474 hdr = (struct nlmsghdr*)request;
1475 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
1476 hdr->nlmsg_type = nlmsg_type;
1477 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg));
1478
1479 msg = (struct ifaddrmsg*)NLMSG_DATA(hdr);
1480 msg->ifa_family = ip->get_family(ip);
1481 msg->ifa_flags = 0;
1482 msg->ifa_prefixlen = 8 * chunk.len;
1483 msg->ifa_scope = RT_SCOPE_UNIVERSE;
1484 msg->ifa_index = if_index;
1485
1486 netlink_add_attribute(hdr, IFA_LOCAL, chunk, sizeof(request));
1487
1488 return this->socket->send_ack(this->socket, hdr);
1489 }
1490
1491 METHOD(kernel_net_t, add_ip, status_t,
1492 private_kernel_netlink_net_t *this, host_t *virtual_ip, host_t *iface_ip)
1493 {
1494 iface_entry_t *iface;
1495 addr_entry_t *addr;
1496 enumerator_t *addrs, *ifaces;
1497 int ifindex;
1498
1499 if (!this->install_virtual_ip)
1500 { /* disabled by config */
1501 return SUCCESS;
1502 }
1503
1504 DBG2(DBG_KNL, "adding virtual IP %H", virtual_ip);
1505
1506 this->mutex->lock(this->mutex);
1507 ifaces = this->ifaces->create_enumerator(this->ifaces);
1508 while (ifaces->enumerate(ifaces, &iface))
1509 {
1510 bool iface_found = FALSE;
1511
1512 addrs = iface->addrs->create_enumerator(iface->addrs);
1513 while (addrs->enumerate(addrs, &addr))
1514 {
1515 if (iface_ip->ip_equals(iface_ip, addr->ip))
1516 {
1517 iface_found = TRUE;
1518 }
1519 else if (virtual_ip->ip_equals(virtual_ip, addr->ip))
1520 {
1521 addr->refcount++;
1522 DBG2(DBG_KNL, "virtual IP %H already installed on %s",
1523 virtual_ip, iface->ifname);
1524 addrs->destroy(addrs);
1525 ifaces->destroy(ifaces);
1526 this->mutex->unlock(this->mutex);
1527 return SUCCESS;
1528 }
1529 }
1530 addrs->destroy(addrs);
1531
1532 if (iface_found)
1533 {
1534 ifindex = iface->ifindex;
1535 addr = malloc_thing(addr_entry_t);
1536 addr->ip = virtual_ip->clone(virtual_ip);
1537 addr->refcount = 0;
1538 addr->virtual = TRUE;
1539 addr->scope = RT_SCOPE_UNIVERSE;
1540 iface->addrs->insert_last(iface->addrs, addr);
1541
1542 if (manage_ipaddr(this, RTM_NEWADDR, NLM_F_CREATE | NLM_F_EXCL,
1543 ifindex, virtual_ip) == SUCCESS)
1544 {
1545 while (get_vip_refcount(this, virtual_ip) == 0)
1546 { /* wait until address appears */
1547 this->condvar->wait(this->condvar, this->mutex);
1548 }
1549 ifaces->destroy(ifaces);
1550 this->mutex->unlock(this->mutex);
1551 return SUCCESS;
1552 }
1553 ifaces->destroy(ifaces);
1554 this->mutex->unlock(this->mutex);
1555 DBG1(DBG_KNL, "adding virtual IP %H failed", virtual_ip);
1556 return FAILED;
1557 }
1558 }
1559 ifaces->destroy(ifaces);
1560 this->mutex->unlock(this->mutex);
1561
1562 DBG1(DBG_KNL, "interface address %H not found, unable to install"
1563 "virtual IP %H", iface_ip, virtual_ip);
1564 return FAILED;
1565 }
1566
1567 METHOD(kernel_net_t, del_ip, status_t,
1568 private_kernel_netlink_net_t *this, host_t *virtual_ip)
1569 {
1570 iface_entry_t *iface;
1571 addr_entry_t *addr;
1572 enumerator_t *addrs, *ifaces;
1573 status_t status;
1574 int ifindex;
1575
1576 if (!this->install_virtual_ip)
1577 { /* disabled by config */
1578 return SUCCESS;
1579 }
1580
1581 DBG2(DBG_KNL, "deleting virtual IP %H", virtual_ip);
1582
1583 this->mutex->lock(this->mutex);
1584 ifaces = this->ifaces->create_enumerator(this->ifaces);
1585 while (ifaces->enumerate(ifaces, &iface))
1586 {
1587 addrs = iface->addrs->create_enumerator(iface->addrs);
1588 while (addrs->enumerate(addrs, &addr))
1589 {
1590 if (virtual_ip->ip_equals(virtual_ip, addr->ip))
1591 {
1592 ifindex = iface->ifindex;
1593 if (addr->refcount == 1)
1594 {
1595 status = manage_ipaddr(this, RTM_DELADDR, 0,
1596 ifindex, virtual_ip);
1597 if (status == SUCCESS)
1598 { /* wait until the address is really gone */
1599 while (get_vip_refcount(this, virtual_ip) > 0)
1600 {
1601 this->condvar->wait(this->condvar, this->mutex);
1602 }
1603 }
1604 addrs->destroy(addrs);
1605 ifaces->destroy(ifaces);
1606 this->mutex->unlock(this->mutex);
1607 return status;
1608 }
1609 else
1610 {
1611 addr->refcount--;
1612 }
1613 DBG2(DBG_KNL, "virtual IP %H used by other SAs, not deleting",
1614 virtual_ip);
1615 addrs->destroy(addrs);
1616 ifaces->destroy(ifaces);
1617 this->mutex->unlock(this->mutex);
1618 return SUCCESS;
1619 }
1620 }
1621 addrs->destroy(addrs);
1622 }
1623 ifaces->destroy(ifaces);
1624 this->mutex->unlock(this->mutex);
1625
1626 DBG2(DBG_KNL, "virtual IP %H not cached, unable to delete", virtual_ip);
1627 return FAILED;
1628 }
1629
1630 /**
1631 * Manages source routes in the routing table.
1632 * By setting the appropriate nlmsg_type, the route gets added or removed.
1633 */
1634 static status_t manage_srcroute(private_kernel_netlink_net_t *this,
1635 int nlmsg_type, int flags, chunk_t dst_net,
1636 u_int8_t prefixlen, host_t *gateway,
1637 host_t *src_ip, char *if_name)
1638 {
1639 netlink_buf_t request;
1640 struct nlmsghdr *hdr;
1641 struct rtmsg *msg;
1642 int ifindex;
1643 chunk_t chunk;
1644
1645 /* if route is 0.0.0.0/0, we can't install it, as it would
1646 * overwrite the default route. Instead, we add two routes:
1647 * 0.0.0.0/1 and 128.0.0.0/1 */
1648 if (this->routing_table == 0 && prefixlen == 0)
1649 {
1650 chunk_t half_net;
1651 u_int8_t half_prefixlen;
1652 status_t status;
1653
1654 half_net = chunk_alloca(dst_net.len);
1655 memset(half_net.ptr, 0, half_net.len);
1656 half_prefixlen = 1;
1657
1658 status = manage_srcroute(this, nlmsg_type, flags, half_net, half_prefixlen,
1659 gateway, src_ip, if_name);
1660 half_net.ptr[0] |= 0x80;
1661 status = manage_srcroute(this, nlmsg_type, flags, half_net, half_prefixlen,
1662 gateway, src_ip, if_name);
1663 return status;
1664 }
1665
1666 memset(&request, 0, sizeof(request));
1667
1668 hdr = (struct nlmsghdr*)request;
1669 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
1670 hdr->nlmsg_type = nlmsg_type;
1671 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
1672
1673 msg = (struct rtmsg*)NLMSG_DATA(hdr);
1674 msg->rtm_family = src_ip->get_family(src_ip);
1675 msg->rtm_dst_len = prefixlen;
1676 msg->rtm_table = this->routing_table;
1677 msg->rtm_protocol = RTPROT_STATIC;
1678 msg->rtm_type = RTN_UNICAST;
1679 msg->rtm_scope = RT_SCOPE_UNIVERSE;
1680
1681 netlink_add_attribute(hdr, RTA_DST, dst_net, sizeof(request));
1682 chunk = src_ip->get_address(src_ip);
1683 netlink_add_attribute(hdr, RTA_PREFSRC, chunk, sizeof(request));
1684 if (gateway && gateway->get_family(gateway) == src_ip->get_family(src_ip))
1685 {
1686 chunk = gateway->get_address(gateway);
1687 netlink_add_attribute(hdr, RTA_GATEWAY, chunk, sizeof(request));
1688 }
1689 ifindex = get_interface_index(this, if_name);
1690 chunk.ptr = (char*)&ifindex;
1691 chunk.len = sizeof(ifindex);
1692 netlink_add_attribute(hdr, RTA_OIF, chunk, sizeof(request));
1693
1694 return this->socket->send_ack(this->socket, hdr);
1695 }
1696
1697 METHOD(kernel_net_t, add_route, status_t,
1698 private_kernel_netlink_net_t *this, chunk_t dst_net, u_int8_t prefixlen,
1699 host_t *gateway, host_t *src_ip, char *if_name)
1700 {
1701 status_t status;
1702 route_entry_t *found, route = {
1703 .dst_net = dst_net,
1704 .prefixlen = prefixlen,
1705 .gateway = gateway,
1706 .src_ip = src_ip,
1707 .if_name = if_name,
1708 };
1709
1710 this->mutex->lock(this->mutex);
1711 found = this->routes->get(this->routes, &route);
1712 if (found)
1713 {
1714 this->mutex->unlock(this->mutex);
1715 return ALREADY_DONE;
1716 }
1717 found = route_entry_clone(&route);
1718 this->routes->put(this->routes, found, found);
1719 status = manage_srcroute(this, RTM_NEWROUTE, NLM_F_CREATE | NLM_F_EXCL,
1720 dst_net, prefixlen, gateway, src_ip, if_name);
1721 this->mutex->unlock(this->mutex);
1722 return status;
1723 }
1724
1725 METHOD(kernel_net_t, del_route, status_t,
1726 private_kernel_netlink_net_t *this, chunk_t dst_net, u_int8_t prefixlen,
1727 host_t *gateway, host_t *src_ip, char *if_name)
1728 {
1729 status_t status;
1730 route_entry_t *found, route = {
1731 .dst_net = dst_net,
1732 .prefixlen = prefixlen,
1733 .gateway = gateway,
1734 .src_ip = src_ip,
1735 .if_name = if_name,
1736 };
1737
1738 this->mutex->lock(this->mutex);
1739 found = this->routes->get(this->routes, &route);
1740 if (!found)
1741 {
1742 this->mutex->unlock(this->mutex);
1743 return NOT_FOUND;
1744 }
1745 this->routes->remove(this->routes, found);
1746 route_entry_destroy(found);
1747 status = manage_srcroute(this, RTM_DELROUTE, 0, dst_net, prefixlen,
1748 gateway, src_ip, if_name);
1749 this->mutex->unlock(this->mutex);
1750 return status;
1751 }
1752
1753 /**
1754 * Initialize a list of local addresses.
1755 */
1756 static status_t init_address_list(private_kernel_netlink_net_t *this)
1757 {
1758 netlink_buf_t request;
1759 struct nlmsghdr *out, *current, *in;
1760 struct rtgenmsg *msg;
1761 size_t len;
1762 enumerator_t *ifaces, *addrs;
1763 iface_entry_t *iface;
1764 addr_entry_t *addr;
1765
1766 DBG2(DBG_KNL, "known interfaces and IP addresses:");
1767
1768 memset(&request, 0, sizeof(request));
1769
1770 in = (struct nlmsghdr*)&request;
1771 in->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg));
1772 in->nlmsg_flags = NLM_F_REQUEST | NLM_F_MATCH | NLM_F_ROOT;
1773 msg = (struct rtgenmsg*)NLMSG_DATA(in);
1774 msg->rtgen_family = AF_UNSPEC;
1775
1776 /* get all links */
1777 in->nlmsg_type = RTM_GETLINK;
1778 if (this->socket->send(this->socket, in, &out, &len) != SUCCESS)
1779 {
1780 return FAILED;
1781 }
1782 current = out;
1783 while (NLMSG_OK(current, len))
1784 {
1785 switch (current->nlmsg_type)
1786 {
1787 case NLMSG_DONE:
1788 break;
1789 case RTM_NEWLINK:
1790 process_link(this, current, FALSE);
1791 /* fall through */
1792 default:
1793 current = NLMSG_NEXT(current, len);
1794 continue;
1795 }
1796 break;
1797 }
1798 free(out);
1799
1800 /* get all interface addresses */
1801 in->nlmsg_type = RTM_GETADDR;
1802 if (this->socket->send(this->socket, in, &out, &len) != SUCCESS)
1803 {
1804 return FAILED;
1805 }
1806 current = out;
1807 while (NLMSG_OK(current, len))
1808 {
1809 switch (current->nlmsg_type)
1810 {
1811 case NLMSG_DONE:
1812 break;
1813 case RTM_NEWADDR:
1814 process_addr(this, current, FALSE);
1815 /* fall through */
1816 default:
1817 current = NLMSG_NEXT(current, len);
1818 continue;
1819 }
1820 break;
1821 }
1822 free(out);
1823
1824 this->mutex->lock(this->mutex);
1825 ifaces = this->ifaces->create_enumerator(this->ifaces);
1826 while (ifaces->enumerate(ifaces, &iface))
1827 {
1828 if (iface->flags & IFF_UP)
1829 {
1830 DBG2(DBG_KNL, " %s", iface->ifname);
1831 addrs = iface->addrs->create_enumerator(iface->addrs);
1832 while (addrs->enumerate(addrs, (void**)&addr))
1833 {
1834 DBG2(DBG_KNL, " %H", addr->ip);
1835 }
1836 addrs->destroy(addrs);
1837 }
1838 }
1839 ifaces->destroy(ifaces);
1840 this->mutex->unlock(this->mutex);
1841 return SUCCESS;
1842 }
1843
1844 /**
1845 * create or delete a rule to use our routing table
1846 */
1847 static status_t manage_rule(private_kernel_netlink_net_t *this, int nlmsg_type,
1848 int family, u_int32_t table, u_int32_t prio)
1849 {
1850 netlink_buf_t request;
1851 struct nlmsghdr *hdr;
1852 struct rtmsg *msg;
1853 chunk_t chunk;
1854
1855 memset(&request, 0, sizeof(request));
1856 hdr = (struct nlmsghdr*)request;
1857 hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
1858 hdr->nlmsg_type = nlmsg_type;
1859 if (nlmsg_type == RTM_NEWRULE)
1860 {
1861 hdr->nlmsg_flags |= NLM_F_CREATE | NLM_F_EXCL;
1862 }
1863 hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
1864
1865 msg = (struct rtmsg*)NLMSG_DATA(hdr);
1866 msg->rtm_table = table;
1867 msg->rtm_family = family;
1868 msg->rtm_protocol = RTPROT_BOOT;
1869 msg->rtm_scope = RT_SCOPE_UNIVERSE;
1870 msg->rtm_type = RTN_UNICAST;
1871
1872 chunk = chunk_from_thing(prio);
1873 netlink_add_attribute(hdr, RTA_PRIORITY, chunk, sizeof(request));
1874
1875 return this->socket->send_ack(this->socket, hdr);
1876 }
1877
1878 /**
1879 * check for kernel features (currently only via version number)
1880 */
1881 static void check_kernel_features(private_kernel_netlink_net_t *this)
1882 {
1883 struct utsname utsname;
1884 int a, b, c;
1885
1886 if (uname(&utsname) == 0)
1887 {
1888 switch(sscanf(utsname.release, "%d.%d.%d", &a, &b, &c))
1889 {
1890 case 3:
1891 if (a == 2)
1892 {
1893 DBG2(DBG_KNL, "detected Linux %d.%d.%d, no support for "
1894 "RTA_PREFSRC for IPv6 routes", a, b, c);
1895 break;
1896 }
1897 /* fall-through */
1898 case 2:
1899 /* only 3.x+ uses two part version numbers */
1900 this->rta_prefsrc_for_ipv6 = TRUE;
1901 break;
1902 default:
1903 break;
1904 }
1905 }
1906 }
1907
1908 METHOD(kernel_net_t, destroy, void,
1909 private_kernel_netlink_net_t *this)
1910 {
1911 enumerator_t *enumerator;
1912 route_entry_t *route;
1913
1914 if (this->routing_table)
1915 {
1916 manage_rule(this, RTM_DELRULE, AF_INET, this->routing_table,
1917 this->routing_table_prio);
1918 manage_rule(this, RTM_DELRULE, AF_INET6, this->routing_table,
1919 this->routing_table_prio);
1920 }
1921 if (this->socket_events > 0)
1922 {
1923 close(this->socket_events);
1924 }
1925 enumerator = this->routes->create_enumerator(this->routes);
1926 while (enumerator->enumerate(enumerator, NULL, (void**)&route))
1927 {
1928 manage_srcroute(this, RTM_DELROUTE, 0, route->dst_net, route->prefixlen,
1929 route->gateway, route->src_ip, route->if_name);
1930 route_entry_destroy(route);
1931 }
1932 enumerator->destroy(enumerator);
1933 this->routes->destroy(this->routes);
1934 DESTROY_IF(this->socket);
1935
1936 net_changes_clear(this);
1937 this->net_changes->destroy(this->net_changes);
1938 this->net_changes_lock->destroy(this->net_changes_lock);
1939
1940 this->ifaces->destroy_function(this->ifaces, (void*)iface_entry_destroy);
1941 this->rt_exclude->destroy(this->rt_exclude);
1942 this->condvar->destroy(this->condvar);
1943 this->mutex->destroy(this->mutex);
1944 free(this);
1945 }
1946
1947 /*
1948 * Described in header.
1949 */
1950 kernel_netlink_net_t *kernel_netlink_net_create()
1951 {
1952 private_kernel_netlink_net_t *this;
1953 enumerator_t *enumerator;
1954 bool register_for_events = TRUE;
1955 char *exclude;
1956
1957 INIT(this,
1958 .public = {
1959 .interface = {
1960 .get_interface = _get_interface_name,
1961 .create_address_enumerator = _create_address_enumerator,
1962 .get_source_addr = _get_source_addr,
1963 .get_nexthop = _get_nexthop,
1964 .add_ip = _add_ip,
1965 .del_ip = _del_ip,
1966 .add_route = _add_route,
1967 .del_route = _del_route,
1968 .destroy = _destroy,
1969 },
1970 },
1971 .socket = netlink_socket_create(NETLINK_ROUTE),
1972 .rt_exclude = linked_list_create(),
1973 .routes = hashtable_create((hashtable_hash_t)route_entry_hash,
1974 (hashtable_equals_t)route_entry_equals, 16),
1975 .net_changes = hashtable_create(
1976 (hashtable_hash_t)net_change_hash,
1977 (hashtable_equals_t)net_change_equals, 16),
1978 .net_changes_lock = mutex_create(MUTEX_TYPE_DEFAULT),
1979 .ifaces = linked_list_create(),
1980 .mutex = mutex_create(MUTEX_TYPE_RECURSIVE),
1981 .condvar = condvar_create(CONDVAR_TYPE_DEFAULT),
1982 .routing_table = lib->settings->get_int(lib->settings,
1983 "%s.routing_table", ROUTING_TABLE, hydra->daemon),
1984 .routing_table_prio = lib->settings->get_int(lib->settings,
1985 "%s.routing_table_prio", ROUTING_TABLE_PRIO, hydra->daemon),
1986 .process_route = lib->settings->get_bool(lib->settings,
1987 "%s.process_route", TRUE, hydra->daemon),
1988 .install_virtual_ip = lib->settings->get_bool(lib->settings,
1989 "%s.install_virtual_ip", TRUE, hydra->daemon),
1990 );
1991 timerclear(&this->last_route_reinstall);
1992 timerclear(&this->last_roam);
1993
1994 check_kernel_features(this);
1995
1996 if (streq(hydra->daemon, "starter"))
1997 { /* starter has no threads, so we do not register for kernel events */
1998 register_for_events = FALSE;
1999 }
2000
2001 exclude = lib->settings->get_str(lib->settings,
2002 "%s.ignore_routing_tables", NULL, hydra->daemon);
2003 if (exclude)
2004 {
2005 char *token;
2006 uintptr_t table;
2007
2008 enumerator = enumerator_create_token(exclude, " ", " ");
2009 while (enumerator->enumerate(enumerator, &token))
2010 {
2011 errno = 0;
2012 table = strtoul(token, NULL, 10);
2013
2014 if (errno == 0)
2015 {
2016 this->rt_exclude->insert_last(this->rt_exclude, (void*)table);
2017 }
2018 }
2019 enumerator->destroy(enumerator);
2020 }
2021
2022 if (register_for_events)
2023 {
2024 struct sockaddr_nl addr;
2025
2026 memset(&addr, 0, sizeof(addr));
2027 addr.nl_family = AF_NETLINK;
2028
2029 /* create and bind RT socket for events (address/interface/route changes) */
2030 this->socket_events = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
2031 if (this->socket_events < 0)
2032 {
2033 DBG1(DBG_KNL, "unable to create RT event socket");
2034 destroy(this);
2035 return NULL;
2036 }
2037 addr.nl_groups = RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR |
2038 RTMGRP_IPV4_ROUTE | RTMGRP_IPV6_ROUTE | RTMGRP_LINK;
2039 if (bind(this->socket_events, (struct sockaddr*)&addr, sizeof(addr)))
2040 {
2041 DBG1(DBG_KNL, "unable to bind RT event socket");
2042 destroy(this);
2043 return NULL;
2044 }
2045
2046 lib->processor->queue_job(lib->processor,
2047 (job_t*)callback_job_create_with_prio(
2048 (callback_job_cb_t)receive_events, this, NULL,
2049 (callback_job_cancel_t)return_false, JOB_PRIO_CRITICAL));
2050 }
2051
2052 if (init_address_list(this) != SUCCESS)
2053 {
2054 DBG1(DBG_KNL, "unable to get interface list");
2055 destroy(this);
2056 return NULL;
2057 }
2058
2059 if (this->routing_table)
2060 {
2061 if (manage_rule(this, RTM_NEWRULE, AF_INET, this->routing_table,
2062 this->routing_table_prio) != SUCCESS)
2063 {
2064 DBG1(DBG_KNL, "unable to create IPv4 routing table rule");
2065 }
2066 if (manage_rule(this, RTM_NEWRULE, AF_INET6, this->routing_table,
2067 this->routing_table_prio) != SUCCESS)
2068 {
2069 DBG1(DBG_KNL, "unable to create IPv6 routing table rule");
2070 }
2071 }
2072
2073 return &this->public;
2074 }