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