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