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