e9a60ee8c4c1836eedf7a00615daae064145758c
[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 "NetworkManagerUtils.h"
31 #include "nm-marshal.h"
32 #include "nm-logging.h"
33 #include "nm-system.h"
34
35 /* Pre-DHCP addrconf timeout, in seconds */
36 #define NM_IP6_TIMEOUT 20
37
38 /* FIXME? Stolen from the kernel sources */
39 #define IF_RA_OTHERCONF 0x80
40 #define IF_RA_MANAGED   0x40
41 #define IF_RA_RCVD      0x20
42 #define IF_RS_SENT      0x10
43
44 typedef struct {
45         NMNetlinkMonitor *monitor;
46         GHashTable *devices;
47
48         struct nl_handle *nlh;
49         struct nl_cache *addr_cache, *route_cache;
50
51         guint netlink_id;
52 } NMIP6ManagerPrivate;
53
54 #define NM_IP6_MANAGER_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), NM_TYPE_IP6_MANAGER, NMIP6ManagerPrivate))
55
56 G_DEFINE_TYPE (NMIP6Manager, nm_ip6_manager, G_TYPE_OBJECT)
57
58 enum {
59         ADDRCONF_COMPLETE,
60         CONFIG_CHANGED,
61         LAST_SIGNAL
62 };
63
64 static guint signals[LAST_SIGNAL] = { 0 };
65
66 typedef enum {
67         NM_IP6_DEVICE_UNCONFIGURED,
68         NM_IP6_DEVICE_GOT_LINK_LOCAL,
69         NM_IP6_DEVICE_GOT_ROUTER_ADVERTISEMENT,
70         NM_IP6_DEVICE_GOT_ADDRESS,
71         NM_IP6_DEVICE_TIMED_OUT
72 } NMIP6DeviceState;
73
74 typedef struct {
75         struct in6_addr addr;
76         time_t expires;
77 } NMIP6RDNSS;
78
79 /******************************************************************/
80
81 typedef struct {
82         NMIP6Manager *manager;
83         char *iface;
84         int ifindex;
85
86         char *accept_ra_path;
87         gboolean accept_ra_save_valid;
88         guint32 accept_ra_save;
89
90         char *disable_ip6_path;
91         gboolean disable_ip6_save_valid;
92         guint32 disable_ip6_save;
93
94         guint finish_addrconf_id;
95         guint config_changed_id;
96
97         NMIP6DeviceState state;
98         NMIP6DeviceState target_state;
99         gboolean addrconf_complete;
100
101         GArray *rdnss_servers;
102         guint rdnss_timeout_id;
103
104         guint ip6flags_poll_id;
105
106         guint32 ra_flags;
107 } NMIP6Device;
108
109 static void
110 nm_ip6_device_destroy (NMIP6Device *device)
111 {
112         g_return_if_fail (device != NULL);
113
114         /* reset the saved RA value */
115         if (device->accept_ra_save_valid) {
116                 nm_utils_do_sysctl (device->accept_ra_path,
117                                     device->accept_ra_save ? "1\n" : "0\n");
118         }
119
120         /* reset the saved IPv6 value */
121         if (device->disable_ip6_save_valid) {
122                 nm_utils_do_sysctl (device->disable_ip6_path,
123                                     device->disable_ip6_save ? "1\n" : "0\n");
124         }
125
126         if (device->finish_addrconf_id)
127                 g_source_remove (device->finish_addrconf_id);
128         if (device->config_changed_id)
129                 g_source_remove (device->config_changed_id);
130         g_free (device->iface);
131         if (device->rdnss_servers)
132                 g_array_free (device->rdnss_servers, TRUE);
133         if (device->rdnss_timeout_id)
134                 g_source_remove (device->rdnss_timeout_id);
135         if (device->ip6flags_poll_id)
136                 g_source_remove (device->ip6flags_poll_id);
137
138         g_free (device->accept_ra_path);
139         g_slice_free (NMIP6Device, device);
140 }
141
142 static gboolean
143 get_proc_sys_net_value (const char *path, const char *iface, guint32 *out_value)
144 {
145         GError *error = NULL;
146         char *contents = NULL;
147         gboolean success = FALSE;
148         long int tmp;
149
150         if (!g_file_get_contents (path, &contents, NULL, &error)) {
151                 nm_log_warn (LOGD_IP6, "(%s): error reading %s: (%d) %s",
152                              iface, path,
153                              error ? error->code : -1,
154                              error && error->message ? error->message : "(unknown)");
155                 g_clear_error (&error);
156         } else {
157                 errno = 0;
158                 tmp = strtol (contents, NULL, 10);
159                 if ((errno == 0) && (tmp == 0 || tmp == 1)) {
160                         *out_value = (guint32) tmp;
161                         success = TRUE;
162                 }
163                 g_free (contents);
164         }
165
166         return success;
167 }
168
169 static NMIP6Device *
170 nm_ip6_device_new (NMIP6Manager *manager, int ifindex)
171 {
172         NMIP6ManagerPrivate *priv = NM_IP6_MANAGER_GET_PRIVATE (manager);
173         NMIP6Device *device;
174
175         g_return_val_if_fail (ifindex > 0, NULL);
176
177         device = g_slice_new0 (NMIP6Device);
178         if (!device) {
179                 nm_log_err (LOGD_IP6, "(%d): out of memory creating IP6 addrconf object.",
180                             ifindex);
181                 return NULL;
182         }
183
184         device->ifindex = ifindex;
185         device->iface = g_strdup (nm_netlink_index_to_iface (ifindex));
186         if (!device->iface) {
187                 nm_log_err (LOGD_IP6, "(%d): could not find interface name from index.",
188                             ifindex);
189                 goto error;
190         }
191
192         device->manager = manager;
193
194         device->rdnss_servers = g_array_new (FALSE, FALSE, sizeof (NMIP6RDNSS));
195
196         g_hash_table_replace (priv->devices, GINT_TO_POINTER (device->ifindex), device);
197
198         /* Grab the original value of "accept_ra" so we can restore it when the
199          * device is taken down.
200          */
201         device->accept_ra_path = g_strdup_printf ("/proc/sys/net/ipv6/conf/%s/accept_ra",
202                                                   device->iface);
203         g_assert (device->accept_ra_path);
204         device->accept_ra_save_valid = get_proc_sys_net_value (device->accept_ra_path,
205                                                                device->iface,
206                                                                &device->accept_ra_save);
207
208         /* and the original value of IPv6 enable/disable */
209         device->disable_ip6_path = g_strdup_printf ("/proc/sys/net/ipv6/conf/%s/disable_ipv6",
210                                                     device->iface);
211         g_assert (device->disable_ip6_path);
212         device->disable_ip6_save_valid = get_proc_sys_net_value (device->disable_ip6_path,
213                                                                  device->iface,
214                                                                  &device->disable_ip6_save);
215
216         return device;
217
218 error:
219         nm_ip6_device_destroy (device);
220         return NULL;
221 }
222
223 static NMIP6Device *
224 nm_ip6_manager_get_device (NMIP6Manager *manager, int ifindex)
225 {
226         NMIP6ManagerPrivate *priv;
227
228         g_return_val_if_fail (manager != NULL, NULL);
229         g_return_val_if_fail (NM_IS_IP6_MANAGER (manager), NULL);
230
231         priv = NM_IP6_MANAGER_GET_PRIVATE (manager);
232         return g_hash_table_lookup (priv->devices, GINT_TO_POINTER (ifindex));
233 }
234
235 /******************************************************************/
236
237 typedef struct {
238         NMIP6Device *device;
239         guint dhcp_opts;
240         gboolean success;
241 } CallbackInfo;
242
243 static gboolean
244 finish_addrconf (gpointer user_data)
245 {
246         CallbackInfo *info = user_data;
247         NMIP6Device *device = info->device;
248         NMIP6Manager *manager = device->manager;
249         int ifindex;
250
251         device->finish_addrconf_id = 0;
252         device->addrconf_complete = TRUE;
253         ifindex = device->ifindex;
254
255         /* We're done, stop polling IPv6 flags */
256         if (device->ip6flags_poll_id) {
257                 g_source_remove (device->ip6flags_poll_id);
258                 device->ip6flags_poll_id = 0;
259         }
260
261         /* And tell listeners that addrconf is complete */
262         if (info->success) {
263                 g_signal_emit (manager, signals[ADDRCONF_COMPLETE], 0,
264                                ifindex, info->dhcp_opts, TRUE);
265         } else {
266                 nm_log_info (LOGD_IP6, "(%s): IP6 addrconf timed out or failed.",
267                              device->iface);
268
269                 nm_ip6_manager_cancel_addrconf (manager, ifindex);
270                 g_signal_emit (manager, signals[ADDRCONF_COMPLETE], 0,
271                                ifindex, info->dhcp_opts, FALSE);
272         }
273
274         return FALSE;
275 }
276
277 static gboolean
278 emit_config_changed (gpointer user_data)
279 {
280         CallbackInfo *info = user_data;
281         NMIP6Device *device = info->device;
282         NMIP6Manager *manager = device->manager;
283
284         device->config_changed_id = 0;
285         g_signal_emit (manager, signals[CONFIG_CHANGED], 0, device->ifindex, info->dhcp_opts);
286         return FALSE;
287 }
288
289 static void set_rdnss_timeout (NMIP6Device *device);
290
291 static gboolean
292 rdnss_expired (gpointer user_data)
293 {
294         NMIP6Device *device = user_data;
295         CallbackInfo info = { device, IP6_DHCP_OPT_NONE };
296
297         set_rdnss_timeout (device);
298         emit_config_changed (&info);
299         return FALSE;
300 }
301
302 static void
303 set_rdnss_timeout (NMIP6Device *device)
304 {
305         time_t expires = 0, now = time (NULL);
306         NMIP6RDNSS *rdnss;
307         int i;
308
309         if (device->rdnss_timeout_id) {
310                 g_source_remove (device->rdnss_timeout_id);
311                 device->rdnss_timeout_id = 0;
312         }
313
314         /* Find the soonest expiration time. */
315         for (i = 0; i < device->rdnss_servers->len; i++) {
316                 rdnss = &g_array_index (device->rdnss_servers, NMIP6RDNSS, i);
317                 if (rdnss->expires == 0)
318                         continue;
319
320                 /* If the entry has already expired, remove it; the "+ 1" is
321                  * because g_timeout_add_seconds() might fudge the timing a
322                  * bit.
323                  */
324                 if (rdnss->expires <= now + 1) {
325                         g_array_remove_index_fast (device->rdnss_servers, i--);
326                         continue;
327                 }
328
329                 if (!expires || rdnss->expires < expires)
330                         expires = rdnss->expires;
331         }
332
333         if (expires) {
334                 device->rdnss_timeout_id = g_timeout_add_seconds (expires - now,
335                                                                                                                   rdnss_expired,
336                                                                                                                   device);
337         }
338 }
339
340 static CallbackInfo *
341 callback_info_new (NMIP6Device *device, guint dhcp_opts, gboolean success)
342 {
343         CallbackInfo *info;
344
345         info = g_malloc0 (sizeof (CallbackInfo));
346         info->device = device;
347         info->dhcp_opts = dhcp_opts;
348         info->success = success;
349         return info;
350 }
351
352 static const char *
353 state_to_string (NMIP6DeviceState state)
354 {
355         switch (state) {
356         case NM_IP6_DEVICE_UNCONFIGURED:
357                 return "unconfigured";
358         case NM_IP6_DEVICE_GOT_LINK_LOCAL:
359                 return "got-link-local";
360         case NM_IP6_DEVICE_GOT_ROUTER_ADVERTISEMENT:
361                 return "got-ra";
362         case NM_IP6_DEVICE_GOT_ADDRESS:
363                 return "got-address";
364         case NM_IP6_DEVICE_TIMED_OUT:
365                 return "timed-out";
366         default:
367                 return "unknown";
368         }
369 }
370
371 static void
372 nm_ip6_device_sync_from_netlink (NMIP6Device *device, gboolean config_changed)
373 {
374         NMIP6Manager *manager = device->manager;
375         NMIP6ManagerPrivate *priv = NM_IP6_MANAGER_GET_PRIVATE (manager);
376         struct rtnl_addr *rtnladdr;
377         struct nl_addr *nladdr;
378         struct in6_addr *addr;
379         CallbackInfo *info;
380         guint dhcp_opts = IP6_DHCP_OPT_NONE;
381         gboolean found_linklocal = FALSE;
382
383         nm_log_dbg (LOGD_IP6, "(%s): syncing with netlink (ra_flags 0x%X) (state/target '%s'/'%s')",
384                     device->iface, device->ra_flags,
385                     state_to_string (device->state),
386                     state_to_string (device->target_state));
387
388         /* Look for any IPv6 addresses the kernel may have set for the device */
389         for (rtnladdr = (struct rtnl_addr *) nl_cache_get_first (priv->addr_cache);
390                  rtnladdr;
391                  rtnladdr = (struct rtnl_addr *) nl_cache_get_next ((struct nl_object *) rtnladdr)) {
392                 char buf[INET6_ADDRSTRLEN];
393
394                 if (rtnl_addr_get_ifindex (rtnladdr) != device->ifindex)
395                         continue;
396
397                 nladdr = rtnl_addr_get_local (rtnladdr);
398                 if (!nladdr || nl_addr_get_family (nladdr) != AF_INET6)
399                         continue;
400
401                 addr = nl_addr_get_binary_addr (nladdr);
402
403                 if (inet_ntop (AF_INET6, addr, buf, INET6_ADDRSTRLEN) > 0) {
404                         nm_log_dbg (LOGD_IP6, "(%s): netlink address: %s",
405                                     device->iface, buf);
406                 }
407
408                 if (IN6_IS_ADDR_LINKLOCAL (addr)) {
409                         if (device->state == NM_IP6_DEVICE_UNCONFIGURED)
410                                 device->state = NM_IP6_DEVICE_GOT_LINK_LOCAL;
411                         found_linklocal = TRUE;
412                 } else {
413                         if (device->state < NM_IP6_DEVICE_GOT_ADDRESS)
414                                 device->state = NM_IP6_DEVICE_GOT_ADDRESS;
415                 }
416         }
417
418         /* There might be a LL address hanging around on the interface from
419          * before in the initial run, but if it goes away later, make sure we
420          * regress from GOT_LINK_LOCAL back to UNCONFIGURED.
421          */
422         if ((device->state == NM_IP6_DEVICE_GOT_LINK_LOCAL) && !found_linklocal)
423                 device->state = NM_IP6_DEVICE_UNCONFIGURED;
424
425         nm_log_dbg (LOGD_IP6, "(%s): addresses synced (state %s)",
426                     device->iface, state_to_string (device->state));
427
428         /* We only care about router advertisements if we want a real IPv6 address */
429         if (device->target_state == NM_IP6_DEVICE_GOT_ADDRESS) {
430                 if (   (device->ra_flags & IF_RA_RCVD)
431                     && (device->state < NM_IP6_DEVICE_GOT_ROUTER_ADVERTISEMENT))
432                         device->state = NM_IP6_DEVICE_GOT_ROUTER_ADVERTISEMENT;
433
434                 if (device->ra_flags & IF_RA_MANAGED) {
435                         dhcp_opts = IP6_DHCP_OPT_MANAGED;
436                         nm_log_dbg (LOGD_IP6, "router advertisement deferred to DHCPv6");
437                 } else if (device->ra_flags & IF_RA_OTHERCONF) {
438                         dhcp_opts = IP6_DHCP_OPT_OTHERCONF;
439                         nm_log_dbg (LOGD_IP6, "router advertisement requests parallel DHCPv6");
440                 }
441         }
442
443         if (!device->addrconf_complete) {
444                 /* Managed mode (ie DHCP only) short-circuits automatic addrconf, so
445                  * we don't bother waiting for the device's target state to be reached
446                  * when the RA requests managed mode.
447                  */
448                 if (   (device->state >= device->target_state)
449                     || (dhcp_opts == IP6_DHCP_OPT_MANAGED)) {
450                         /* device->finish_addrconf_id may currently be a timeout
451                          * rather than an idle, so we remove the existing source.
452                          */
453                         if (device->finish_addrconf_id)
454                                 g_source_remove (device->finish_addrconf_id);
455
456                         nm_log_dbg (LOGD_IP6, "(%s): reached target state or Managed-mode requested (state '%s') (dhcp opts 0x%X)",
457                                     device->iface, state_to_string (device->state),
458                                     dhcp_opts);
459
460                         info = callback_info_new (device, dhcp_opts, TRUE);
461                         device->finish_addrconf_id = g_idle_add_full (G_PRIORITY_DEFAULT_IDLE,
462                                                                       finish_addrconf,
463                                                                       info,
464                                                                       (GDestroyNotify) g_free);
465                 }
466         } else if (config_changed) {
467                 if (!device->config_changed_id) {
468                         info = callback_info_new (device, dhcp_opts, TRUE);
469                         device->config_changed_id = g_idle_add_full (G_PRIORITY_DEFAULT_IDLE,
470                                                                      emit_config_changed,
471                                                                      info,
472                                                                      (GDestroyNotify) g_free);
473                 }
474         }
475 }
476
477 static void
478 ref_object (struct nl_object *obj, void *data)
479 {
480         struct nl_object **out = data;
481
482         nl_object_get (obj);
483         *out = obj;
484 }
485
486 static NMIP6Device *
487 process_addr (NMIP6Manager *manager, struct nl_msg *msg)
488 {
489         NMIP6ManagerPrivate *priv = NM_IP6_MANAGER_GET_PRIVATE (manager);
490         NMIP6Device *device;
491         struct rtnl_addr *rtnladdr;
492         int old_size;
493
494         nm_log_dbg (LOGD_IP6, "processing netlink new/del address message");
495
496         rtnladdr = NULL;
497         nl_msg_parse (msg, ref_object, &rtnladdr);
498         if (!rtnladdr) {
499                 nm_log_dbg (LOGD_IP6, "error processing netlink new/del address message");
500                 return NULL;
501         }
502
503         device = nm_ip6_manager_get_device (manager, rtnl_addr_get_ifindex (rtnladdr));
504         if (!device) {
505                 nm_log_dbg (LOGD_IP6, "ignoring message for unknown device");
506                 return NULL;
507         }
508
509         old_size = nl_cache_nitems (priv->addr_cache);
510         nl_cache_include (priv->addr_cache, (struct nl_object *)rtnladdr, NULL);
511         rtnl_addr_put (rtnladdr);
512
513         /* The kernel will re-notify us of automatically-added addresses
514          * every time it gets another router advertisement. We only want
515          * to notify higher levels if we actually changed something.
516          */
517         if (nl_cache_nitems (priv->addr_cache) == old_size) {
518                 nm_log_dbg (LOGD_IP6, "(%s): address cache unchanged, ignoring message");
519                 return NULL;
520         }
521
522         return device;
523 }
524
525 static NMIP6Device *
526 process_route (NMIP6Manager *manager, struct nl_msg *msg)
527 {
528         NMIP6ManagerPrivate *priv = NM_IP6_MANAGER_GET_PRIVATE (manager);
529         NMIP6Device *device;
530         struct rtnl_route *rtnlroute;
531         int old_size;
532
533         nm_log_dbg (LOGD_IP6, "processing netlink new/del route message");
534
535         rtnlroute = NULL;
536         nl_msg_parse (msg, ref_object, &rtnlroute);
537         if (!rtnlroute) {
538                 nm_log_dbg (LOGD_IP6, "error processing netlink new/del route message");
539                 return NULL;
540         }
541
542         device = nm_ip6_manager_get_device (manager, rtnl_route_get_oif (rtnlroute));
543         if (!device) {
544                 nm_log_dbg (LOGD_IP6, "ignoring message for unknown device");
545                 return NULL;
546         }
547
548         old_size = nl_cache_nitems (priv->route_cache);
549         nl_cache_include (priv->route_cache, (struct nl_object *)rtnlroute, NULL);
550         rtnl_route_put (rtnlroute);
551
552         /* As above in process_addr */
553         if (nl_cache_nitems (priv->route_cache) == old_size) {
554                 nm_log_dbg (LOGD_IP6, "(%s): route cache unchanged, ignoring message");
555                 return NULL;
556         }
557
558         return device;
559 }
560
561 static NMIP6Device *
562 process_prefix (NMIP6Manager *manager, struct nl_msg *msg)
563 {
564         struct prefixmsg *pmsg;
565         NMIP6Device *device;
566
567         /* We don't care about the prefix itself, but if we receive a
568          * router advertisement telling us to use DHCP, we might not
569          * get any RTM_NEWADDRs or RTM_NEWROUTEs, so this is our only
570          * way to notice immediately that an RA was received.
571          */
572
573         nm_log_dbg (LOGD_IP6, "processing netlink new prefix message");
574
575         pmsg = (struct prefixmsg *) NLMSG_DATA (nlmsg_hdr (msg));
576         device = nm_ip6_manager_get_device (manager, pmsg->prefix_ifindex);
577
578         if (!device || device->addrconf_complete) {
579                 nm_log_dbg (LOGD_IP6, "(%s): ignoring unknown or completed device",
580                             device ? device->iface : "(none)");
581                 return NULL;
582         }
583
584         return device;
585 }
586
587 /* RDNSS parsing code based on rdnssd, Copyright 2007 Pierre Ynard,
588  * RĂ©mi Denis-Courmont. GPLv2/3
589  */
590
591 #define ND_OPT_RDNSS 25
592 struct nd_opt_rdnss {
593         uint8_t nd_opt_rdnss_type;
594         uint8_t nd_opt_rdnss_len;
595         uint16_t nd_opt_rdnss_reserved1;
596         uint32_t nd_opt_rdnss_lifetime;
597         /* followed by one or more IPv6 addresses */
598 };
599
600 static NMIP6Device *
601 process_nduseropt (NMIP6Manager *manager, struct nl_msg *msg)
602 {
603         NMIP6Device *device;
604         struct nduseroptmsg *ndmsg;
605         struct nd_opt_hdr *opt;
606         guint opts_len, i;
607         time_t now = time (NULL);
608         struct nd_opt_rdnss *rdnss_opt;
609         struct in6_addr *addr;
610         GArray *servers;
611         NMIP6RDNSS server, *sa, *sb;
612         gboolean changed;
613
614         nm_log_dbg (LOGD_IP6, "processing netlink nduseropt message");
615
616         ndmsg = (struct nduseroptmsg *) NLMSG_DATA (nlmsg_hdr (msg));
617
618         if (ndmsg->nduseropt_family != AF_INET6 ||
619                 ndmsg->nduseropt_icmp_type != ND_ROUTER_ADVERT ||
620                 ndmsg->nduseropt_icmp_code != 0) {
621                 nm_log_dbg (LOGD_IP6, "ignoring non-Router Advertisement message");
622                 return NULL;
623         }
624
625         device = nm_ip6_manager_get_device (manager, ndmsg->nduseropt_ifindex);
626         if (!device) {
627                 nm_log_dbg (LOGD_IP6, "ignoring message for unknown device");
628                 return NULL;
629         }
630
631         servers = g_array_new (FALSE, FALSE, sizeof (NMIP6RDNSS));
632
633         opt = (struct nd_opt_hdr *) (ndmsg + 1);
634         opts_len = ndmsg->nduseropt_opts_len;
635
636         while (opts_len >= sizeof (struct nd_opt_hdr)) {
637                 size_t nd_opt_len = opt->nd_opt_len;
638
639                 if (nd_opt_len == 0 || opts_len < (nd_opt_len << 3))
640                         break;
641
642                 if (opt->nd_opt_type != ND_OPT_RDNSS)
643                         goto next;
644
645                 if (nd_opt_len < 3 || (nd_opt_len & 1) == 0)
646                         goto next;
647
648                 rdnss_opt = (struct nd_opt_rdnss *) opt;
649
650                 server.expires = now + ntohl (rdnss_opt->nd_opt_rdnss_lifetime);
651                 for (addr = (struct in6_addr *) (rdnss_opt + 1); nd_opt_len >= 2; addr++, nd_opt_len -= 2) {
652                         char buf[INET6_ADDRSTRLEN];
653
654                         if (inet_ntop (AF_INET6, &addr, buf, INET6_ADDRSTRLEN) > 0) {
655                                 nm_log_dbg (LOGD_IP6, "(%s): found RA-provided nameserver %s",
656                                             device->iface, buf);
657                         }
658
659                         server.addr = *addr;
660                         g_array_append_val (servers, server);
661                 }
662
663         next:
664                 opts_len -= opt->nd_opt_len << 3;
665                 opt = (struct nd_opt_hdr *) ((uint8_t *) opt + (opt->nd_opt_len << 3));
666         }
667
668         /* See if anything (other than expiration time) changed */
669         if (servers->len != device->rdnss_servers->len)
670                 changed = TRUE;
671         else {
672                 for (i = 0; i < servers->len; i++) {
673                         sa = &(g_array_index (servers, NMIP6RDNSS, i));
674                         sb = &(g_array_index (device->rdnss_servers, NMIP6RDNSS, i));
675                         if (memcmp (&sa->addr, &sb->addr, sizeof (struct in6_addr)) != 0) {
676                                 changed = TRUE;
677                                 break;
678                         }
679                 }
680                 changed = FALSE;
681         }
682
683         if (changed) {
684                 nm_log_dbg (LOGD_IP6, "(%s): RA-provided nameservers changed", device->iface);
685                 g_array_free (device->rdnss_servers, TRUE);
686                 device->rdnss_servers = servers;
687         } else
688                 g_array_free (servers, TRUE);
689
690         /* Timeouts may have changed even if IPs didn't */
691         set_rdnss_timeout (device);
692
693         if (changed)
694                 return device;
695         else
696                 return NULL;
697 }
698
699 static struct nla_policy link_policy[IFLA_MAX + 1] = {
700         [IFLA_PROTINFO] = { .type = NLA_NESTED },
701 };
702
703 static struct nla_policy link_prot_policy[IFLA_INET6_MAX + 1] = {
704         [IFLA_INET6_FLAGS]      = { .type = NLA_U32 },
705 };
706
707 static NMIP6Device *
708 process_newlink (NMIP6Manager *manager, struct nl_msg *msg)
709 {
710         struct nlmsghdr *hdr = nlmsg_hdr (msg);
711         struct ifinfomsg *ifi;
712         NMIP6Device *device;
713         struct nlattr *tb[IFLA_MAX + 1];
714         struct nlattr *pi[IFLA_INET6_MAX + 1];
715         int err;
716
717         ifi = nlmsg_data (hdr);
718         if (ifi->ifi_family != AF_INET6) {
719                 nm_log_dbg (LOGD_IP6, "ignoring netlink message family %d", ifi->ifi_family);
720                 return NULL;
721         }
722
723         device = nm_ip6_manager_get_device (manager, ifi->ifi_index);
724         if (!device || device->addrconf_complete) {
725                 nm_log_dbg (LOGD_IP6, "(%s): ignoring unknown or completed device",
726                             device ? device->iface : "(none)");
727                 return NULL;
728         }
729
730         /* FIXME: we have to do this manually for now since libnl doesn't yet
731          * support the IFLA_PROTINFO attribute of NEWLINK messages.  When it does,
732          * we can get rid of this function and just grab IFLA_PROTINFO from
733          * nm_ip6_device_sync_from_netlink(), then get the IFLA_INET6_FLAGS out of
734          * the PROTINFO.
735          */
736
737         err = nlmsg_parse (hdr, sizeof (*ifi), tb, IFLA_MAX, link_policy);
738         if (err < 0) {
739                 nm_log_dbg (LOGD_IP6, "(%s): error parsing PROTINFO attribute", device->iface);
740                 return NULL;
741         }
742         if (!tb[IFLA_PROTINFO]) {
743                 nm_log_dbg (LOGD_IP6, "(%s): message had no PROTINFO attribute", device->iface);
744                 return NULL;
745         }
746
747         err = nla_parse_nested (pi, IFLA_INET6_MAX, tb[IFLA_PROTINFO], link_prot_policy);
748         if (err < 0) {
749                 nm_log_dbg (LOGD_IP6, "(%s): error parsing PROTINFO flags", device->iface);
750                 return NULL;
751         }
752         if (!pi[IFLA_INET6_FLAGS]) {
753                 nm_log_dbg (LOGD_IP6, "(%s): message had no PROTINFO flags", device->iface);
754                 return NULL;
755         }
756
757         device->ra_flags = nla_get_u32 (pi[IFLA_INET6_FLAGS]);
758         nm_log_dbg (LOGD_IP6, "(%s): got IPv6 flags 0x%X", device->iface, device->ra_flags);
759
760         return device;
761 }
762
763 static void
764 netlink_notification (NMNetlinkMonitor *monitor, struct nl_msg *msg, gpointer user_data)
765 {
766         NMIP6Manager *manager = (NMIP6Manager *) user_data;
767         NMIP6Device *device;
768         struct nlmsghdr *hdr;
769         gboolean config_changed = FALSE;
770
771         hdr = nlmsg_hdr (msg);
772         nm_log_dbg (LOGD_HW, "netlink notificate type %d", hdr->nlmsg_type);
773         switch (hdr->nlmsg_type) {
774         case RTM_NEWADDR:
775         case RTM_DELADDR:
776                 device = process_addr (manager, msg);
777                 config_changed = TRUE;
778                 break;
779         case RTM_NEWROUTE:
780         case RTM_DELROUTE:
781                 device = process_route (manager, msg);
782                 config_changed = TRUE;
783                 break;
784         case RTM_NEWPREFIX:
785                 device = process_prefix (manager, msg);
786                 break;
787         case RTM_NEWNDUSEROPT:
788                 device = process_nduseropt (manager, msg);
789                 config_changed = TRUE;
790                 break;
791         case RTM_NEWLINK:
792                 device = process_newlink (manager, msg);
793                 config_changed = TRUE;
794                 break;
795         default:
796                 return;
797         }
798
799         if (device) {
800                 nm_log_dbg (LOGD_IP6, "(%s): syncing device with netlink changes", device->iface);
801                 nm_ip6_device_sync_from_netlink (device, config_changed);
802         }
803 }
804
805 void
806 nm_ip6_manager_prepare_interface (NMIP6Manager *manager,
807                                                                   int ifindex,
808                                                                   NMSettingIP6Config *s_ip6)
809 {
810         NMIP6ManagerPrivate *priv;
811         NMIP6Device *device;
812         const char *method = NULL;
813
814         g_return_if_fail (NM_IS_IP6_MANAGER (manager));
815         g_return_if_fail (ifindex > 0);
816
817         priv = NM_IP6_MANAGER_GET_PRIVATE (manager);
818
819         device = nm_ip6_device_new (manager, ifindex);
820         g_return_if_fail (device != NULL);
821         g_return_if_fail (   strchr (device->iface, '/') == NULL
822                           && strcmp (device->iface, "all") != 0
823                           && strcmp (device->iface, "default") != 0);
824
825         if (s_ip6)
826                 method = nm_setting_ip6_config_get_method (s_ip6);
827         if (!method)
828                 method = NM_SETTING_IP6_CONFIG_METHOD_AUTO;
829
830         /* Establish target state and turn router advertisement acceptance on or off */
831         if (!strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL)) {
832                 device->target_state = NM_IP6_DEVICE_GOT_LINK_LOCAL;
833                 nm_utils_do_sysctl (device->accept_ra_path, "0\n");
834         } else {
835                 device->target_state = NM_IP6_DEVICE_GOT_ADDRESS;
836                 nm_utils_do_sysctl (device->accept_ra_path, "1\n");
837         }
838 }
839
840 static gboolean
841 poll_ip6_flags (gpointer user_data)
842 {
843         nm_netlink_monitor_request_ip6_info (NM_NETLINK_MONITOR (user_data), NULL);
844         return TRUE;
845 }
846
847 void
848 nm_ip6_manager_begin_addrconf (NMIP6Manager *manager, int ifindex)
849 {
850         NMIP6ManagerPrivate *priv;
851         NMIP6Device *device;
852         CallbackInfo *info;
853
854         g_return_if_fail (NM_IS_IP6_MANAGER (manager));
855         g_return_if_fail (ifindex > 0);
856
857         priv = NM_IP6_MANAGER_GET_PRIVATE (manager);
858
859         device = (NMIP6Device *) g_hash_table_lookup (priv->devices, GINT_TO_POINTER (ifindex));
860         g_return_if_fail (device != NULL);
861
862         nm_log_info (LOGD_IP6, "Activation (%s) Beginning IP6 addrconf.", device->iface);
863
864         device->addrconf_complete = FALSE;
865         device->ra_flags = 0;
866
867         /* Set up a timeout on the transaction to kill it after the timeout */
868         info = callback_info_new (device, 0, FALSE);
869         device->finish_addrconf_id = g_timeout_add_seconds_full (G_PRIORITY_DEFAULT,
870                                                                  NM_IP6_TIMEOUT,
871                                                                  finish_addrconf,
872                                                                  info,
873                                                                  (GDestroyNotify) g_free);
874
875         /* Bounce IPv6 on the interface to ensure the kernel will start looking for
876          * new RAs; there doesn't seem to be a better way to do this right now.
877          */
878         if (device->target_state >= NM_IP6_DEVICE_GOT_ADDRESS) {
879                 nm_utils_do_sysctl (device->disable_ip6_path, "1\n");
880                 g_usleep (200);
881                 nm_utils_do_sysctl (device->disable_ip6_path, "0\n");
882         }
883
884         device->ip6flags_poll_id = g_timeout_add_seconds (1, poll_ip6_flags, priv->monitor);
885
886         /* Kick off the initial IPv6 flags request */
887         nm_netlink_monitor_request_ip6_info (priv->monitor, NULL);
888
889         /* Sync flags, etc, from netlink; this will also notice if the
890          * device is already fully configured and schedule the
891          * ADDRCONF_COMPLETE signal in that case.
892          */
893         nm_ip6_device_sync_from_netlink (device, FALSE);
894 }
895
896 void
897 nm_ip6_manager_cancel_addrconf (NMIP6Manager *manager, int ifindex)
898 {
899         g_return_if_fail (NM_IS_IP6_MANAGER (manager));
900         g_return_if_fail (ifindex > 0);
901
902         g_hash_table_remove (NM_IP6_MANAGER_GET_PRIVATE (manager)->devices,
903                              GINT_TO_POINTER (ifindex));
904 }
905
906 #define FIRST_ROUTE(m) ((struct rtnl_route *) nl_cache_get_first (m))
907 #define NEXT_ROUTE(m) ((struct rtnl_route *) nl_cache_get_next ((struct nl_object *) m))
908
909 #define FIRST_ADDR(m) ((struct rtnl_addr *) nl_cache_get_first (m))
910 #define NEXT_ADDR(m) ((struct rtnl_addr *) nl_cache_get_next ((struct nl_object *) m))
911
912 NMIP6Config *
913 nm_ip6_manager_get_ip6_config (NMIP6Manager *manager, int ifindex)
914 {
915         NMIP6ManagerPrivate *priv;
916         NMIP6Device *device;
917         NMIP6Config *config;
918         struct rtnl_addr *rtnladdr;
919         struct nl_addr *nladdr;
920         struct in6_addr *addr;
921         NMIP6Address *ip6addr;
922         struct rtnl_route *rtnlroute;
923         struct nl_addr *nldest, *nlgateway;
924         struct in6_addr *dest, *gateway;
925         gboolean defgw_set = FALSE;
926         struct in6_addr defgw;
927         uint32_t metric;
928         NMIP6Route *ip6route;
929         int i;
930
931         g_return_val_if_fail (NM_IS_IP6_MANAGER (manager), NULL);
932         g_return_val_if_fail (ifindex > 0, NULL);
933
934         priv = NM_IP6_MANAGER_GET_PRIVATE (manager);
935
936         device = (NMIP6Device *) g_hash_table_lookup (priv->devices,
937                                                       GINT_TO_POINTER (ifindex));
938         if (!device) {
939                 nm_log_warn (LOGD_IP6, "(%d): addrconf not started.", ifindex);
940                 return NULL;
941         }
942
943         config = nm_ip6_config_new ();
944         if (!config) {
945                 nm_log_err (LOGD_IP6, "(%s): out of memory creating IP6 config object.",
946                             device->iface);
947                 return NULL;
948         }
949
950         /* Make sure we refill the route and address caches, otherwise we won't get
951          * up-to-date information here since the netlink route/addr change messages
952          * may be lagging a bit.
953          */
954         nl_cache_refill (priv->nlh, priv->route_cache);
955         nl_cache_refill (priv->nlh, priv->addr_cache);
956
957         /* Add routes */
958         for (rtnlroute = FIRST_ROUTE (priv->route_cache); rtnlroute; rtnlroute = NEXT_ROUTE (rtnlroute)) {
959                 /* Make sure it's an IPv6 route for this device */
960                 if (rtnl_route_get_oif (rtnlroute) != device->ifindex)
961                         continue;
962                 if (rtnl_route_get_family (rtnlroute) != AF_INET6)
963                         continue;
964
965                 nldest = rtnl_route_get_dst (rtnlroute);
966                 if (!nldest || nl_addr_get_family (nldest) != AF_INET6)
967                         continue;
968                 dest = nl_addr_get_binary_addr (nldest);
969
970                 nlgateway = rtnl_route_get_gateway (rtnlroute);
971                 if (!nlgateway || nl_addr_get_family (nlgateway) != AF_INET6)
972                         continue;
973                 gateway = nl_addr_get_binary_addr (nlgateway);
974
975                 if (rtnl_route_get_dst_len (rtnlroute) == 0) {
976                         /* Default gateway route; don't add to normal routes but to each address */
977                         if (!defgw_set) {
978                                 memcpy (&defgw, gateway, sizeof (defgw));
979                                 defgw_set = TRUE;
980                         }
981                         continue;
982                 }
983
984                 ip6route = nm_ip6_route_new ();
985                 nm_ip6_route_set_dest (ip6route, dest);
986                 nm_ip6_route_set_prefix (ip6route, rtnl_route_get_dst_len (rtnlroute));
987                 nm_ip6_route_set_next_hop (ip6route, gateway);
988                 metric = rtnl_route_get_metric (rtnlroute, 1);
989                 if (metric != UINT_MAX)
990                         nm_ip6_route_set_metric (ip6route, metric);
991                 nm_ip6_config_take_route (config, ip6route);
992         }
993
994         /* Add addresses */
995         for (rtnladdr = FIRST_ADDR (priv->addr_cache); rtnladdr; rtnladdr = NEXT_ADDR (rtnladdr)) {
996                 if (rtnl_addr_get_ifindex (rtnladdr) != device->ifindex)
997                         continue;
998
999                 nladdr = rtnl_addr_get_local (rtnladdr);
1000                 if (!nladdr || nl_addr_get_family (nladdr) != AF_INET6)
1001                         continue;
1002
1003                 addr = nl_addr_get_binary_addr (nladdr);
1004                 ip6addr = nm_ip6_address_new ();
1005                 nm_ip6_address_set_prefix (ip6addr, rtnl_addr_get_prefixlen (rtnladdr));
1006                 nm_ip6_address_set_address (ip6addr, addr);
1007                 nm_ip6_config_take_address (config, ip6addr);
1008                 if (defgw_set)
1009                         nm_ip6_address_set_gateway (ip6addr, &defgw);
1010         }
1011
1012         /* Add DNS servers */
1013         if (device->rdnss_servers) {
1014                 NMIP6RDNSS *rdnss = (NMIP6RDNSS *)(device->rdnss_servers->data);
1015
1016                 for (i = 0; i < device->rdnss_servers->len; i++)
1017                         nm_ip6_config_add_nameserver (config, &rdnss[i].addr);
1018         }
1019
1020         return config;
1021 }
1022
1023 /******************************************************************/
1024
1025 static NMIP6Manager *
1026 nm_ip6_manager_new (void)
1027 {
1028         NMIP6Manager *manager;
1029         NMIP6ManagerPrivate *priv;
1030
1031         manager = g_object_new (NM_TYPE_IP6_MANAGER, NULL);
1032         priv = NM_IP6_MANAGER_GET_PRIVATE (manager);
1033
1034         if (!priv->devices) {
1035                 nm_log_err (LOGD_IP6, "not enough memory to initialize IP6 manager tables");
1036                 g_object_unref (manager);
1037                 manager = NULL;
1038         }
1039
1040         return manager;
1041 }
1042
1043 static NMIP6Manager *singleton = NULL;
1044
1045 NMIP6Manager *
1046 nm_ip6_manager_get (void)
1047 {
1048         if (!singleton) {
1049                 singleton = nm_ip6_manager_new ();
1050                 g_assert (singleton);
1051         } else
1052                 g_object_ref (singleton);
1053
1054         return singleton;
1055 }
1056
1057 static void
1058 nm_ip6_manager_init (NMIP6Manager *manager)
1059 {
1060         NMIP6ManagerPrivate *priv = NM_IP6_MANAGER_GET_PRIVATE (manager);
1061
1062         priv->devices = g_hash_table_new_full (g_direct_hash, g_direct_equal,
1063                                                NULL,
1064                                                (GDestroyNotify) nm_ip6_device_destroy);
1065
1066         priv->monitor = nm_netlink_monitor_get ();
1067         nm_netlink_monitor_subscribe (priv->monitor, RTNLGRP_IPV6_IFADDR, NULL);
1068         nm_netlink_monitor_subscribe (priv->monitor, RTNLGRP_IPV6_PREFIX, NULL);
1069         nm_netlink_monitor_subscribe (priv->monitor, RTNLGRP_ND_USEROPT, NULL);
1070         nm_netlink_monitor_subscribe (priv->monitor, RTNLGRP_LINK, NULL);
1071
1072         priv->netlink_id = g_signal_connect (priv->monitor, "notification",
1073                                              G_CALLBACK (netlink_notification), manager);
1074
1075         priv->nlh = nm_netlink_get_default_handle ();
1076         priv->addr_cache = rtnl_addr_alloc_cache (priv->nlh);
1077         priv->route_cache = rtnl_route_alloc_cache (priv->nlh);
1078 }
1079
1080 static void
1081 finalize (GObject *object)
1082 {
1083         NMIP6ManagerPrivate *priv = NM_IP6_MANAGER_GET_PRIVATE (object);
1084
1085         g_signal_handler_disconnect (priv->monitor, priv->netlink_id);
1086
1087         g_hash_table_destroy (priv->devices);
1088         g_object_unref (priv->monitor);
1089         nl_cache_free (priv->addr_cache);
1090         nl_cache_free (priv->route_cache);
1091
1092         singleton = NULL;
1093
1094         G_OBJECT_CLASS (nm_ip6_manager_parent_class)->finalize (object);
1095 }
1096
1097 static void
1098 nm_ip6_manager_class_init (NMIP6ManagerClass *manager_class)
1099 {
1100         GObjectClass *object_class = G_OBJECT_CLASS (manager_class);
1101
1102         g_type_class_add_private (manager_class, sizeof (NMIP6ManagerPrivate));
1103
1104         /* virtual methods */
1105         object_class->finalize = finalize;
1106
1107         /* signals */
1108         signals[ADDRCONF_COMPLETE] =
1109                 g_signal_new ("addrconf-complete",
1110                                           G_OBJECT_CLASS_TYPE (object_class),
1111                                           G_SIGNAL_RUN_FIRST,
1112                                           G_STRUCT_OFFSET (NMIP6ManagerClass, addrconf_complete),
1113                                           NULL, NULL,
1114                                           _nm_marshal_VOID__INT_UINT_BOOLEAN,
1115                                           G_TYPE_NONE, 3, G_TYPE_INT, G_TYPE_UINT, G_TYPE_BOOLEAN);
1116
1117         signals[CONFIG_CHANGED] =
1118                 g_signal_new ("config-changed",
1119                                           G_OBJECT_CLASS_TYPE (object_class),
1120                                           G_SIGNAL_RUN_FIRST,
1121                                           G_STRUCT_OFFSET (NMIP6ManagerClass, config_changed),
1122                                           NULL, NULL,
1123                                           _nm_marshal_VOID__INT_UINT,
1124                                           G_TYPE_NONE, 2, G_TYPE_INT, G_TYPE_UINT);
1125 }
1126