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