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