5889ca5acbd45ce1df7e79b762e1134c2d985f4b
[NetworkManager.git] / src / ip6-manager / nm-ip6-manager.c
1 /* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
2 /* nm-ip6-manager.c - Handle IPv6 address configuration for NetworkManager
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2, or (at your option)
7  * any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  *
18  * Copyright (C) 2009 - 2010 Red Hat, Inc.
19  */
20
21 #include <errno.h>
22 #include <netinet/icmp6.h>
23
24 #include <netlink/route/addr.h>
25 #include <netlink/route/rtnl.h>
26 #include <netlink/route/route.h>
27
28 #include "nm-ip6-manager.h"
29 #include "nm-netlink-monitor.h"
30 #include "nm-netlink-utils.h"
31 #include "nm-netlink-compat.h"
32 #include "NetworkManagerUtils.h"
33 #include "nm-marshal.h"
34 #include "nm-logging.h"
35
36 /* Pre-DHCP addrconf timeout, in seconds */
37 #define NM_IP6_TIMEOUT 20
38
39 /* FIXME? Stolen from the kernel sources */
40 #define IF_RA_OTHERCONF 0x80
41 #define IF_RA_MANAGED   0x40
42 #define IF_RA_RCVD      0x20
43 #define IF_RS_SENT      0x10
44
45 typedef struct {
46         NMNetlinkMonitor *monitor;
47         GHashTable *devices;
48
49         struct nl_sock *nlh;
50         struct nl_cache *addr_cache, *route_cache;
51
52         guint netlink_id;
53 } NMIP6ManagerPrivate;
54
55 #define NM_IP6_MANAGER_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), NM_TYPE_IP6_MANAGER, NMIP6ManagerPrivate))
56
57 G_DEFINE_TYPE (NMIP6Manager, nm_ip6_manager, G_TYPE_OBJECT)
58
59 enum {
60         ADDRCONF_COMPLETE,
61         CONFIG_CHANGED,
62         LAST_SIGNAL
63 };
64
65 static guint signals[LAST_SIGNAL] = { 0 };
66
67 typedef enum {
68         NM_IP6_DEVICE_UNCONFIGURED,
69         NM_IP6_DEVICE_GOT_LINK_LOCAL,
70         NM_IP6_DEVICE_GOT_ROUTER_ADVERTISEMENT,
71         NM_IP6_DEVICE_GOT_ADDRESS,
72         NM_IP6_DEVICE_TIMED_OUT
73 } NMIP6DeviceState;
74
75 typedef struct {
76         struct in6_addr addr;
77         time_t expires;
78 } NMIP6RDNSS;
79
80 typedef struct {
81         char domain[256];
82         time_t expires;
83 } NMIP6DNSSL;
84
85 /******************************************************************/
86
87 typedef struct {
88         NMIP6Manager *manager;
89         char *iface;
90         int ifindex;
91
92         gboolean has_linklocal;
93         gboolean has_nonlinklocal;
94         guint dhcp_opts;
95
96         char *disable_ip6_path;
97         gboolean disable_ip6_save_valid;
98         gint32 disable_ip6_save;
99
100         guint finish_addrconf_id;
101         guint config_changed_id;
102
103         NMIP6DeviceState state;
104         NMIP6DeviceState target_state;
105         gboolean addrconf_complete;
106
107         GArray *rdnss_servers;
108         guint rdnss_timeout_id;
109
110         GArray *dnssl_domains;
111         guint dnssl_timeout_id;
112
113         guint ip6flags_poll_id;
114
115         guint32 ra_flags;
116 } NMIP6Device;
117
118 static void
119 clear_config_changed (NMIP6Device *device)
120 {
121         if (device->config_changed_id)
122                 g_source_remove (device->config_changed_id);
123         device->config_changed_id = 0;
124 }
125
126 static void
127 nm_ip6_device_destroy (NMIP6Device *device)
128 {
129         g_return_if_fail (device != NULL);
130
131         /* reset the saved IPv6 value */
132         if (device->disable_ip6_save_valid) {
133                 nm_utils_do_sysctl (device->disable_ip6_path,
134                                     device->disable_ip6_save ? "1\n" : "0\n");
135         }
136
137         if (device->finish_addrconf_id)
138                 g_source_remove (device->finish_addrconf_id);
139
140         clear_config_changed (device);
141
142         g_free (device->iface);
143         if (device->rdnss_servers)
144                 g_array_free (device->rdnss_servers, TRUE);
145         if (device->rdnss_timeout_id)
146                 g_source_remove (device->rdnss_timeout_id);
147         if (device->dnssl_domains)
148                 g_array_free (device->dnssl_domains, TRUE);
149         if (device->dnssl_timeout_id)
150                 g_source_remove (device->dnssl_timeout_id);
151         if (device->ip6flags_poll_id)
152                 g_source_remove (device->ip6flags_poll_id);
153
154         g_slice_free (NMIP6Device, device);
155 }
156
157 static NMIP6Device *
158 nm_ip6_device_new (NMIP6Manager *manager, int ifindex)
159 {
160         NMIP6ManagerPrivate *priv = NM_IP6_MANAGER_GET_PRIVATE (manager);
161         NMIP6Device *device;
162
163         g_return_val_if_fail (ifindex > 0, NULL);
164
165         device = g_slice_new0 (NMIP6Device);
166         if (!device) {
167                 nm_log_err (LOGD_IP6, "(%d): out of memory creating IP6 addrconf object.",
168                             ifindex);
169                 return NULL;
170         }
171
172         device->ifindex = ifindex;
173         device->iface = nm_netlink_index_to_iface (ifindex);
174         if (!device->iface) {
175                 nm_log_err (LOGD_IP6, "(%d): could not find interface name from index.",
176                             ifindex);
177                 goto error;
178         }
179
180         device->manager = manager;
181
182         device->rdnss_servers = g_array_new (FALSE, FALSE, sizeof (NMIP6RDNSS));
183
184         device->dnssl_domains = g_array_new (FALSE, FALSE, sizeof (NMIP6DNSSL));
185
186         g_hash_table_replace (priv->devices, GINT_TO_POINTER (device->ifindex), device);
187
188         /* and the original value of IPv6 enable/disable */
189         device->disable_ip6_path = g_strdup_printf ("/proc/sys/net/ipv6/conf/%s/disable_ipv6",
190                                                     device->iface);
191         g_assert (device->disable_ip6_path);
192         device->disable_ip6_save_valid = nm_utils_get_proc_sys_net_value_with_bounds (device->disable_ip6_path,
193                                                                                       device->iface,
194                                                                                       &device->disable_ip6_save,
195                                                                                       0, 1);
196
197         return device;
198
199 error:
200         nm_ip6_device_destroy (device);
201         return NULL;
202 }
203
204 static NMIP6Device *
205 nm_ip6_manager_get_device (NMIP6Manager *manager, int ifindex)
206 {
207         NMIP6ManagerPrivate *priv;
208
209         g_return_val_if_fail (manager != NULL, NULL);
210         g_return_val_if_fail (NM_IS_IP6_MANAGER (manager), NULL);
211
212         priv = NM_IP6_MANAGER_GET_PRIVATE (manager);
213         return g_hash_table_lookup (priv->devices, GINT_TO_POINTER (ifindex));
214 }
215
216 static char *
217 device_get_iface (NMIP6Device *device)
218 {
219         return device ? device->iface : "unknown";
220 }
221
222 static const char *
223 state_to_string (NMIP6DeviceState state)
224 {
225         switch (state) {
226         case NM_IP6_DEVICE_UNCONFIGURED:
227                 return "unconfigured";
228         case NM_IP6_DEVICE_GOT_LINK_LOCAL:
229                 return "got-link-local";
230         case NM_IP6_DEVICE_GOT_ROUTER_ADVERTISEMENT:
231                 return "got-ra";
232         case NM_IP6_DEVICE_GOT_ADDRESS:
233                 return "got-address";
234         case NM_IP6_DEVICE_TIMED_OUT:
235                 return "timed-out";
236         default:
237                 return "unknown";
238         }
239 }
240
241 static void
242 device_set_state (NMIP6Device *device, NMIP6DeviceState state)
243 {
244         NMIP6DeviceState oldstate;
245
246         g_return_if_fail (device != NULL);
247
248         oldstate = device->state;
249         device->state = state;
250         nm_log_dbg (LOGD_IP6, "(%s) IP6 device state: %s -> %s",
251                     device_get_iface (device), state_to_string (oldstate), state_to_string (state));
252 }
253
254 /******************************************************************/
255
256 typedef struct {
257         NMIP6Device *device;
258         guint dhcp_opts;
259         gboolean success;
260 } CallbackInfo;
261
262 static gboolean
263 finish_addrconf (gpointer user_data)
264 {
265         CallbackInfo *info = user_data;
266         NMIP6Device *device = info->device;
267         NMIP6Manager *manager = device->manager;
268         int ifindex;
269
270         device->finish_addrconf_id = 0;
271         device->addrconf_complete = TRUE;
272         ifindex = device->ifindex;
273
274         /* We're done, stop polling IPv6 flags */
275         if (device->ip6flags_poll_id) {
276                 g_source_remove (device->ip6flags_poll_id);
277                 device->ip6flags_poll_id = 0;
278         }
279
280         /* And tell listeners that addrconf is complete */
281         if (info->success) {
282                 g_signal_emit (manager, signals[ADDRCONF_COMPLETE], 0,
283                                ifindex, info->dhcp_opts, TRUE);
284         } else {
285                 nm_log_info (LOGD_IP6, "(%s): IP6 addrconf timed out or failed.",
286                              device->iface);
287
288                 nm_ip6_manager_cancel_addrconf (manager, ifindex);
289                 g_signal_emit (manager, signals[ADDRCONF_COMPLETE], 0,
290                                ifindex, info->dhcp_opts, FALSE);
291         }
292
293         return FALSE;
294 }
295
296 static gboolean
297 emit_config_changed (gpointer user_data)
298 {
299         CallbackInfo *info = user_data;
300         NMIP6Device *device = info->device;
301         NMIP6Manager *manager = device->manager;
302
303         device->config_changed_id = 0;
304         g_signal_emit (manager, signals[CONFIG_CHANGED], 0,
305                        device->ifindex,
306                        info->dhcp_opts,
307                        info->success);
308         return FALSE;
309 }
310
311 static void set_rdnss_timeout (NMIP6Device *device);
312
313 static gboolean
314 rdnss_expired (gpointer user_data)
315 {
316         NMIP6Device *device = user_data;
317         CallbackInfo info = { device, IP6_DHCP_OPT_NONE, FALSE };
318
319         nm_log_dbg (LOGD_IP6, "(%s): IPv6 RDNSS information expired", device->iface);
320
321         set_rdnss_timeout (device);
322         clear_config_changed (device);
323         emit_config_changed (&info);
324         return FALSE;
325 }
326
327 static void
328 set_rdnss_timeout (NMIP6Device *device)
329 {
330         time_t expires = 0, now = time (NULL);
331         NMIP6RDNSS *rdnss;
332         int i;
333
334         if (device->rdnss_timeout_id) {
335                 g_source_remove (device->rdnss_timeout_id);
336                 device->rdnss_timeout_id = 0;
337         }
338
339         /* Find the soonest expiration time. */
340         for (i = 0; i < device->rdnss_servers->len; i++) {
341                 rdnss = &g_array_index (device->rdnss_servers, NMIP6RDNSS, i);
342                 if (rdnss->expires == 0)
343                         continue;
344
345                 /* If the entry has already expired, remove it; the "+ 1" is
346                  * because g_timeout_add_seconds() might fudge the timing a
347                  * bit.
348                  */
349                 if (rdnss->expires <= now + 1) {
350                         char buf[INET6_ADDRSTRLEN + 1];
351
352                         if (inet_ntop (AF_INET6, &(rdnss->addr), buf, sizeof (buf)) > 0) {
353                                 nm_log_dbg (LOGD_IP6, "(%s): removing expired RA-provided nameserver %s",
354                                             device->iface, buf);
355                         }
356                         g_array_remove_index (device->rdnss_servers, i--);
357                         continue;
358                 }
359
360                 if (!expires || rdnss->expires < expires)
361                         expires = rdnss->expires;
362         }
363
364         if (expires) {
365                 device->rdnss_timeout_id = g_timeout_add_seconds (MIN (expires - now, G_MAXUINT32 - 1),
366                                                                   rdnss_expired,
367                                                                   device);
368         }
369 }
370
371 static void set_dnssl_timeout (NMIP6Device *device);
372
373 static gboolean
374 dnssl_expired (gpointer user_data)
375 {
376         NMIP6Device *device = user_data;
377         CallbackInfo info = { device, IP6_DHCP_OPT_NONE, FALSE };
378
379         nm_log_dbg (LOGD_IP6, "(%s): IPv6 DNSSL information expired", device->iface);
380
381         set_dnssl_timeout (device);
382         clear_config_changed (device);
383         emit_config_changed (&info);
384         return FALSE;
385 }
386
387 static void
388 set_dnssl_timeout (NMIP6Device *device)
389 {
390         time_t expires = 0, now = time (NULL);
391         NMIP6DNSSL *dnssl;
392         int i;
393
394         if (device->dnssl_timeout_id) {
395                 g_source_remove (device->dnssl_timeout_id);
396                 device->dnssl_timeout_id = 0;
397         }
398
399         /* Find the soonest expiration time. */
400         for (i = 0; i < device->dnssl_domains->len; i++) {
401                 dnssl = &g_array_index (device->dnssl_domains, NMIP6DNSSL, i);
402                 if (dnssl->expires == 0)
403                         continue;
404
405                 /* If the entry has already expired, remove it; the "+ 1" is
406                  * because g_timeout_add_seconds() might fudge the timing a
407                  * bit.
408                  */
409                 if (dnssl->expires <= now + 1) {
410                         nm_log_dbg (LOGD_IP6, "(%s): removing expired RA-provided domain %s",
411                                     device->iface, dnssl->domain);
412                         g_array_remove_index (device->dnssl_domains, i--);
413                         continue;
414                 }
415
416                 if (!expires || dnssl->expires < expires)
417                         expires = dnssl->expires;
418         }
419
420         if (expires) {
421                 device->dnssl_timeout_id = g_timeout_add_seconds (MIN (expires - now, G_MAXUINT32 - 1),
422                                                                   dnssl_expired,
423                                                                   device);
424         }
425 }
426
427 static CallbackInfo *
428 callback_info_new (NMIP6Device *device, guint dhcp_opts, gboolean success)
429 {
430         CallbackInfo *info;
431
432         info = g_malloc0 (sizeof (CallbackInfo));
433         info->device = device;
434         info->dhcp_opts = dhcp_opts;
435         info->success = success;
436         return info;
437 }
438
439 static void
440 check_addresses (NMIP6Device *device)
441 {
442         NMIP6Manager *manager = device->manager;
443         NMIP6ManagerPrivate *priv = NM_IP6_MANAGER_GET_PRIVATE (manager);
444         struct rtnl_addr *rtnladdr;
445         struct nl_addr *nladdr;
446         struct in6_addr *addr;
447
448         /* Reset address information */
449         device->has_linklocal = FALSE;
450         device->has_nonlinklocal = FALSE;
451
452         /* Look for any IPv6 addresses the kernel may have set for the device */
453         for (rtnladdr = (struct rtnl_addr *) nl_cache_get_first (priv->addr_cache);
454                  rtnladdr;
455                  rtnladdr = (struct rtnl_addr *) nl_cache_get_next ((struct nl_object *) rtnladdr)) {
456                 char buf[INET6_ADDRSTRLEN];
457
458                 if (rtnl_addr_get_ifindex (rtnladdr) != device->ifindex)
459                         continue;
460
461                 nladdr = rtnl_addr_get_local (rtnladdr);
462                 if (!nladdr || nl_addr_get_family (nladdr) != AF_INET6)
463                         continue;
464
465                 addr = nl_addr_get_binary_addr (nladdr);
466
467                 if (inet_ntop (AF_INET6, addr, buf, INET6_ADDRSTRLEN) > 0) {
468                         nm_log_dbg (LOGD_IP6, "(%s): netlink address: %s/%d",
469                                     device->iface, buf,
470                                     rtnl_addr_get_prefixlen (rtnladdr));
471                 }
472
473                 if (IN6_IS_ADDR_LINKLOCAL (addr)) {
474                         if (device->state == NM_IP6_DEVICE_UNCONFIGURED)
475                                 device_set_state (device, NM_IP6_DEVICE_GOT_LINK_LOCAL);
476                         device->has_linklocal = TRUE;
477                 } else {
478                         if (device->state < NM_IP6_DEVICE_GOT_ADDRESS)
479                                 device_set_state (device, NM_IP6_DEVICE_GOT_ADDRESS);
480                         device->has_nonlinklocal = TRUE;
481                 }
482         }
483
484         /* There might be a LL address hanging around on the interface from
485          * before in the initial run, but if it goes away later, make sure we
486          * regress from GOT_LINK_LOCAL back to UNCONFIGURED.
487          */
488         if ((device->state == NM_IP6_DEVICE_GOT_LINK_LOCAL) && !device->has_linklocal)
489                 device_set_state (device, NM_IP6_DEVICE_UNCONFIGURED);
490
491         nm_log_dbg (LOGD_IP6, "(%s): addresses checked (state %s)",
492                     device->iface, state_to_string (device->state));
493 }
494
495 static void
496 check_ra_flags (NMIP6Device *device)
497 {
498         device->dhcp_opts = IP6_DHCP_OPT_NONE;
499
500         /* We only care about router advertisements if we want a real IPv6 address */
501         if (   (device->target_state == NM_IP6_DEVICE_GOT_ADDRESS)
502             && (device->ra_flags & IF_RA_RCVD)) {
503
504                 if (device->state < NM_IP6_DEVICE_GOT_ROUTER_ADVERTISEMENT)
505                         device_set_state (device, NM_IP6_DEVICE_GOT_ROUTER_ADVERTISEMENT);
506
507                 if (device->ra_flags & IF_RA_MANAGED) {
508                         device->dhcp_opts = IP6_DHCP_OPT_MANAGED;
509                         nm_log_dbg (LOGD_IP6, "router advertisement deferred to DHCPv6");
510                 } else if (device->ra_flags & IF_RA_OTHERCONF) {
511                         device->dhcp_opts = IP6_DHCP_OPT_OTHERCONF;
512                         nm_log_dbg (LOGD_IP6, "router advertisement requests parallel DHCPv6");
513                 }
514         }
515         nm_log_dbg (LOGD_IP6, "(%s): router advertisement checked (state %s)",
516                     device->iface, state_to_string (device->state));
517 }
518
519 static void
520 check_addrconf_complete (NMIP6Device *device)
521 {
522         CallbackInfo *info;
523
524         if (!device->addrconf_complete) {
525                 /* Managed mode (ie DHCP only) short-circuits automatic addrconf, so
526                  * we don't bother waiting for the device's target state to be reached
527                  * when the RA requests managed mode.
528                  */
529                 if (   (device->state >= device->target_state)
530                     || (device->dhcp_opts == IP6_DHCP_OPT_MANAGED)) {
531                         /* device->finish_addrconf_id may currently be a timeout
532                          * rather than an idle, so we remove the existing source.
533                          */
534                         if (device->finish_addrconf_id)
535                                 g_source_remove (device->finish_addrconf_id);
536
537                         nm_log_dbg (LOGD_IP6, "(%s): reached target state or Managed-mode requested (state '%s') (dhcp opts 0x%X)",
538                                     device->iface, state_to_string (device->state),
539                                     device->dhcp_opts);
540
541                         info = callback_info_new (device, device->dhcp_opts, TRUE);
542                         device->finish_addrconf_id = g_idle_add_full (G_PRIORITY_DEFAULT_IDLE,
543                                                                       finish_addrconf,
544                                                                       info,
545                                                                       (GDestroyNotify) g_free);
546                 }
547         } else {
548                 if (!device->config_changed_id) {
549                         gboolean success = TRUE;
550
551                         /* If for some reason an RA-provided address disappeared, we need
552                          * to make sure we fail the connection as it's no longer valid.
553                          */
554                         if (   (device->state == NM_IP6_DEVICE_GOT_ADDRESS)
555                             && (device->target_state == NM_IP6_DEVICE_GOT_ADDRESS)
556                             && !device->has_nonlinklocal) {
557                                 nm_log_dbg (LOGD_IP6, "(%s): RA-provided address no longer found",
558                                             device->iface);
559                                 success = FALSE;
560                         }
561
562                         info = callback_info_new (device, device->dhcp_opts, success);
563                         device->config_changed_id = g_idle_add_full (G_PRIORITY_DEFAULT_IDLE,
564                                                                      emit_config_changed,
565                                                                      info,
566                                                                      (GDestroyNotify) g_free);
567                 }
568         }
569
570         nm_log_dbg (LOGD_IP6, "(%s): dhcp_opts checked (state %s)",
571                     device->iface, state_to_string (device->state));
572 }
573
574 static void
575 nm_ip6_device_sync_from_netlink (NMIP6Device *device)
576 {
577         nm_log_dbg (LOGD_IP6, "(%s): syncing with netlink (ra_flags 0x%X) (state/target '%s'/'%s')",
578                     device->iface, device->ra_flags,
579                     state_to_string (device->state),
580                     state_to_string (device->target_state));
581
582         check_addresses (device);
583         check_ra_flags (device);
584         check_addrconf_complete (device);
585 }
586
587 static void
588 ref_object (struct nl_object *obj, void *data)
589 {
590         struct nl_object **out = data;
591
592         nl_object_get (obj);
593         *out = obj;
594 }
595
596 static void
597 dump_address_change (NMIP6Device *device, struct nlmsghdr *hdr, struct rtnl_addr *rtnladdr)
598 {
599         char *event;
600         struct nl_addr *addr;
601         char addr_str[40] = "none";
602
603         event = hdr->nlmsg_type == RTM_NEWADDR ? "new" : "lost";
604         addr = rtnl_addr_get_local (rtnladdr);
605         if (addr)
606                 nl_addr2str (addr, addr_str, 40);
607
608         nm_log_dbg (LOGD_IP6, "(%s) %s address: %s", device_get_iface (device), event, addr_str);
609 }
610
611 static void
612 dump_route_change (NMIP6Device *device, struct nlmsghdr *hdr, struct rtnl_route *rtnlroute)
613 {
614         char *event;
615         struct nl_addr *dst;
616         char dst_str[40] = "none";
617         struct nl_addr *gateway;
618         char gateway_str[40] = "none";
619
620         event = hdr->nlmsg_type == RTM_NEWROUTE ? "new" : "lost";
621         dst = rtnl_route_get_dst (rtnlroute);
622         gateway = rtnl_route_get_gateway (rtnlroute);
623         if (dst)
624                 nl_addr2str (dst, dst_str, 40);
625         if (gateway)
626                 nl_addr2str (gateway, gateway_str, 40);
627
628         nm_log_dbg (LOGD_IP6, "(%s) %s route: %s via %s",device_get_iface (device), event, dst_str, gateway_str);
629 }
630
631 static NMIP6Device *
632 process_address_change (NMIP6Manager *manager, struct nl_msg *msg)
633 {
634         NMIP6ManagerPrivate *priv = NM_IP6_MANAGER_GET_PRIVATE (manager);
635         NMIP6Device *device;
636         struct nlmsghdr *hdr;
637         struct rtnl_addr *rtnladdr;
638         int old_size;
639
640         hdr = nlmsg_hdr (msg);
641         rtnladdr = NULL;
642         nl_msg_parse (msg, ref_object, &rtnladdr);
643         if (!rtnladdr) {
644                 nm_log_dbg (LOGD_IP6, "error processing netlink new/del address message");
645                 return NULL;
646         }
647
648         device = nm_ip6_manager_get_device (manager, rtnl_addr_get_ifindex (rtnladdr));
649
650         old_size = nl_cache_nitems (priv->addr_cache);
651         nl_cache_include (priv->addr_cache, (struct nl_object *)rtnladdr, NULL, NULL);
652
653         /* The kernel will re-notify us of automatically-added addresses
654          * every time it gets another router advertisement. We only want
655          * to notify higher levels if we actually changed something.
656          */
657         nm_log_dbg (LOGD_IP6, "(%s): address cache size: %d -> %d:",
658                     device_get_iface (device), old_size, nl_cache_nitems (priv->addr_cache));
659         dump_address_change (device, hdr, rtnladdr);
660         rtnl_addr_put (rtnladdr);
661         if (nl_cache_nitems (priv->addr_cache) == old_size)
662                 return NULL;
663
664         return device;
665 }
666
667 static NMIP6Device *
668 process_route_change (NMIP6Manager *manager, struct nl_msg *msg)
669 {
670         NMIP6ManagerPrivate *priv = NM_IP6_MANAGER_GET_PRIVATE (manager);
671         NMIP6Device *device;
672         struct nlmsghdr *hdr;
673         struct rtnl_route *rtnlroute;
674         int old_size;
675
676         hdr = nlmsg_hdr (msg);
677         rtnlroute = NULL;
678         nl_msg_parse (msg, ref_object, &rtnlroute);
679         if (!rtnlroute) {
680                 nm_log_dbg (LOGD_IP6, "error processing netlink new/del route message");
681                 return NULL;
682         }
683
684         device = nm_ip6_manager_get_device (manager, rtnl_route_get_oif (rtnlroute));
685
686         old_size = nl_cache_nitems (priv->route_cache);
687         nl_cache_include (priv->route_cache, (struct nl_object *)rtnlroute, NULL, NULL);
688
689         /* As above in process_address_change */
690         nm_log_dbg (LOGD_IP6, "(%s): route cache size: %d -> %d:",
691                     device_get_iface (device), old_size, nl_cache_nitems (priv->route_cache));
692         dump_route_change (device, hdr, rtnlroute);
693         rtnl_route_put (rtnlroute);
694         if (nl_cache_nitems (priv->route_cache) == old_size)
695                 return NULL;
696
697         return device;
698 }
699
700 /* RDNSS parsing code based on rdnssd, Copyright 2007 Pierre Ynard,
701  * RĂ©mi Denis-Courmont. GPLv2/3
702  */
703
704 #define ND_OPT_RDNSS 25
705 #define ND_OPT_DNSSL 31
706
707 struct nd_opt_rdnss {
708         uint8_t nd_opt_rdnss_type;
709         uint8_t nd_opt_rdnss_len;
710         uint16_t nd_opt_rdnss_reserved1;
711         uint32_t nd_opt_rdnss_lifetime;
712         /* followed by one or more IPv6 addresses */
713 } __attribute__ ((packed));
714
715 struct nd_opt_dnssl {
716         uint8_t nd_opt_dnssl_type;
717         uint8_t nd_opt_dnssl_len;
718         uint16_t nd_opt_dnssl_reserved1;
719         uint32_t nd_opt_dnssl_lifetime;
720         /* followed by one or more suffixes */
721 } __attribute__ ((packed));
722
723 static gboolean
724 process_nduseropt_rdnss (NMIP6Device *device, struct nd_opt_hdr *opt)
725 {
726         size_t opt_len;
727         struct nd_opt_rdnss *rdnss_opt;
728         time_t now = time (NULL);
729         struct in6_addr *addr;
730         GArray *new_servers;
731         NMIP6RDNSS server, *cur_server;
732         gboolean changed = FALSE;
733         guint i;
734
735         opt_len = opt->nd_opt_len;
736
737         if (opt_len < 3 || (opt_len & 1) == 0)
738                 return FALSE;
739
740         rdnss_opt = (struct nd_opt_rdnss *) opt;
741
742         new_servers = g_array_new (FALSE, FALSE, sizeof (NMIP6RDNSS));
743
744         /* Pad the DNS server expiry somewhat to give a bit of slack in cases
745          * where one RA gets lost or something (which can happen on unreliable
746          * links like WiFi where certain types of frames are not retransmitted).
747          * Note that 0 has special meaning and is therefore not adjusted.
748          */
749         server.expires = ntohl (rdnss_opt->nd_opt_rdnss_lifetime);
750         if (server.expires > 0)
751                 server.expires += now + 10;
752
753         for (addr = (struct in6_addr *) (rdnss_opt + 1); opt_len >= 2; addr++, opt_len -= 2) {
754                 char buf[INET6_ADDRSTRLEN + 1];
755
756                 if (!inet_ntop (AF_INET6, addr, buf, sizeof (buf))) {
757                         nm_log_warn (LOGD_IP6, "(%s): received invalid RA-provided nameserver", device->iface);
758                         continue;
759                 }
760
761                 /* Update the cached timeout if we already saw this server */
762                 for (i = 0; i < device->rdnss_servers->len; i++) {
763                         cur_server = &(g_array_index (device->rdnss_servers, NMIP6RDNSS, i));
764
765                         if (!IN6_ARE_ADDR_EQUAL (addr, &cur_server->addr))
766                                 continue;
767
768                         cur_server->expires = server.expires;
769
770                         if (server.expires > 0) {
771                                 nm_log_dbg (LOGD_IP6, "(%s): refreshing RA-provided nameserver %s (expires in %ld seconds)",
772                                             device->iface, buf,
773                                             server.expires - now);
774                                 break;
775                         }
776
777                         nm_log_dbg (LOGD_IP6, "(%s): removing RA-provided nameserver %s on router request",
778                                     device->iface, buf);
779
780                         g_array_remove_index (device->rdnss_servers, i);
781                         changed = TRUE;
782                         break;
783                 }
784
785                 if (server.expires == 0)
786                         continue;
787                 if (i < device->rdnss_servers->len)
788                         continue;
789
790                 nm_log_dbg (LOGD_IP6, "(%s): found RA-provided nameserver %s (expires in %ld seconds)",
791                             device->iface, buf, server.expires - now);
792
793                 server.addr = *addr;
794                 g_array_append_val (new_servers, server);
795         }
796
797         /* New servers must be added in the order they are listed in the
798          * RA option and before any existing servers.
799          *
800          * Note: This is the place to remove servers if we want to cap the
801          *       number of resolvers. The RFC states that the one to expire
802          *       first of the existing servers should be removed.
803          */
804         if (new_servers->len) {
805                 g_array_prepend_vals (device->rdnss_servers,
806                                       new_servers->data, new_servers->len);
807                 changed = TRUE;
808         }
809
810         g_array_free (new_servers, TRUE);
811
812         /* Timeouts may have changed even if IPs didn't */
813         set_rdnss_timeout (device);
814
815         return changed;
816 }
817
818 static const char *
819 parse_dnssl_domain (const unsigned char *buffer, size_t maxlen)
820 {
821         static char domain[256];
822         size_t label_len;
823
824         domain[0] = '\0';
825
826         while (maxlen > 0) {
827                 label_len = *buffer;
828                 buffer++;
829                 maxlen--;
830
831                 if (label_len == 0)
832                         return domain;
833
834                 if (label_len > maxlen)
835                         return NULL;
836                 if ((sizeof (domain) - strlen (domain)) < (label_len + 2))
837                         return NULL;
838
839                 if (domain[0] != '\0')
840                         strcat (domain, ".");
841                 strncat (domain, (const char *)buffer, label_len);
842                 buffer += label_len;
843                 maxlen -= label_len;
844         }
845
846         return NULL;
847 }
848
849 static gboolean
850 process_nduseropt_dnssl (NMIP6Device *device, struct nd_opt_hdr *opt)
851 {
852         size_t opt_len;
853         struct nd_opt_dnssl *dnssl_opt;
854         unsigned char *opt_ptr;
855         time_t now = time (NULL);
856         GArray *new_domains;
857         NMIP6DNSSL domain, *cur_domain;
858         gboolean changed;
859         guint i;
860
861         opt_len = opt->nd_opt_len;
862
863         if (opt_len < 2)
864                 return FALSE;
865
866         dnssl_opt = (struct nd_opt_dnssl *) opt;
867
868         opt_ptr = (unsigned char *)(dnssl_opt + 1);
869         opt_len = (opt_len - 1) * 8; /* prefer bytes for later handling */
870
871         new_domains = g_array_new (FALSE, FALSE, sizeof (NMIP6DNSSL));
872
873         changed = FALSE;
874
875         /* Pad the DNS server expiry somewhat to give a bit of slack in cases
876          * where one RA gets lost or something (which can happen on unreliable
877          * links like wifi where certain types of frames are not retransmitted).
878          * Note that 0 has special meaning and is therefore not adjusted.
879          */
880         domain.expires = ntohl (dnssl_opt->nd_opt_dnssl_lifetime);
881         if (domain.expires > 0)
882                 domain.expires += now + 10;
883
884         while (opt_len) {
885                 const char *domain_str;
886
887                 domain_str = parse_dnssl_domain (opt_ptr, opt_len);
888                 if (domain_str == NULL) {
889                         nm_log_dbg (LOGD_IP6, "(%s): invalid DNSSL option, parsing aborted",
890                                     device->iface);
891                         break;
892                 }
893
894                 /* The DNSSL encoding of domains happen to occupy the same size
895                  * as the length of the resulting string, including terminating
896                  * null. */
897                 opt_ptr += strlen (domain_str) + 1;
898                 opt_len -= strlen (domain_str) + 1;
899
900                 /* Ignore empty domains. They're probably just padding... */
901                 if (domain_str[0] == '\0')
902                         continue;
903
904                 /* Update cached domain information if we've seen this domain before */
905                 for (i = 0; i < device->dnssl_domains->len; i++) {
906                         cur_domain = &(g_array_index (device->dnssl_domains, NMIP6DNSSL, i));
907
908                         if (strcmp (domain_str, cur_domain->domain) != 0)
909                                 continue;
910
911                         cur_domain->expires = domain.expires;
912
913                         if (domain.expires > 0) {
914                                 nm_log_dbg (LOGD_IP6, "(%s): refreshing RA-provided domain %s (expires in %ld seconds)",
915                                             device->iface, domain_str,
916                                             domain.expires - now);
917                                 break;
918                         }
919
920                         nm_log_dbg (LOGD_IP6, "(%s): removing RA-provided domain %s on router request",
921                                     device->iface, domain_str);
922
923                         g_array_remove_index (device->dnssl_domains, i);
924                         changed = TRUE;
925                         break;
926                 }
927
928                 if (domain.expires == 0)
929                         continue;
930                 if (i < device->dnssl_domains->len)
931                         continue;
932
933                 nm_log_dbg (LOGD_IP6, "(%s): found RA-provided domain %s (expires in %ld seconds)",
934                             device->iface, domain_str, domain.expires - now);
935
936                 g_assert (strlen (domain_str) < sizeof (domain.domain));
937                 strcpy (domain.domain, domain_str);
938                 g_array_append_val (new_domains, domain);
939         }
940
941         /* New domains must be added in the order they are listed in the
942          * RA option and before any existing domains.
943          *
944          * Note: This is the place to remove domains if we want to cap the
945          *       number of domains. The RFC states that the one to expire
946          *       first of the existing domains should be removed.
947          */
948         if (new_domains->len) {
949                 g_array_prepend_vals (device->dnssl_domains,
950                                       new_domains->data, new_domains->len);
951                 changed = TRUE;
952         }
953
954         g_array_free (new_domains, TRUE);
955
956         /* Timeouts may have changed even if domains didn't */
957         set_dnssl_timeout (device);
958
959         return changed;
960 }
961
962 static NMIP6Device *
963 process_nduseropt (NMIP6Manager *manager, struct nl_msg *msg)
964 {
965         NMIP6Device *device;
966         struct nduseroptmsg *ndmsg;
967         struct nd_opt_hdr *opt;
968         guint opts_len;
969         gboolean changed = FALSE;
970
971         nm_log_dbg (LOGD_IP6, "processing netlink nduseropt message");
972
973         ndmsg = (struct nduseroptmsg *) NLMSG_DATA (nlmsg_hdr (msg));
974
975         if (!nlmsg_valid_hdr (nlmsg_hdr (msg), sizeof (*ndmsg)) ||
976             nlmsg_datalen (nlmsg_hdr (msg)) <
977                 (ndmsg->nduseropt_opts_len + sizeof (*ndmsg))) {
978                 nm_log_dbg (LOGD_IP6, "ignoring invalid nduseropt message");
979                 return NULL;
980         }
981
982         if (ndmsg->nduseropt_family != AF_INET6 ||
983                 ndmsg->nduseropt_icmp_type != ND_ROUTER_ADVERT ||
984                 ndmsg->nduseropt_icmp_code != 0) {
985                 nm_log_dbg (LOGD_IP6, "ignoring non-Router Advertisement message");
986                 return NULL;
987         }
988
989         device = nm_ip6_manager_get_device (manager, ndmsg->nduseropt_ifindex);
990         if (!device) {
991                 nm_log_dbg (LOGD_IP6, "ignoring message for unknown device");
992                 return NULL;
993         }
994
995         opt = (struct nd_opt_hdr *) (ndmsg + 1);
996         opts_len = ndmsg->nduseropt_opts_len;
997
998         while (opts_len >= sizeof (struct nd_opt_hdr)) {
999                 size_t nd_opt_len = opt->nd_opt_len;
1000
1001                 if (nd_opt_len == 0 || opts_len < (nd_opt_len << 3))
1002                         break;
1003
1004                 switch (opt->nd_opt_type) {
1005                 case ND_OPT_RDNSS:
1006                         changed = process_nduseropt_rdnss (device, opt);
1007                         break;
1008                 case ND_OPT_DNSSL:
1009                         changed = process_nduseropt_dnssl (device, opt);
1010                         break;
1011                 }
1012
1013                 opts_len -= opt->nd_opt_len << 3;
1014                 opt = (struct nd_opt_hdr *) ((uint8_t *) opt + (opt->nd_opt_len << 3));
1015         }
1016
1017         if (changed)
1018                 return device;
1019         else
1020                 return NULL;
1021 }
1022
1023 static struct nla_policy link_policy[IFLA_MAX + 1] = {
1024         [IFLA_PROTINFO] = { .type = NLA_NESTED },
1025 };
1026
1027 static struct nla_policy link_prot_policy[IFLA_INET6_MAX + 1] = {
1028         [IFLA_INET6_FLAGS]      = { .type = NLA_U32 },
1029 };
1030
1031 static char *
1032 ra_flags_to_string (guint32 ra_flags)
1033 {
1034         GString *s = g_string_sized_new (20);
1035
1036         g_string_append (s, " (");
1037         if (ra_flags & IF_RS_SENT)
1038                 g_string_append_c (s, 'S');
1039
1040         if (ra_flags & IF_RA_RCVD)
1041                 g_string_append_c (s, 'R');
1042
1043         if (ra_flags & IF_RA_OTHERCONF)
1044                 g_string_append_c (s, 'O');
1045
1046         if (ra_flags & IF_RA_MANAGED)
1047                 g_string_append_c (s, 'M');
1048
1049         g_string_append_c (s, ')');
1050         return g_string_free (s, FALSE);
1051 }
1052
1053 static NMIP6Device *
1054 process_newlink (NMIP6Manager *manager, struct nl_msg *msg)
1055 {
1056         struct nlmsghdr *hdr = nlmsg_hdr (msg);
1057         struct ifinfomsg *ifi;
1058         NMIP6Device *device;
1059         struct nlattr *tb[IFLA_MAX + 1];
1060         struct nlattr *pi[IFLA_INET6_MAX + 1];
1061         int err;
1062         char *flags_str = NULL;
1063
1064         /* FIXME: we have to do this manually for now since libnl doesn't yet
1065          * support the IFLA_PROTINFO attribute of NEWLINK messages.  When it does,
1066          * we can get rid of this function and just grab IFLA_PROTINFO from
1067          * nm_ip6_device_sync_from_netlink(), then get the IFLA_INET6_FLAGS out of
1068          * the PROTINFO.
1069          */
1070         err = nlmsg_parse (hdr, sizeof (*ifi), tb, IFLA_MAX, link_policy);
1071         if (err < 0) {
1072                 nm_log_dbg (LOGD_IP6, "ignoring invalid newlink netlink message "
1073                                       "while parsing PROTINFO attribute");
1074                 return NULL;
1075         }
1076
1077         ifi = nlmsg_data (hdr);
1078         if (ifi->ifi_family != AF_INET6) {
1079                 nm_log_dbg (LOGD_IP6, "ignoring netlink message family %d", ifi->ifi_family);
1080                 return NULL;
1081         }
1082
1083         device = nm_ip6_manager_get_device (manager, ifi->ifi_index);
1084         if (!device || device->addrconf_complete) {
1085                 nm_log_dbg (LOGD_IP6, "(%s): ignoring unknown or completed device",
1086                             device ? device->iface : "(none)");
1087                 return NULL;
1088         }
1089
1090         if (!tb[IFLA_PROTINFO]) {
1091                 nm_log_dbg (LOGD_IP6, "(%s): message had no PROTINFO attribute", device->iface);
1092                 return NULL;
1093         }
1094
1095         err = nla_parse_nested (pi, IFLA_INET6_MAX, tb[IFLA_PROTINFO], link_prot_policy);
1096         if (err < 0) {
1097                 nm_log_dbg (LOGD_IP6, "(%s): error parsing PROTINFO flags", device->iface);
1098                 return NULL;
1099         }
1100         if (!pi[IFLA_INET6_FLAGS]) {
1101                 nm_log_dbg (LOGD_IP6, "(%s): message had no PROTINFO flags", device->iface);
1102                 return NULL;
1103         }
1104
1105         device->ra_flags = nla_get_u32 (pi[IFLA_INET6_FLAGS]);
1106
1107         if (nm_logging_level_enabled (LOGL_DEBUG))
1108                 flags_str = ra_flags_to_string (device->ra_flags);
1109         nm_log_dbg (LOGD_IP6, "(%s): got IPv6 flags 0x%X%s",
1110                     device->iface, device->ra_flags, flags_str ? flags_str : "");
1111         g_free (flags_str);
1112
1113         return device;
1114 }
1115
1116 static void
1117 netlink_notification (NMNetlinkMonitor *monitor, struct nl_msg *msg, gpointer user_data)
1118 {
1119         NMIP6Manager *manager = (NMIP6Manager *) user_data;
1120         NMIP6Device *device;
1121         struct nlmsghdr *hdr;
1122
1123         hdr = nlmsg_hdr (msg);
1124         nm_log_dbg (LOGD_HW, "netlink event type %d", hdr->nlmsg_type);
1125         switch (hdr->nlmsg_type) {
1126         case RTM_NEWADDR:
1127         case RTM_DELADDR:
1128                 device = process_address_change (manager, msg);
1129                 break;
1130         case RTM_NEWROUTE:
1131         case RTM_DELROUTE:
1132                 device = process_route_change (manager, msg);
1133                 break;
1134         case RTM_NEWNDUSEROPT:
1135                 device = process_nduseropt (manager, msg);
1136                 break;
1137         case RTM_NEWLINK:
1138                 device = process_newlink (manager, msg);
1139                 break;
1140         default:
1141                 return;
1142         }
1143
1144         if (device) {
1145                 nm_ip6_device_sync_from_netlink (device);
1146         }
1147 }
1148
1149 gboolean
1150 nm_ip6_manager_prepare_interface (NMIP6Manager *manager,
1151                                   int ifindex,
1152                                   NMSettingIP6Config *s_ip6,
1153                                   const char *accept_ra_path)
1154 {
1155         NMIP6ManagerPrivate *priv;
1156         NMIP6Device *device;
1157         const char *method = NULL;
1158
1159         g_return_val_if_fail (NM_IS_IP6_MANAGER (manager), FALSE);
1160         g_return_val_if_fail (ifindex > 0, FALSE);
1161
1162         priv = NM_IP6_MANAGER_GET_PRIVATE (manager);
1163
1164         device = nm_ip6_device_new (manager, ifindex);
1165         g_return_val_if_fail (device != NULL, FALSE);
1166         g_return_val_if_fail (   strchr (device->iface, '/') == NULL
1167                               && strcmp (device->iface, "all") != 0
1168                               && strcmp (device->iface, "default") != 0,
1169                               FALSE);
1170
1171         if (s_ip6)
1172                 method = nm_setting_ip6_config_get_method (s_ip6);
1173         if (!method)
1174                 method = NM_SETTING_IP6_CONFIG_METHOD_AUTO;
1175
1176         /* Establish target state and turn router advertisement acceptance on or off */
1177         if (!strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL)) {
1178                 device->target_state = NM_IP6_DEVICE_GOT_LINK_LOCAL;
1179                 nm_utils_do_sysctl (accept_ra_path, "0\n");
1180         } else {
1181                 device->target_state = NM_IP6_DEVICE_GOT_ADDRESS;
1182                 nm_utils_do_sysctl (accept_ra_path, "2\n");
1183         }
1184
1185         return TRUE;
1186 }
1187
1188 static gboolean
1189 poll_ip6_flags (gpointer user_data)
1190 {
1191         nm_netlink_monitor_request_ip6_info (NM_NETLINK_MONITOR (user_data), NULL);
1192         return TRUE;
1193 }
1194
1195 void
1196 nm_ip6_manager_begin_addrconf (NMIP6Manager *manager, int ifindex)
1197 {
1198         NMIP6ManagerPrivate *priv;
1199         NMIP6Device *device;
1200         CallbackInfo *info;
1201
1202         g_return_if_fail (NM_IS_IP6_MANAGER (manager));
1203         g_return_if_fail (ifindex > 0);
1204
1205         priv = NM_IP6_MANAGER_GET_PRIVATE (manager);
1206
1207         device = (NMIP6Device *) g_hash_table_lookup (priv->devices, GINT_TO_POINTER (ifindex));
1208         g_return_if_fail (device != NULL);
1209
1210         nm_log_info (LOGD_IP6, "Activation (%s) Beginning IP6 addrconf.", device->iface);
1211
1212         device->addrconf_complete = FALSE;
1213         device->ra_flags = 0;
1214
1215         /* Set up a timeout on the transaction to kill it after the timeout */
1216         info = callback_info_new (device, 0, FALSE);
1217         device->finish_addrconf_id = g_timeout_add_seconds_full (G_PRIORITY_DEFAULT,
1218                                                                  NM_IP6_TIMEOUT,
1219                                                                  finish_addrconf,
1220                                                                  info,
1221                                                                  (GDestroyNotify) g_free);
1222
1223         /* Bounce IPv6 on the interface to ensure the kernel will start looking for
1224          * new RAs; there doesn't seem to be a better way to do this right now.
1225          */
1226         if (device->target_state >= NM_IP6_DEVICE_GOT_ADDRESS) {
1227                 nm_utils_do_sysctl (device->disable_ip6_path, "1\n");
1228                 g_usleep (200);
1229                 nm_utils_do_sysctl (device->disable_ip6_path, "0\n");
1230         }
1231
1232         device->ip6flags_poll_id = g_timeout_add_seconds (1, poll_ip6_flags, priv->monitor);
1233
1234         /* Kick off the initial IPv6 flags request */
1235         nm_netlink_monitor_request_ip6_info (priv->monitor, NULL);
1236
1237         /* Sync flags, etc, from netlink; this will also notice if the
1238          * device is already fully configured and schedule the
1239          * ADDRCONF_COMPLETE signal in that case.
1240          */
1241         nm_ip6_device_sync_from_netlink (device);
1242 }
1243
1244 void
1245 nm_ip6_manager_cancel_addrconf (NMIP6Manager *manager, int ifindex)
1246 {
1247         g_return_if_fail (NM_IS_IP6_MANAGER (manager));
1248         g_return_if_fail (ifindex > 0);
1249
1250         g_hash_table_remove (NM_IP6_MANAGER_GET_PRIVATE (manager)->devices,
1251                              GINT_TO_POINTER (ifindex));
1252 }
1253
1254 #define FIRST_ROUTE(m) ((struct rtnl_route *) nl_cache_get_first (m))
1255 #define NEXT_ROUTE(m) ((struct rtnl_route *) nl_cache_get_next ((struct nl_object *) m))
1256
1257 #define FIRST_ADDR(m) ((struct rtnl_addr *) nl_cache_get_first (m))
1258 #define NEXT_ADDR(m) ((struct rtnl_addr *) nl_cache_get_next ((struct nl_object *) m))
1259
1260 NMIP6Config *
1261 nm_ip6_manager_get_ip6_config (NMIP6Manager *manager, int ifindex)
1262 {
1263         NMIP6ManagerPrivate *priv;
1264         NMIP6Device *device;
1265         NMIP6Config *config;
1266         struct rtnl_addr *rtnladdr;
1267         struct nl_addr *nladdr;
1268         struct in6_addr *addr;
1269         NMIP6Address *ip6addr;
1270         struct rtnl_route *rtnlroute;
1271         struct nl_addr *nldest, *nlgateway;
1272         struct in6_addr *dest, *gateway;
1273         uint32_t metric;
1274         NMIP6Route *ip6route;
1275         int i;
1276
1277         g_return_val_if_fail (NM_IS_IP6_MANAGER (manager), NULL);
1278         g_return_val_if_fail (ifindex > 0, NULL);
1279
1280         priv = NM_IP6_MANAGER_GET_PRIVATE (manager);
1281
1282         device = (NMIP6Device *) g_hash_table_lookup (priv->devices,
1283                                                       GINT_TO_POINTER (ifindex));
1284         if (!device) {
1285                 nm_log_warn (LOGD_IP6, "(%d): addrconf not started.", ifindex);
1286                 return NULL;
1287         }
1288
1289         config = nm_ip6_config_new ();
1290         if (!config) {
1291                 nm_log_err (LOGD_IP6, "(%s): out of memory creating IP6 config object.",
1292                             device->iface);
1293                 return NULL;
1294         }
1295
1296         /* Make sure we refill the route and address caches, otherwise we won't get
1297          * up-to-date information here since the netlink route/addr change messages
1298          * may be lagging a bit.
1299          */
1300         nl_cache_refill (priv->nlh, priv->route_cache);
1301         nl_cache_refill (priv->nlh, priv->addr_cache);
1302
1303         /* Add routes */
1304         for (rtnlroute = FIRST_ROUTE (priv->route_cache); rtnlroute; rtnlroute = NEXT_ROUTE (rtnlroute)) {
1305                 /* Make sure it's an IPv6 route for this device */
1306                 if (rtnl_route_get_oif (rtnlroute) != device->ifindex)
1307                         continue;
1308                 if (rtnl_route_get_family (rtnlroute) != AF_INET6)
1309                         continue;
1310
1311                 nldest = rtnl_route_get_dst (rtnlroute);
1312                 if (!nldest || nl_addr_get_family (nldest) != AF_INET6)
1313                         continue;
1314                 dest = nl_addr_get_binary_addr (nldest);
1315
1316                 nlgateway = rtnl_route_get_gateway (rtnlroute);
1317                 if (!nlgateway || nl_addr_get_family (nlgateway) != AF_INET6)
1318                         continue;
1319                 gateway = nl_addr_get_binary_addr (nlgateway);
1320
1321                 if (rtnl_route_get_dst_len (rtnlroute) == 0) {
1322                         /* Default gateway route; don't add to normal routes but to each address */
1323                         if (!nm_ip6_config_get_gateway (config)) {
1324                                 nm_ip6_config_set_gateway (config, gateway);
1325                         }
1326                         continue;
1327                 }
1328
1329                 /* Also ignore link-local routes where the destination and gateway are
1330                  * the same, which apparently get added by the kernel but return -EINVAL
1331                  * when we try to add them via netlink.
1332                  */
1333                 if (gateway && IN6_ARE_ADDR_EQUAL (dest, gateway))
1334                         continue;
1335
1336                 ip6route = nm_ip6_route_new ();
1337                 nm_ip6_route_set_dest (ip6route, dest);
1338                 nm_ip6_route_set_prefix (ip6route, rtnl_route_get_dst_len (rtnlroute));
1339                 nm_ip6_route_set_next_hop (ip6route, gateway);
1340                 rtnl_route_get_metric(rtnlroute, 1, &metric);
1341                 if (metric != UINT_MAX)
1342                         nm_ip6_route_set_metric (ip6route, metric);
1343                 nm_ip6_config_take_route (config, ip6route);
1344         }
1345
1346         /* Add addresses */
1347         for (rtnladdr = FIRST_ADDR (priv->addr_cache); rtnladdr; rtnladdr = NEXT_ADDR (rtnladdr)) {
1348                 if (rtnl_addr_get_ifindex (rtnladdr) != device->ifindex)
1349                         continue;
1350
1351                 nladdr = rtnl_addr_get_local (rtnladdr);
1352                 if (!nladdr || nl_addr_get_family (nladdr) != AF_INET6)
1353                         continue;
1354
1355                 addr = nl_addr_get_binary_addr (nladdr);
1356                 ip6addr = nm_ip6_address_new ();
1357                 nm_ip6_address_set_prefix (ip6addr, rtnl_addr_get_prefixlen (rtnladdr));
1358                 nm_ip6_address_set_address (ip6addr, addr);
1359                 nm_ip6_config_take_address (config, ip6addr);
1360                 gateway = nm_ip6_config_get_gateway (config);
1361                 if (gateway)
1362                         nm_ip6_address_set_gateway (ip6addr, gateway);
1363         }
1364
1365         /* Add DNS servers */
1366         if (device->rdnss_servers) {
1367                 NMIP6RDNSS *rdnss = (NMIP6RDNSS *)(device->rdnss_servers->data);
1368
1369                 for (i = 0; i < device->rdnss_servers->len; i++)
1370                         nm_ip6_config_add_nameserver (config, &rdnss[i].addr);
1371         }
1372
1373         /* Add DNS domains */
1374         if (device->dnssl_domains) {
1375                 NMIP6DNSSL *dnssl = (NMIP6DNSSL *)(device->dnssl_domains->data);
1376
1377                 for (i = 0; i < device->dnssl_domains->len; i++)
1378                         nm_ip6_config_add_domain (config, dnssl[i].domain);
1379         }
1380
1381         return config;
1382 }
1383
1384 /******************************************************************/
1385
1386 static NMIP6Manager *
1387 nm_ip6_manager_new (void)
1388 {
1389         NMIP6Manager *manager;
1390         NMIP6ManagerPrivate *priv;
1391
1392         manager = g_object_new (NM_TYPE_IP6_MANAGER, NULL);
1393         priv = NM_IP6_MANAGER_GET_PRIVATE (manager);
1394
1395         if (!priv->devices) {
1396                 nm_log_err (LOGD_IP6, "not enough memory to initialize IP6 manager tables");
1397                 g_object_unref (manager);
1398                 manager = NULL;
1399         }
1400
1401         return manager;
1402 }
1403
1404 static NMIP6Manager *singleton = NULL;
1405
1406 NMIP6Manager *
1407 nm_ip6_manager_get (void)
1408 {
1409         if (!singleton) {
1410                 singleton = nm_ip6_manager_new ();
1411                 g_assert (singleton);
1412         } else
1413                 g_object_ref (singleton);
1414
1415         return singleton;
1416 }
1417
1418 static void
1419 nm_ip6_manager_init (NMIP6Manager *manager)
1420 {
1421         NMIP6ManagerPrivate *priv = NM_IP6_MANAGER_GET_PRIVATE (manager);
1422
1423         priv->devices = g_hash_table_new_full (g_direct_hash, g_direct_equal,
1424                                                NULL,
1425                                                (GDestroyNotify) nm_ip6_device_destroy);
1426
1427         priv->monitor = nm_netlink_monitor_get ();
1428         nm_netlink_monitor_subscribe (priv->monitor, RTNLGRP_IPV6_IFADDR, NULL);
1429         nm_netlink_monitor_subscribe (priv->monitor, RTNLGRP_IPV6_PREFIX, NULL);
1430         nm_netlink_monitor_subscribe (priv->monitor, RTNLGRP_IPV6_ROUTE, NULL);
1431         nm_netlink_monitor_subscribe (priv->monitor, RTNLGRP_ND_USEROPT, NULL);
1432         nm_netlink_monitor_subscribe (priv->monitor, RTNLGRP_LINK, NULL);
1433
1434         priv->netlink_id = g_signal_connect (priv->monitor, "notification",
1435                                              G_CALLBACK (netlink_notification), manager);
1436
1437         priv->nlh = nm_netlink_get_default_handle ();
1438         rtnl_addr_alloc_cache (priv->nlh, &priv->addr_cache);
1439         g_warn_if_fail (priv->addr_cache != NULL);
1440         rtnl_route_alloc_cache (priv->nlh, NETLINK_ROUTE, NL_AUTO_PROVIDE, &priv->route_cache);
1441         g_warn_if_fail (priv->route_cache != NULL);
1442 }
1443
1444 static void
1445 finalize (GObject *object)
1446 {
1447         NMIP6ManagerPrivate *priv = NM_IP6_MANAGER_GET_PRIVATE (object);
1448
1449         g_signal_handler_disconnect (priv->monitor, priv->netlink_id);
1450
1451         g_hash_table_destroy (priv->devices);
1452         g_object_unref (priv->monitor);
1453         nl_cache_free (priv->addr_cache);
1454         nl_cache_free (priv->route_cache);
1455
1456         singleton = NULL;
1457
1458         G_OBJECT_CLASS (nm_ip6_manager_parent_class)->finalize (object);
1459 }
1460
1461 static void
1462 nm_ip6_manager_class_init (NMIP6ManagerClass *manager_class)
1463 {
1464         GObjectClass *object_class = G_OBJECT_CLASS (manager_class);
1465
1466         g_type_class_add_private (manager_class, sizeof (NMIP6ManagerPrivate));
1467
1468         /* virtual methods */
1469         object_class->finalize = finalize;
1470
1471         /* signals */
1472         signals[ADDRCONF_COMPLETE] =
1473                 g_signal_new ("addrconf-complete",
1474                                           G_OBJECT_CLASS_TYPE (object_class),
1475                                           G_SIGNAL_RUN_FIRST,
1476                                           G_STRUCT_OFFSET (NMIP6ManagerClass, addrconf_complete),
1477                                           NULL, NULL,
1478                                           _nm_marshal_VOID__INT_UINT_BOOLEAN,
1479                                           G_TYPE_NONE, 3, G_TYPE_INT, G_TYPE_UINT, G_TYPE_BOOLEAN);
1480
1481         signals[CONFIG_CHANGED] =
1482                 g_signal_new ("config-changed",
1483                                           G_OBJECT_CLASS_TYPE (object_class),
1484                                           G_SIGNAL_RUN_FIRST,
1485                                           G_STRUCT_OFFSET (NMIP6ManagerClass, config_changed),
1486                                           NULL, NULL,
1487                                           _nm_marshal_VOID__INT_UINT_BOOLEAN,
1488                                           G_TYPE_NONE, 3, G_TYPE_INT, G_TYPE_UINT, G_TYPE_BOOLEAN);
1489 }
1490