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