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