device: _get_available_connections() with _get_best_connection()
[NetworkManager.git] / src / devices / nm-device.c
1 /* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
2 /* NetworkManager -- Network link manager
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 of the License, or
7  * (at your option) 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) 2005 - 2013 Red Hat, Inc.
19  * Copyright (C) 2006 - 2008 Novell, Inc.
20  */
21
22 #include "nm-default.h"
23
24 #include <netinet/in.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <errno.h>
28 #include <sys/ioctl.h>
29 #include <signal.h>
30 #include <sys/types.h>
31 #include <sys/wait.h>
32 #include <arpa/inet.h>
33 #include <fcntl.h>
34 #include <netlink/route/addr.h>
35 #include <linux/if_addr.h>
36
37 #include "nm-device.h"
38 #include "nm-device-private.h"
39 #include "NetworkManagerUtils.h"
40 #include "nm-manager.h"
41 #include "nm-platform.h"
42 #include "nm-rdisc.h"
43 #include "nm-lndp-rdisc.h"
44 #include "nm-dhcp-manager.h"
45 #include "nm-activation-request.h"
46 #include "nm-ip4-config.h"
47 #include "nm-ip6-config.h"
48 #include "nm-dnsmasq-manager.h"
49 #include "nm-dhcp4-config.h"
50 #include "nm-dhcp6-config.h"
51 #include "nm-rfkill-manager.h"
52 #include "nm-firewall-manager.h"
53 #include "nm-enum-types.h"
54 #include "nm-settings-connection.h"
55 #include "nm-connection-provider.h"
56 #include "nm-auth-utils.h"
57 #include "nm-dispatcher.h"
58 #include "nm-config.h"
59 #include "nm-dns-manager.h"
60 #include "nm-core-internal.h"
61 #include "nm-default-route-manager.h"
62 #include "nm-route-manager.h"
63 #include "nm-lldp-listener.h"
64 #include "sd-ipv4ll.h"
65 #include "nm-audit-manager.h"
66 #include "nm-arping-manager.h"
67
68 #include "nm-device-logging.h"
69 _LOG_DECLARE_SELF (NMDevice);
70
71 #include "nmdbus-device.h"
72
73 G_DEFINE_ABSTRACT_TYPE (NMDevice, nm_device, NM_TYPE_EXPORTED_OBJECT)
74
75 #define NM_DEVICE_GET_PRIVATE(o) ((o)->priv)
76
77 enum {
78         STATE_CHANGED,
79         AUTOCONNECT_ALLOWED,
80         AUTH_REQUEST,
81         IP4_CONFIG_CHANGED,
82         IP6_CONFIG_CHANGED,
83         REMOVED,
84         RECHECK_AUTO_ACTIVATE,
85         RECHECK_ASSUME,
86         LAST_SIGNAL,
87 };
88 static guint signals[LAST_SIGNAL] = { 0 };
89
90 NM_GOBJECT_PROPERTIES_DEFINE (NMDevice,
91         PROP_UDI,
92         PROP_IFACE,
93         PROP_IP_IFACE,
94         PROP_DRIVER,
95         PROP_DRIVER_VERSION,
96         PROP_FIRMWARE_VERSION,
97         PROP_CAPABILITIES,
98         PROP_CARRIER,
99         PROP_MTU,
100         PROP_IP4_ADDRESS,
101         PROP_IP4_CONFIG,
102         PROP_DHCP4_CONFIG,
103         PROP_IP6_CONFIG,
104         PROP_DHCP6_CONFIG,
105         PROP_STATE,
106         PROP_STATE_REASON,
107         PROP_ACTIVE_CONNECTION,
108         PROP_DEVICE_TYPE,
109         PROP_LINK_TYPE,
110         PROP_MANAGED,
111         PROP_AUTOCONNECT,
112         PROP_FIRMWARE_MISSING,
113         PROP_NM_PLUGIN_MISSING,
114         PROP_TYPE_DESC,
115         PROP_RFKILL_TYPE,
116         PROP_IFINDEX,
117         PROP_AVAILABLE_CONNECTIONS,
118         PROP_PHYSICAL_PORT_ID,
119         PROP_IS_MASTER,
120         PROP_MASTER,
121         PROP_HW_ADDRESS,
122         PROP_HAS_PENDING_ACTION,
123         PROP_METERED,
124         PROP_LLDP_NEIGHBORS,
125         PROP_REAL,
126         PROP_SLAVES,
127 );
128
129 #define DEFAULT_AUTOCONNECT TRUE
130
131 /***********************************************************/
132
133 #define PENDING_ACTION_DHCP4 "dhcp4"
134 #define PENDING_ACTION_DHCP6 "dhcp6"
135 #define PENDING_ACTION_AUTOCONF6 "autoconf6"
136
137 typedef void (*ActivationHandleFunc) (NMDevice *self);
138
139 typedef struct {
140         ActivationHandleFunc func;
141         guint id;
142 } ActivationHandleData;
143
144 typedef enum {
145         CLEANUP_TYPE_DECONFIGURE,
146         CLEANUP_TYPE_KEEP,
147         CLEANUP_TYPE_REMOVED,
148 } CleanupType;
149
150 typedef enum {
151         IP_NONE = 0,
152         IP_WAIT,
153         IP_CONF,
154         IP_DONE,
155         IP_FAIL
156 } IpState;
157
158 typedef struct {
159         NMDeviceState state;
160         NMDeviceStateReason reason;
161         guint id;
162 } QueuedState;
163
164 typedef struct {
165         NMDevice *slave;
166         gboolean slave_is_enslaved;
167         gboolean configure;
168         gulong watch_id;
169 } SlaveInfo;
170
171 typedef struct {
172         NMLogDomain log_domain;
173         guint timeout;
174         guint watch;
175         GPid pid;
176         const char *binary;
177         const char *address;
178         guint deadline;
179 } PingInfo;
180
181 typedef struct {
182         NMDevice *device;
183         guint idle_add_id;
184         int ifindex;
185 } DeleteOnDeactivateData;
186
187 typedef void (*ArpingCallback) (NMDevice *, NMIP4Config **, gboolean);
188
189 typedef struct {
190         ArpingCallback callback;
191         NMDevice *device;
192         NMIP4Config **configs;
193 } ArpingData;
194
195 typedef struct _NMDevicePrivate {
196         gboolean in_state_changed;
197
198         guint device_link_changed_id;
199         guint device_ip_link_changed_id;
200
201         NMDeviceState state;
202         NMDeviceStateReason state_reason;
203         QueuedState   queued_state;
204         guint queued_ip4_config_id;
205         guint queued_ip6_config_id;
206         GSList *pending_actions;
207         GSList *dad6_failed_addrs;
208
209         char *        udi;
210         char *        iface;   /* may change, could be renamed by user */
211         int           ifindex;
212         gboolean      real;
213         char *        ip_iface;
214         int           ip_ifindex;
215         NMDeviceType  type;
216         char *        type_desc;
217         char *        type_description;
218         NMLinkType    link_type;
219         NMDeviceCapabilities capabilities;
220         char *        driver;
221         char *        driver_version;
222         char *        firmware_version;
223         RfKillType    rfkill_type;
224         gboolean      firmware_missing;
225         gboolean      nm_plugin_missing;
226         GHashTable *  available_connections;
227         char *        hw_addr;
228         guint         hw_addr_len;
229         char *        perm_hw_addr;
230         char *        initial_hw_addr;
231         char *        physical_port_id;
232         guint         dev_id;
233
234         NMUnmanagedFlags        unmanaged_mask;
235         NMUnmanagedFlags        unmanaged_flags;
236         gboolean                is_nm_owned; /* whether the device is a device owned and created by NM */
237         DeleteOnDeactivateData *delete_on_deactivate_data; /* data for scheduled cleanup when deleting link (g_idle_add) */
238
239         GCancellable *deactivating_cancellable;
240
241         guint32         ip4_address;
242
243         NMActRequest *  queued_act_request;
244         gboolean        queued_act_request_is_waiting_for_carrier;
245         NMActRequest *  act_request;
246         ActivationHandleData act_handle4; /* for layer2 and IPv4. */
247         ActivationHandleData act_handle6;
248         guint           recheck_assume_id;
249         struct {
250                 guint               call_id;
251                 NMDeviceStateReason available_reason;
252                 NMDeviceStateReason unavailable_reason;
253         }               recheck_available;
254         struct {
255                 guint               call_id;
256                 NMDeviceState       post_state;
257                 NMDeviceStateReason post_state_reason;
258         }               dispatcher;
259
260         /* Link stuff */
261         guint           link_connected_id;
262         guint           link_disconnected_id;
263         guint           carrier_defer_id;
264         gboolean        carrier;
265         guint           carrier_wait_id;
266         gboolean        ignore_carrier;
267         guint32         mtu;
268         gboolean        up;   /* IFF_UP */
269
270         /* Generic DHCP stuff */
271         guint32         dhcp_timeout;
272         char *          dhcp_anycast_address;
273
274         /* IP4 configuration info */
275         NMIP4Config *   ip4_config;     /* Combined config from VPN, settings, and device */
276         IpState         ip4_state;
277         NMIP4Config *   con_ip4_config; /* config from the setting */
278         NMIP4Config *   dev_ip4_config; /* Config from DHCP, PPP, LLv4, etc */
279         NMIP4Config *   ext_ip4_config; /* Stuff added outside NM */
280         NMIP4Config *   wwan_ip4_config; /* WWAN configuration */
281         GSList *        vpn4_configs;   /* VPNs which use this device */
282         struct {
283                 gboolean v4_has;
284                 gboolean v4_is_assumed;
285                 NMPlatformIP4Route v4;
286                 gboolean v6_has;
287                 gboolean v6_is_assumed;
288                 NMPlatformIP6Route v6;
289         } default_route;
290
291         gboolean v4_commit_first_time;
292         gboolean v6_commit_first_time;
293
294         /* DHCPv4 tracking */
295         NMDhcpClient *  dhcp4_client;
296         gulong          dhcp4_state_sigid;
297         NMDhcp4Config * dhcp4_config;
298         guint           dhcp4_restart_id;
299
300         PingInfo        gw_ping;
301
302         /* dnsmasq stuff for shared connections */
303         NMDnsMasqManager *dnsmasq_manager;
304         gulong            dnsmasq_state_id;
305
306         /* Firewall */
307         gboolean       fw_ready;
308         NMFirewallManagerCallId fw_call;
309
310         /* IPv4LL stuff */
311         sd_ipv4ll *    ipv4ll;
312         guint          ipv4ll_timeout;
313
314         /* IPv4 DAD stuff */
315         struct {
316                 GSList *          dad_list;
317                 NMArpingManager * announcing;
318         } arping;
319
320         /* IP6 configuration info */
321         NMIP6Config *  ip6_config;
322         IpState        ip6_state;
323         NMIP6Config *  con_ip6_config; /* config from the setting */
324         NMIP6Config *  wwan_ip6_config;
325         NMIP6Config *  ext_ip6_config; /* Stuff added outside NM */
326         NMIP6Config *  ext_ip6_config_captured; /* Configuration captured from platform. */
327         GSList *       vpn6_configs;   /* VPNs which use this device */
328         gboolean       nm_ipv6ll; /* TRUE if NM handles the device's IPv6LL address */
329         guint32        ip6_mtu;
330
331         NMRDisc *      rdisc;
332         gulong         rdisc_changed_id;
333         gulong         rdisc_timeout_id;
334         NMSettingIP6ConfigPrivacy rdisc_use_tempaddr;
335         /* IP6 config from autoconf */
336         NMIP6Config *  ac_ip6_config;
337
338         guint          linklocal6_timeout_id;
339         guint8         linklocal6_dad_counter;
340
341         GHashTable *   ip6_saved_properties;
342
343         NMDhcpClient *  dhcp6_client;
344         NMRDiscDHCPLevel dhcp6_mode;
345         gulong          dhcp6_state_sigid;
346         NMDhcp6Config * dhcp6_config;
347         /* IP6 config from DHCP */
348         NMIP6Config *   dhcp6_ip6_config;
349         /* Event ID of the current IP6 config from DHCP */
350         char *          dhcp6_event_id;
351         guint           dhcp6_restart_id;
352
353         /* allow autoconnect feature */
354         gboolean        autoconnect;
355
356         /* master interface for bridge/bond/team slave */
357         NMDevice *      master;
358         gboolean        is_enslaved;
359         gboolean        master_ready_handled;
360         gulong          master_ready_id;
361
362         /* slave management */
363         gboolean        is_master;
364         GSList *        slaves;    /* list of SlaveInfo */
365
366         NMMetered       metered;
367
368         NMConnectionProvider *con_provider;
369         NMLldpListener *lldp_listener;
370
371         guint check_delete_unrealized_id;
372 } NMDevicePrivate;
373
374 static gboolean nm_device_set_ip4_config (NMDevice *self,
375                                           NMIP4Config *config,
376                                           guint32 default_route_metric,
377                                           gboolean commit,
378                                           gboolean routes_full_sync,
379                                           NMDeviceStateReason *reason);
380 static gboolean ip4_config_merge_and_apply (NMDevice *self,
381                                             NMIP4Config *config,
382                                             gboolean commit,
383                                             NMDeviceStateReason *out_reason);
384
385 static gboolean nm_device_set_ip6_config (NMDevice *self,
386                                           NMIP6Config *config,
387                                           gboolean commit,
388                                           gboolean routes_full_sync,
389                                           NMDeviceStateReason *reason);
390
391 static void nm_device_master_add_slave (NMDevice *self, NMDevice *slave, gboolean configure);
392 static void nm_device_slave_notify_enslave (NMDevice *self, gboolean success);
393 static void nm_device_slave_notify_release (NMDevice *self, NMDeviceStateReason reason);
394
395 static gboolean addrconf6_start_with_link_ready (NMDevice *self);
396 static NMActStageReturn linklocal6_start (NMDevice *self);
397
398 static void _carrier_wait_check_queued_act_request (NMDevice *self);
399
400 static const char *_activation_func_to_string (ActivationHandleFunc func);
401 static void activation_source_handle_cb (NMDevice *self, int family);
402
403 static void _set_state_full (NMDevice *self,
404                              NMDeviceState state,
405                              NMDeviceStateReason reason,
406                              gboolean quitting);
407
408 static gboolean queued_ip4_config_change (gpointer user_data);
409 static gboolean queued_ip6_config_change (gpointer user_data);
410 static void ip_check_ping_watch_cb (GPid pid, gint status, gpointer user_data);
411 static gboolean ip_config_valid (NMDeviceState state);
412 static NMActStageReturn dhcp4_start (NMDevice *self, NMConnection *connection, NMDeviceStateReason *reason);
413 static gboolean dhcp6_start (NMDevice *self, gboolean wait_for_ll, NMDeviceStateReason *reason);
414 static void nm_device_start_ip_check (NMDevice *self);
415 static void realize_start_setup (NMDevice *self, const NMPlatformLink *plink);
416
417 /***********************************************************/
418
419 #define QUEUED_PREFIX "queued state change to "
420
421 static const char *state_table[] = {
422         [NM_DEVICE_STATE_UNKNOWN]      = QUEUED_PREFIX "unknown",
423         [NM_DEVICE_STATE_UNMANAGED]    = QUEUED_PREFIX "unmanaged",
424         [NM_DEVICE_STATE_UNAVAILABLE]  = QUEUED_PREFIX "unavailable",
425         [NM_DEVICE_STATE_DISCONNECTED] = QUEUED_PREFIX "disconnected",
426         [NM_DEVICE_STATE_PREPARE]      = QUEUED_PREFIX "prepare",
427         [NM_DEVICE_STATE_CONFIG]       = QUEUED_PREFIX "config",
428         [NM_DEVICE_STATE_NEED_AUTH]    = QUEUED_PREFIX "need-auth",
429         [NM_DEVICE_STATE_IP_CONFIG]    = QUEUED_PREFIX "ip-config",
430         [NM_DEVICE_STATE_IP_CHECK]     = QUEUED_PREFIX "ip-check",
431         [NM_DEVICE_STATE_SECONDARIES]  = QUEUED_PREFIX "secondaries",
432         [NM_DEVICE_STATE_ACTIVATED]    = QUEUED_PREFIX "activated",
433         [NM_DEVICE_STATE_DEACTIVATING] = QUEUED_PREFIX "deactivating",
434         [NM_DEVICE_STATE_FAILED]       = QUEUED_PREFIX "failed",
435 };
436
437 static const char *
438 queued_state_to_string (NMDeviceState state)
439 {
440         if ((gsize) state < G_N_ELEMENTS (state_table))
441                 return state_table[state];
442         return state_table[NM_DEVICE_STATE_UNKNOWN];
443 }
444
445 static const char *
446 state_to_string (NMDeviceState state)
447 {
448         return queued_state_to_string (state) + strlen (QUEUED_PREFIX);
449 }
450
451 NM_UTILS_LOOKUP_STR_DEFINE_STATIC (_reason_to_string, NMDeviceStateReason,
452         NM_UTILS_LOOKUP_DEFAULT (NULL),
453         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_UNKNOWN,                        "unknown"),
454         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_NONE,                           "none"),
455         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_NOW_MANAGED,                    "managed"),
456         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_NOW_UNMANAGED,                  "unmanaged"),
457         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_CONFIG_FAILED,                  "config-failed"),
458         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE,          "ip-config-unavailable"),
459         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED,              "ip-config-expired"),
460         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_NO_SECRETS,                     "no-secrets"),
461         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_SUPPLICANT_DISCONNECT,          "supplicant-disconnect"),
462         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_SUPPLICANT_CONFIG_FAILED,       "supplicant-config-failed"),
463         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED,              "supplicant-failed"),
464         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_SUPPLICANT_TIMEOUT,             "supplicant-timeout"),
465         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_PPP_START_FAILED,               "ppp-start-failed"),
466         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_PPP_DISCONNECT,                 "ppp-disconnect"),
467         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_PPP_FAILED,                     "ppp-failed"),
468         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_DHCP_START_FAILED,              "dhcp-start-failed"),
469         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_DHCP_ERROR,                     "dhcp-error"),
470         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_DHCP_FAILED,                    "dhcp-failed"),
471         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_SHARED_START_FAILED,            "sharing-start-failed"),
472         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_SHARED_FAILED,                  "sharing-failed"),
473         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_AUTOIP_START_FAILED,            "autoip-start-failed"),
474         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_AUTOIP_ERROR,                   "autoip-error"),
475         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_AUTOIP_FAILED,                  "autoip-failed"),
476         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_MODEM_BUSY,                     "modem-busy"),
477         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_MODEM_NO_DIAL_TONE,             "modem-no-dialtone"),
478         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_MODEM_NO_CARRIER,               "modem-no-carrier"),
479         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_MODEM_DIAL_TIMEOUT,             "modem-dial-timeout"),
480         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_MODEM_DIAL_FAILED,              "modem-dial-failed"),
481         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_MODEM_INIT_FAILED,              "modem-init-failed"),
482         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_GSM_APN_FAILED,                 "gsm-apn-failed"),
483         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_GSM_REGISTRATION_NOT_SEARCHING, "gsm-registration-idle"),
484         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_GSM_REGISTRATION_DENIED,        "gsm-registration-denied"),
485         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_GSM_REGISTRATION_TIMEOUT,       "gsm-registration-timeout"),
486         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_GSM_REGISTRATION_FAILED,        "gsm-registration-failed"),
487         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_GSM_PIN_CHECK_FAILED,           "gsm-pin-check-failed"),
488         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_FIRMWARE_MISSING,               "firmware-missing"),
489         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_REMOVED,                        "removed"),
490         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_SLEEPING,                       "sleeping"),
491         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_CONNECTION_REMOVED,             "connection-removed"),
492         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_USER_REQUESTED,                 "user-requested"),
493         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_CARRIER,                        "carrier-changed"),
494         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED,             "connection-assumed"),
495         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_SUPPLICANT_AVAILABLE,           "supplicant-available"),
496         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_MODEM_NOT_FOUND,                "modem-not-found"),
497         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_BT_FAILED,                      "bluetooth-failed"),
498         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_GSM_SIM_NOT_INSERTED,           "gsm-sim-not-inserted"),
499         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_GSM_SIM_PIN_REQUIRED,           "gsm-sim-pin-required"),
500         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_GSM_SIM_PUK_REQUIRED,           "gsm-sim-puk-required"),
501         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_GSM_SIM_WRONG,                  "gsm-sim-wrong"),
502         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_INFINIBAND_MODE,                "infiniband-mode"),
503         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_DEPENDENCY_FAILED,              "dependency-failed"),
504         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_BR2684_FAILED,                  "br2684-bridge-failed"),
505         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_MODEM_MANAGER_UNAVAILABLE,      "modem-manager-unavailable"),
506         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_SSID_NOT_FOUND,                 "ssid-not-found"),
507         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_SECONDARY_CONNECTION_FAILED,    "secondary-connection-failed"),
508         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_DCB_FCOE_FAILED,                "dcb-fcoe-failed"),
509         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_TEAMD_CONTROL_FAILED,           "teamd-control-failed"),
510         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_MODEM_FAILED,                   "modem-failed"),
511         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_MODEM_AVAILABLE,                "modem-available"),
512         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_SIM_PIN_INCORRECT,              "sim-pin-incorrect"),
513         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_NEW_ACTIVATION,                 "new-activation"),
514         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_PARENT_CHANGED,                 "parent-changed"),
515         NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_PARENT_MANAGED_CHANGED,         "parent-managed-changed"),
516 );
517
518 #define reason_to_string(reason) \
519         NM_UTILS_LOOKUP_STR (_reason_to_string, reason)
520
521 /***********************************************************/
522
523 gboolean
524 nm_device_ipv6_sysctl_set (NMDevice *self, const char *property, const char *value)
525 {
526         return nm_platform_sysctl_set (NM_PLATFORM_GET, nm_utils_ip6_property_path (nm_device_get_ip_iface (self), property), value);
527 }
528
529 static guint32
530 nm_device_ipv6_sysctl_get_int32 (NMDevice *self, const char *property, gint32 fallback)
531 {
532         return nm_platform_sysctl_get_int32 (NM_PLATFORM_GET, nm_utils_ip6_property_path (nm_device_get_ip_iface (self), property), fallback);
533 }
534
535 gboolean
536 nm_device_has_capability (NMDevice *self, NMDeviceCapabilities caps)
537 {
538         return NM_FLAGS_ANY (NM_DEVICE_GET_PRIVATE (self)->capabilities, caps);
539 }
540
541 /***********************************************************/
542
543 const char *
544 nm_device_get_udi (NMDevice *self)
545 {
546         g_return_val_if_fail (self != NULL, NULL);
547
548         return NM_DEVICE_GET_PRIVATE (self)->udi;
549 }
550
551 const char *
552 nm_device_get_iface (NMDevice *self)
553 {
554         g_return_val_if_fail (NM_IS_DEVICE (self), NULL);
555
556         return NM_DEVICE_GET_PRIVATE (self)->iface;
557 }
558
559 int
560 nm_device_get_ifindex (NMDevice *self)
561 {
562         g_return_val_if_fail (NM_IS_DEVICE (self), 0);
563
564         return NM_DEVICE_GET_PRIVATE (self)->ifindex;
565 }
566
567 /**
568  * nm_device_is_software:
569  * @self: the #NMDevice
570  *
571  * Indicates if the device is a software-based virtual device without
572  * backing hardware, which can be added and removed programmatically.
573  *
574  * Returns: %TRUE if the device is a software-based device
575  */
576 gboolean
577 nm_device_is_software (NMDevice *self)
578 {
579         return NM_FLAGS_HAS (NM_DEVICE_GET_PRIVATE (self)->capabilities, NM_DEVICE_CAP_IS_SOFTWARE);
580 }
581
582 /**
583  * nm_device_is_real:
584  * @self: the #NMDevice
585  *
586  * Returns: %TRUE if the device exists, %FALSE if the device is a placeholder
587  */
588 gboolean
589 nm_device_is_real (NMDevice *self)
590 {
591         g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
592
593         return NM_DEVICE_GET_PRIVATE (self)->real;
594 }
595
596 const char *
597 nm_device_get_ip_iface (NMDevice *self)
598 {
599         NMDevicePrivate *priv;
600
601         g_return_val_if_fail (self != NULL, NULL);
602
603         priv = NM_DEVICE_GET_PRIVATE (self);
604         /* If it's not set, default to iface */
605         return priv->ip_iface ? priv->ip_iface : priv->iface;
606 }
607
608 int
609 nm_device_get_ip_ifindex (NMDevice *self)
610 {
611         NMDevicePrivate *priv;
612
613         g_return_val_if_fail (self != NULL, 0);
614
615         priv = NM_DEVICE_GET_PRIVATE (self);
616         /* If it's not set, default to ifindex */
617         return priv->ip_iface ? priv->ip_ifindex : priv->ifindex;
618 }
619
620 void
621 nm_device_set_ip_iface (NMDevice *self, const char *iface)
622 {
623         NMDevicePrivate *priv;
624         char *old_ip_iface;
625
626         g_return_if_fail (NM_IS_DEVICE (self));
627
628         priv = NM_DEVICE_GET_PRIVATE (self);
629         if (!g_strcmp0 (iface, priv->ip_iface))
630                 return;
631
632         old_ip_iface = priv->ip_iface;
633         priv->ip_ifindex = 0;
634
635         priv->ip_iface = g_strdup (iface);
636         if (priv->ip_iface) {
637                 priv->ip_ifindex = nm_platform_link_get_ifindex (NM_PLATFORM_GET, priv->ip_iface);
638                 if (priv->ip_ifindex > 0) {
639                         if (nm_platform_check_support_user_ipv6ll (NM_PLATFORM_GET))
640                                 nm_platform_link_set_user_ipv6ll_enabled (NM_PLATFORM_GET, priv->ip_ifindex, TRUE);
641
642                         if (!nm_platform_link_is_up (NM_PLATFORM_GET, priv->ip_ifindex))
643                                 nm_platform_link_set_up (NM_PLATFORM_GET, priv->ip_ifindex, NULL);
644                 } else {
645                         /* Device IP interface must always be a kernel network interface */
646                         _LOGW (LOGD_HW, "failed to look up interface index");
647                 }
648         }
649
650         /* We don't care about any saved values from the old iface */
651         g_hash_table_remove_all (priv->ip6_saved_properties);
652
653         /* Emit change notification */
654         if (g_strcmp0 (old_ip_iface, priv->ip_iface))
655                 _notify (self, PROP_IP_IFACE);
656         g_free (old_ip_iface);
657 }
658
659 static gboolean
660 get_ip_iface_identifier (NMDevice *self, NMUtilsIPv6IfaceId *out_iid)
661 {
662         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
663         NMLinkType link_type;
664         const guint8 *hwaddr = NULL;
665         size_t hwaddr_len = 0;
666         int ifindex;
667         gboolean success;
668
669         /* If we get here, we *must* have a kernel netdev, which implies an ifindex */
670         ifindex = nm_device_get_ip_ifindex (self);
671         g_assert (ifindex);
672
673         link_type = nm_platform_link_get_type (NM_PLATFORM_GET, ifindex);
674         g_return_val_if_fail (link_type > NM_LINK_TYPE_UNKNOWN, 0);
675
676         hwaddr = nm_platform_link_get_address (NM_PLATFORM_GET, ifindex, &hwaddr_len);
677         if (!hwaddr_len)
678                 return FALSE;
679
680         success = nm_utils_get_ipv6_interface_identifier (link_type,
681                                                           hwaddr,
682                                                           hwaddr_len,
683                                                           priv->dev_id,
684                                                           out_iid);
685         if (!success) {
686                 _LOGW (LOGD_HW, "failed to generate interface identifier "
687                        "for link type %u hwaddr_len %zu", link_type, hwaddr_len);
688         }
689         return success;
690 }
691
692 static gboolean
693 nm_device_get_ip_iface_identifier (NMDevice *self, NMUtilsIPv6IfaceId *iid)
694 {
695         return NM_DEVICE_GET_CLASS (self)->get_ip_iface_identifier (self, iid);
696 }
697
698 const char *
699 nm_device_get_driver (NMDevice *self)
700 {
701         g_return_val_if_fail (self != NULL, NULL);
702
703         return NM_DEVICE_GET_PRIVATE (self)->driver;
704 }
705
706 const char *
707 nm_device_get_driver_version (NMDevice *self)
708 {
709         g_return_val_if_fail (self != NULL, NULL);
710
711         return NM_DEVICE_GET_PRIVATE (self)->driver_version;
712 }
713
714 NMDeviceType
715 nm_device_get_device_type (NMDevice *self)
716 {
717         g_return_val_if_fail (NM_IS_DEVICE (self), NM_DEVICE_TYPE_UNKNOWN);
718
719         return NM_DEVICE_GET_PRIVATE (self)->type;
720 }
721
722 NMLinkType
723 nm_device_get_link_type (NMDevice *self)
724 {
725         g_return_val_if_fail (NM_IS_DEVICE (self), NM_LINK_TYPE_UNKNOWN);
726
727         return NM_DEVICE_GET_PRIVATE (self)->link_type;
728 }
729
730 /**
731  * nm_device_get_metered:
732  * @setting: the #NMDevice
733  *
734  * Returns: the #NMDevice:metered property of the device.
735  *
736  * Since: 1.2
737  **/
738 NMMetered
739 nm_device_get_metered (NMDevice *self)
740 {
741         g_return_val_if_fail (NM_IS_DEVICE (self), NM_METERED_UNKNOWN);
742
743         return NM_DEVICE_GET_PRIVATE (self)->metered;
744 }
745
746 /**
747  * nm_device_get_priority():
748  * @self: the #NMDevice
749  *
750  * Returns: the device's routing priority.  Lower numbers means a "better"
751  *  device, eg higher priority.
752  */
753 int
754 nm_device_get_priority (NMDevice *self)
755 {
756         g_return_val_if_fail (NM_IS_DEVICE (self), 1000);
757
758         /* Device 'priority' is used for the default route-metric and is based on
759          * the device type. The settings ipv4.route-metric and ipv6.route-metric
760          * can overwrite this default.
761          *
762          * Currently for both IPv4 and IPv6 we use the same default values.
763          *
764          * The route-metric is used for the metric of the routes of device.
765          * This also applies to the default route. Therefore it affects also
766          * which device is the "best".
767          *
768          * For comparison, note that iproute2 by default adds IPv4 routes with
769          * metric 0, and IPv6 routes with metric 1024. The latter is the IPv6
770          * "user default" in the kernel (NM_PLATFORM_ROUTE_METRIC_DEFAULT_IP6).
771          * In kernel, the full uint32_t range is available for route
772          * metrics (except for IPv6, where 0 means 1024).
773          */
774
775         switch (nm_device_get_device_type (self)) {
776         /* 50 is reserved for VPN (NM_VPN_ROUTE_METRIC_DEFAULT) */
777         case NM_DEVICE_TYPE_ETHERNET:
778         case NM_DEVICE_TYPE_VETH:
779                 return 100;
780         case NM_DEVICE_TYPE_INFINIBAND:
781                 return 150;
782         case NM_DEVICE_TYPE_ADSL:
783                 return 200;
784         case NM_DEVICE_TYPE_WIMAX:
785                 return 250;
786         case NM_DEVICE_TYPE_BOND:
787                 return 300;
788         case NM_DEVICE_TYPE_TEAM:
789                 return 350;
790         case NM_DEVICE_TYPE_VLAN:
791                 return 400;
792         case NM_DEVICE_TYPE_MACVLAN:
793                 return 410;
794         case NM_DEVICE_TYPE_BRIDGE:
795                 return 425;
796         case NM_DEVICE_TYPE_TUN:
797                 return 450;
798         case NM_DEVICE_TYPE_VXLAN:
799                 return 500;
800         case NM_DEVICE_TYPE_WIFI:
801                 return 600;
802         case NM_DEVICE_TYPE_OLPC_MESH:
803                 return 650;
804         case NM_DEVICE_TYPE_IP_TUNNEL:
805                 return 675;
806         case NM_DEVICE_TYPE_MODEM:
807                 return 700;
808         case NM_DEVICE_TYPE_BT:
809                 return 750;
810         case NM_DEVICE_TYPE_GENERIC:
811                 return 950;
812         case NM_DEVICE_TYPE_UNKNOWN:
813                 return 10000;
814         case NM_DEVICE_TYPE_UNUSED1:
815         case NM_DEVICE_TYPE_UNUSED2:
816                 /* omit default: to get compiler warning about missing switch cases */
817                 break;
818         }
819         return 11000;
820 }
821
822 static guint32
823 _get_ipx_route_metric (NMDevice *self,
824                        gboolean is_v4)
825 {
826         char *value;
827         gint64 route_metric;
828         NMSettingIPConfig *s_ip;
829         NMConnection *connection;
830
831         g_return_val_if_fail (NM_IS_DEVICE (self), G_MAXUINT32);
832
833         connection = nm_device_get_applied_connection (self);
834         if (connection) {
835                 s_ip = is_v4
836                        ? nm_connection_get_setting_ip4_config (connection)
837                        : nm_connection_get_setting_ip6_config (connection);
838
839                 /* Slave interfaces don't have IP settings, but we may get here when
840                  * external changes are made or when noticing IP changes when starting
841                  * the slave connection.
842                  */
843                 if (s_ip) {
844                         route_metric = nm_setting_ip_config_get_route_metric (s_ip);
845                         if (route_metric >= 0)
846                                 goto out;
847                 }
848         }
849
850         /* use the current NMConfigData, which makes this configuration reloadable.
851          * Note that that means that the route-metric might change between SIGHUP.
852          * You must cache the returned value if that is a problem. */
853         value = nm_config_data_get_connection_default (NM_CONFIG_GET_DATA,
854                                                        is_v4 ? "ipv4.route-metric" : "ipv6.route-metric", self);
855         if (value) {
856                 route_metric = _nm_utils_ascii_str_to_int64 (value, 10, 0, G_MAXUINT32, -1);
857                 g_free (value);
858
859                 if (route_metric >= 0)
860                         goto out;
861         }
862         route_metric = nm_device_get_priority (self);
863 out:
864         if (!is_v4)
865                 route_metric = nm_utils_ip6_route_metric_normalize (route_metric);
866         return route_metric;
867 }
868
869 guint32
870 nm_device_get_ip4_route_metric (NMDevice *self)
871 {
872         return _get_ipx_route_metric (self, TRUE);
873 }
874
875 guint32
876 nm_device_get_ip6_route_metric (NMDevice *self)
877 {
878         return _get_ipx_route_metric (self, FALSE);
879 }
880
881 const NMPlatformIP4Route *
882 nm_device_get_ip4_default_route (NMDevice *self, gboolean *out_is_assumed)
883 {
884         NMDevicePrivate *priv;
885
886         g_return_val_if_fail (NM_IS_DEVICE (self), NULL);
887
888         priv = NM_DEVICE_GET_PRIVATE (self);
889
890         if (out_is_assumed)
891                 *out_is_assumed = priv->default_route.v4_is_assumed;
892
893         return priv->default_route.v4_has ? &priv->default_route.v4 : NULL;
894 }
895
896 const NMPlatformIP6Route *
897 nm_device_get_ip6_default_route (NMDevice *self, gboolean *out_is_assumed)
898 {
899         NMDevicePrivate *priv;
900
901         g_return_val_if_fail (NM_IS_DEVICE (self), NULL);
902
903         priv = NM_DEVICE_GET_PRIVATE (self);
904
905         if (out_is_assumed)
906                 *out_is_assumed = priv->default_route.v6_is_assumed;
907
908         return priv->default_route.v6_has ? &priv->default_route.v6 : NULL;
909 }
910
911 const char *
912 nm_device_get_type_desc (NMDevice *self)
913 {
914         g_return_val_if_fail (self != NULL, NULL);
915
916         return NM_DEVICE_GET_PRIVATE (self)->type_desc;
917 }
918
919 const char *
920 nm_device_get_type_description (NMDevice *self)
921 {
922         g_return_val_if_fail (self != NULL, NULL);
923
924         /* Beware: this function should return the same
925          * value as nm_device_get_type_description() in libnm. */
926
927         return NM_DEVICE_GET_CLASS (self)->get_type_description (self);
928 }
929
930 static const char *
931 get_type_description (NMDevice *self)
932 {
933         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
934
935         if (!priv->type_description) {
936                 const char *typename;
937
938                 typename = G_OBJECT_TYPE_NAME (self);
939                 if (g_str_has_prefix (typename, "NMDevice"))
940                         typename += 8;
941                 priv->type_description = g_ascii_strdown (typename, -1);
942         }
943
944         return priv->type_description;
945 }
946
947 gboolean
948 nm_device_has_carrier (NMDevice *self)
949 {
950         return NM_DEVICE_GET_PRIVATE (self)->carrier;
951 }
952
953 NMActRequest *
954 nm_device_get_act_request (NMDevice *self)
955 {
956         g_return_val_if_fail (self != NULL, NULL);
957
958         return NM_DEVICE_GET_PRIVATE (self)->act_request;
959 }
960
961 NMSettingsConnection *
962 nm_device_get_settings_connection (NMDevice *self)
963 {
964         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
965
966         return priv->act_request ? nm_act_request_get_settings_connection (priv->act_request) : NULL;
967 }
968
969 NMConnection *
970 nm_device_get_applied_connection (NMDevice *self)
971 {
972         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
973
974         return priv->act_request ? nm_act_request_get_applied_connection (priv->act_request) : NULL;
975 }
976
977 gboolean
978 nm_device_has_unmodified_applied_connection (NMDevice *self, NMSettingCompareFlags compare_flags)
979 {
980         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
981
982         if (!priv->act_request)
983                 return FALSE;
984
985         return nm_active_connection_has_unmodified_applied_connection ((NMActiveConnection *) priv->act_request, compare_flags);
986 }
987
988 NMSetting *
989 nm_device_get_applied_setting (NMDevice *device, GType setting_type)
990 {
991         NMActRequest *req;
992         NMSetting *setting = NULL;
993
994         g_return_val_if_fail (NM_IS_DEVICE (device), NULL);
995
996         req = nm_device_get_act_request (device);
997         if (req) {
998                 NMConnection *connection;
999
1000                 connection = nm_act_request_get_applied_connection (req);
1001                 if (connection)
1002                         setting = nm_connection_get_setting (connection, setting_type);
1003         }
1004
1005         return setting;
1006 }
1007
1008 RfKillType
1009 nm_device_get_rfkill_type (NMDevice *self)
1010 {
1011         g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
1012
1013         return NM_DEVICE_GET_PRIVATE (self)->rfkill_type;
1014 }
1015
1016 static const char *
1017 nm_device_get_physical_port_id (NMDevice *self)
1018 {
1019         return NM_DEVICE_GET_PRIVATE (self)->physical_port_id;
1020 }
1021
1022 /***********************************************************/
1023
1024 static gboolean
1025 nm_device_uses_generated_assumed_connection (NMDevice *self)
1026 {
1027         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
1028         NMSettingsConnection *connection;
1029
1030         if (   priv->act_request
1031             && nm_active_connection_get_assumed (NM_ACTIVE_CONNECTION (priv->act_request))) {
1032                 connection = nm_act_request_get_settings_connection (priv->act_request);
1033                 if (   connection
1034                     && nm_settings_connection_get_nm_generated_assumed (connection))
1035                         return TRUE;
1036         }
1037         return FALSE;
1038 }
1039
1040 gboolean
1041 nm_device_uses_assumed_connection (NMDevice *self)
1042 {
1043         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
1044
1045         if (   priv->act_request
1046             && nm_active_connection_get_assumed (NM_ACTIVE_CONNECTION (priv->act_request)))
1047                 return TRUE;
1048         return FALSE;
1049 }
1050
1051 static SlaveInfo *
1052 find_slave_info (NMDevice *self, NMDevice *slave)
1053 {
1054         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
1055         SlaveInfo *info;
1056         GSList *iter;
1057
1058         for (iter = priv->slaves; iter; iter = g_slist_next (iter)) {
1059                 info = iter->data;
1060                 if (info->slave == slave)
1061                         return info;
1062         }
1063         return NULL;
1064 }
1065
1066 /**
1067  * nm_device_master_enslave_slave:
1068  * @self: the master device
1069  * @slave: the slave device to enslave
1070  * @connection: (allow-none): the slave device's connection
1071  *
1072  * If @self is capable of enslaving other devices (ie it's a bridge, bond, team,
1073  * etc) then this function enslaves @slave.
1074  *
1075  * Returns: %TRUE on success, %FALSE on failure or if this device cannot enslave
1076  *  other devices.
1077  */
1078 static gboolean
1079 nm_device_master_enslave_slave (NMDevice *self, NMDevice *slave, NMConnection *connection)
1080 {
1081         SlaveInfo *info;
1082         gboolean success = FALSE;
1083         gboolean configure;
1084
1085         g_return_val_if_fail (self != NULL, FALSE);
1086         g_return_val_if_fail (slave != NULL, FALSE);
1087         g_return_val_if_fail (NM_DEVICE_GET_CLASS (self)->enslave_slave != NULL, FALSE);
1088
1089         info = find_slave_info (self, slave);
1090         if (!info)
1091                 return FALSE;
1092
1093         if (info->slave_is_enslaved)
1094                 success = TRUE;
1095         else {
1096                 configure = (info->configure && connection != NULL);
1097                 if (configure)
1098                         g_return_val_if_fail (nm_device_get_state (slave) >= NM_DEVICE_STATE_DISCONNECTED, FALSE);
1099
1100                 success = NM_DEVICE_GET_CLASS (self)->enslave_slave (self, slave, connection, configure);
1101                 info->slave_is_enslaved = success;
1102         }
1103
1104         nm_device_slave_notify_enslave (info->slave, success);
1105
1106         /* Ensure the device's hardware address is up-to-date; it often changes
1107          * when slaves change.
1108          */
1109         nm_device_update_hw_address (self);
1110
1111         /* Restart IP configuration if we're waiting for slaves.  Do this
1112          * after updating the hardware address as IP config may need the
1113          * new address.
1114          */
1115         if (success) {
1116                 if (NM_DEVICE_GET_PRIVATE (self)->ip4_state == IP_WAIT)
1117                         nm_device_activate_stage3_ip4_start (self);
1118
1119                 if (NM_DEVICE_GET_PRIVATE (self)->ip6_state == IP_WAIT)
1120                         nm_device_activate_stage3_ip6_start (self);
1121         }
1122
1123         return success;
1124 }
1125
1126 /**
1127  * nm_device_master_release_one_slave:
1128  * @self: the master device
1129  * @slave: the slave device to release
1130  * @configure: whether @self needs to actually release @slave
1131  * @reason: the state change reason for the @slave
1132  *
1133  * If @self is capable of enslaving other devices (ie it's a bridge, bond, team,
1134  * etc) then this function releases the previously enslaved @slave and/or
1135  * updates the state of @self and @slave to reflect its release.
1136  */
1137 static void
1138 nm_device_master_release_one_slave (NMDevice *self, NMDevice *slave, gboolean configure, NMDeviceStateReason reason)
1139 {
1140         NMDevicePrivate *priv;
1141         NMDevicePrivate *slave_priv;
1142         SlaveInfo *info;
1143         gs_unref_object NMDevice *self_free = NULL;
1144
1145         g_return_if_fail (NM_DEVICE (self));
1146         g_return_if_fail (NM_DEVICE (slave));
1147         g_return_if_fail (NM_DEVICE_GET_CLASS (self)->release_slave != NULL);
1148
1149         info = find_slave_info (self, slave);
1150
1151         _LOGt (LOGD_CORE, "master: release one slave %p/%s%s", slave, nm_device_get_iface (slave),
1152                !info ? " (not registered)" : "");
1153
1154         if (!info)
1155                 g_return_if_reached ();
1156
1157         priv = NM_DEVICE_GET_PRIVATE (self);
1158         slave_priv = NM_DEVICE_GET_PRIVATE (slave);
1159
1160         g_return_if_fail (self == slave_priv->master);
1161         nm_assert (slave == info->slave);
1162
1163         /* first, let subclasses handle the release ... */
1164         if (info->slave_is_enslaved)
1165                 NM_DEVICE_GET_CLASS (self)->release_slave (self, slave, configure);
1166
1167         /* raise notifications about the release, including clearing is_enslaved. */
1168         nm_device_slave_notify_release (slave, reason);
1169
1170         /* keep both alive until the end of the function.
1171          * Transfers ownership from slave_priv->master.  */
1172         self_free = self;
1173
1174         priv->slaves = g_slist_remove (priv->slaves, info);
1175         slave_priv->master = NULL;
1176
1177         g_signal_handler_disconnect (slave, info->watch_id);
1178         g_object_unref (slave);
1179         g_slice_free (SlaveInfo, info);
1180
1181         /* Ensure the device's hardware address is up-to-date; it often changes
1182          * when slaves change.
1183          */
1184         nm_device_update_hw_address (self);
1185         nm_device_set_unmanaged_by_flags (slave, NM_UNMANAGED_IS_SLAVE, NM_UNMAN_FLAG_OP_FORGET, NM_DEVICE_STATE_REASON_REMOVED);
1186 }
1187
1188 /**
1189  * can_unmanaged_external_down:
1190  * @self: the device
1191  *
1192  * Check whether the device should stay NM_UNMANAGED_EXTERNAL_DOWN unless
1193  * IFF_UP-ed externally.
1194  */
1195 static gboolean
1196 can_unmanaged_external_down (NMDevice *self)
1197 {
1198         return nm_device_is_software (self) && !NM_DEVICE_GET_PRIVATE (self)->is_nm_owned;
1199 }
1200
1201 static void
1202 update_dynamic_ip_setup (NMDevice *self)
1203 {
1204         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
1205         GError *error;
1206         gconstpointer addr;
1207         size_t addr_length;
1208
1209         g_hash_table_remove_all (priv->ip6_saved_properties);
1210
1211         if (priv->dhcp4_client) {
1212                 if (!nm_device_dhcp4_renew (self, FALSE)) {
1213                         nm_device_state_changed (self,
1214                                                  NM_DEVICE_STATE_FAILED,
1215                                                  NM_DEVICE_STATE_REASON_DHCP_FAILED);
1216                         return;
1217                 }
1218         }
1219         if (priv->dhcp6_client) {
1220                 if (!nm_device_dhcp6_renew (self, FALSE)) {
1221                         nm_device_state_changed (self,
1222                                                  NM_DEVICE_STATE_FAILED,
1223                                                  NM_DEVICE_STATE_REASON_DHCP_FAILED);
1224                         return;
1225                 }
1226         }
1227         if (priv->rdisc) {
1228                 /* FIXME: todo */
1229         }
1230         if (priv->dnsmasq_manager) {
1231                 /* FIXME: todo */
1232         }
1233
1234         if (priv->lldp_listener && nm_lldp_listener_is_running (priv->lldp_listener)) {
1235                 nm_lldp_listener_stop (priv->lldp_listener);
1236                 addr = nm_platform_link_get_address (NM_PLATFORM_GET, priv->ifindex, &addr_length);
1237
1238                 if (!nm_lldp_listener_start (priv->lldp_listener, nm_device_get_ifindex (self), &error)) {
1239                         _LOGD (LOGD_DEVICE, "LLDP listener %p could not be restarted: %s",
1240                                priv->lldp_listener, error->message);
1241                         g_clear_error (&error);
1242                 }
1243         }
1244 }
1245
1246 static void
1247 carrier_changed (NMDevice *self, gboolean carrier)
1248 {
1249         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
1250
1251         if (priv->state <= NM_DEVICE_STATE_UNMANAGED)
1252                 return;
1253
1254         nm_device_recheck_available_connections (self);
1255
1256         /* ignore-carrier devices ignore all carrier-down events */
1257         if (priv->ignore_carrier && !carrier)
1258                 return;
1259
1260         if (priv->is_master) {
1261                 /* Bridge/bond/team carrier does not affect its own activation,
1262                  * but when carrier comes on, if there are slaves waiting,
1263                  * it will restart them.
1264                  */
1265                 if (!carrier)
1266                         return;
1267
1268                 if (nm_device_activate_ip4_state_in_wait (self))
1269                         nm_device_activate_stage3_ip4_start (self);
1270                 if (nm_device_activate_ip6_state_in_wait (self))
1271                         nm_device_activate_stage3_ip6_start (self);
1272
1273                 return;
1274         } else if (nm_device_get_enslaved (self) && !carrier) {
1275                 /* Slaves don't deactivate when they lose carrier; for
1276                  * bonds/teams in particular that would be actively
1277                  * counterproductive.
1278                  */
1279                 return;
1280         }
1281
1282         if (carrier) {
1283                 if (priv->state == NM_DEVICE_STATE_UNAVAILABLE) {
1284                         nm_device_queue_state (self, NM_DEVICE_STATE_DISCONNECTED,
1285                                                NM_DEVICE_STATE_REASON_CARRIER);
1286                 } else if (priv->state == NM_DEVICE_STATE_DISCONNECTED) {
1287                         /* If the device is already in DISCONNECTED state without a carrier
1288                          * (probably because it is tagged for carrier ignore) ensure that
1289                          * when the carrier appears, auto connections are rechecked for
1290                          * the device.
1291                          */
1292                         nm_device_emit_recheck_auto_activate (self);
1293                 } else if (priv->state == NM_DEVICE_STATE_ACTIVATED) {
1294                         /* If the device is active without a carrier (probably because it is
1295                          * tagged for carrier ignore) ensure that when the carrier appears we
1296                          * renew DHCP leases and such.
1297                          */
1298                         update_dynamic_ip_setup (self);
1299                 }
1300         } else {
1301                 if (priv->state == NM_DEVICE_STATE_UNAVAILABLE) {
1302                         if (nm_device_queued_state_peek (self) >= NM_DEVICE_STATE_DISCONNECTED)
1303                                 nm_device_queued_state_clear (self);
1304                 } else {
1305                         nm_device_queue_state (self, NM_DEVICE_STATE_UNAVAILABLE,
1306                                                NM_DEVICE_STATE_REASON_CARRIER);
1307                 }
1308         }
1309 }
1310
1311 #define LINK_DISCONNECT_DELAY 4
1312
1313 static gboolean
1314 link_disconnect_action_cb (gpointer user_data)
1315 {
1316         NMDevice *self = NM_DEVICE (user_data);
1317         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
1318
1319         _LOGD (LOGD_DEVICE, "link disconnected (calling deferred action) (id=%u)", priv->carrier_defer_id);
1320
1321         priv->carrier_defer_id = 0;
1322
1323         _LOGI (LOGD_DEVICE, "link disconnected (calling deferred action)");
1324
1325         NM_DEVICE_GET_CLASS (self)->carrier_changed (self, FALSE);
1326
1327         return FALSE;
1328 }
1329
1330 static void
1331 link_disconnect_action_cancel (NMDevice *self)
1332 {
1333         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
1334
1335         if (priv->carrier_defer_id) {
1336                 g_source_remove (priv->carrier_defer_id);
1337                 _LOGD (LOGD_DEVICE, "link disconnected (canceling deferred action) (id=%u)", priv->carrier_defer_id);
1338                 priv->carrier_defer_id = 0;
1339         }
1340 }
1341
1342 void
1343 nm_device_set_carrier (NMDevice *self, gboolean carrier)
1344 {
1345         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
1346         NMDeviceClass *klass = NM_DEVICE_GET_CLASS (self);
1347         NMDeviceState state = nm_device_get_state (self);
1348
1349         if (priv->carrier == carrier)
1350                 return;
1351
1352         priv->carrier = carrier;
1353         _notify (self, PROP_CARRIER);
1354
1355         if (priv->carrier) {
1356                 _LOGI (LOGD_DEVICE, "link connected");
1357                 link_disconnect_action_cancel (self);
1358                 klass->carrier_changed (self, TRUE);
1359
1360                 if (nm_clear_g_source (&priv->carrier_wait_id)) {
1361                         nm_device_remove_pending_action (self, "carrier wait", TRUE);
1362                         _carrier_wait_check_queued_act_request (self);
1363                 }
1364         } else if (state <= NM_DEVICE_STATE_DISCONNECTED) {
1365                 _LOGI (LOGD_DEVICE, "link disconnected");
1366                 klass->carrier_changed (self, FALSE);
1367         } else {
1368                 _LOGI (LOGD_DEVICE, "link disconnected (deferring action for %d seconds)", LINK_DISCONNECT_DELAY);
1369                 priv->carrier_defer_id = g_timeout_add_seconds (LINK_DISCONNECT_DELAY,
1370                                                                 link_disconnect_action_cb, self);
1371                 _LOGD (LOGD_DEVICE, "link disconnected (deferring action for %d seconds) (id=%u)",
1372                        LINK_DISCONNECT_DELAY, priv->carrier_defer_id);
1373         }
1374 }
1375
1376 static void
1377 device_recheck_slave_status (NMDevice *self, const NMPlatformLink *plink)
1378 {
1379         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
1380
1381         g_return_if_fail (plink);
1382
1383         if (plink->master <= 0)
1384                 return;
1385
1386         if (priv->master) {
1387                 if (   plink->master > 0
1388                     && plink->master == nm_device_get_ifindex (priv->master)) {
1389                         /* call add-slave again. We expect @self already to be added to
1390                          * the master, but this also triggers a recheck-assume. */
1391                         nm_device_master_add_slave (priv->master, self, FALSE);
1392                         return;
1393                 }
1394
1395                 nm_device_master_release_one_slave (priv->master, self, FALSE, NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED);
1396         }
1397         if (plink->master > 0) {
1398                 NMDevice *master;
1399
1400                 master = nm_manager_get_device_by_ifindex (nm_manager_get (), plink->master);
1401                 if (master && NM_DEVICE_GET_CLASS (master)->enslave_slave)
1402                         nm_device_master_add_slave (master, self, FALSE);
1403                 else if (master) {
1404                         _LOGI (LOGD_DEVICE, "enslaved to non-master-type device %s; ignoring",
1405                                nm_device_get_iface (master));
1406                 } else {
1407                         _LOGW (LOGD_DEVICE, "enslaved to unknown device %d %s",
1408                                plink->master,
1409                                nm_platform_link_get_name (NM_PLATFORM_GET, plink->master));
1410                 }
1411         }
1412 }
1413
1414 static gboolean
1415 device_link_changed (NMDevice *self)
1416 {
1417         NMDeviceClass *klass = NM_DEVICE_GET_CLASS (self);
1418         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
1419         NMUtilsIPv6IfaceId token_iid;
1420         gboolean ip_ifname_changed = FALSE;
1421         const char *udi;
1422         NMPlatformLink info;
1423         const NMPlatformLink *pllink;
1424         int ifindex;
1425         gboolean was_up;
1426
1427         priv->device_link_changed_id = 0;
1428
1429         ifindex = nm_device_get_ifindex (self);
1430         pllink = nm_platform_link_get (NM_PLATFORM_GET, ifindex);
1431         if (!pllink)
1432                 return G_SOURCE_REMOVE;
1433
1434         info = *pllink;
1435
1436         udi = nm_platform_link_get_udi (NM_PLATFORM_GET, info.ifindex);
1437         if (udi && g_strcmp0 (udi, priv->udi)) {
1438                 /* Update UDI to what udev gives us */
1439                 g_free (priv->udi);
1440                 priv->udi = g_strdup (udi);
1441                 _notify (self, PROP_UDI);
1442         }
1443
1444         if (g_strcmp0 (info.driver, priv->driver)) {
1445                 /* Update driver to what udev gives us */
1446                 g_free (priv->driver);
1447                 priv->driver = g_strdup (info.driver);
1448                 _notify (self, PROP_DRIVER);
1449         }
1450
1451         /* Update MTU if it has changed. */
1452         if (priv->mtu != info.mtu) {
1453                 priv->mtu = info.mtu;
1454                 _notify (self, PROP_MTU);
1455         }
1456
1457         if (info.driver && g_strcmp0 (priv->driver, info.driver) != 0) {
1458                 g_free (priv->driver);
1459                 priv->driver = g_strdup (info.driver);
1460                 _notify (self, PROP_DRIVER);
1461         }
1462
1463         if (info.name[0] && strcmp (priv->iface, info.name) != 0) {
1464                 _LOGI (LOGD_DEVICE, "interface index %d renamed iface from '%s' to '%s'",
1465                        priv->ifindex, priv->iface, info.name);
1466                 g_free (priv->iface);
1467                 priv->iface = g_strdup (info.name);
1468
1469                 /* If the device has no explicit ip_iface, then changing iface changes ip_iface too. */
1470                 ip_ifname_changed = !priv->ip_iface;
1471
1472                 _notify (self, PROP_IFACE);
1473                 if (ip_ifname_changed)
1474                         _notify (self, PROP_IP_IFACE);
1475
1476                 /* Re-match available connections against the new interface name */
1477                 nm_device_recheck_available_connections (self);
1478
1479                 /* Let any connections that use the new interface name have a chance
1480                  * to auto-activate on the device.
1481                  */
1482                 nm_device_emit_recheck_auto_activate (self);
1483         }
1484
1485         if (priv->rdisc && nm_platform_link_get_ipv6_token (NM_PLATFORM_GET, priv->ifindex, &token_iid)) {
1486                 _LOGD (LOGD_DEVICE, "IPv6 tokenized identifier present on device %s", priv->iface);
1487                 if (nm_rdisc_set_iid (priv->rdisc, token_iid))
1488                         nm_rdisc_start (priv->rdisc);
1489         }
1490
1491         if (klass->link_changed)
1492                 klass->link_changed (self, &info);
1493
1494         /* Update DHCP, etc, if needed */
1495         if (ip_ifname_changed)
1496                 update_dynamic_ip_setup (self);
1497
1498         was_up = priv->up;
1499         priv->up = NM_FLAGS_HAS (info.n_ifi_flags, IFF_UP);
1500
1501         if (   priv->ifindex > 0
1502             && info.initialized
1503             && nm_device_get_unmanaged_flags (self, NM_UNMANAGED_PLATFORM_INIT)) {
1504                 NMDeviceStateReason reason;
1505
1506                 nm_device_set_unmanaged_by_user_udev (self);
1507
1508                 /* If the devices that need an external IFF_UP go managed below,
1509                  * it means they're already up. In that case we should use an "assumed"
1510                  * reason to prevent the cleanup sequence from being run on transition
1511                  * from "unmanaged" to "unavailable". */
1512                 if (   priv->up
1513                     && !nm_device_get_unmanaged_flags (self, NM_UNMANAGED_EXTERNAL_DOWN)
1514                     && NM_DEVICE_GET_CLASS (self)->can_unmanaged_external_down (self)) {
1515                         /* Ensure the assume check is queued before any queued state changes
1516                          * from the transition to UNAVAILABLE.
1517                          */
1518                         nm_device_queue_recheck_assume (self);
1519                         reason = NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED;
1520                 } else
1521                         reason = NM_DEVICE_STATE_REASON_NOW_MANAGED;
1522
1523                 nm_device_set_unmanaged_by_flags (self, NM_UNMANAGED_PLATFORM_INIT, FALSE, reason);
1524         }
1525
1526         if (   priv->ifindex > 0
1527             && priv->up != was_up
1528             && NM_DEVICE_GET_CLASS (self)->can_unmanaged_external_down (self)) {
1529                 /* Manage externally-created software interfaces only when they are IFF_UP */
1530                 if (   priv->up
1531                     && nm_device_get_unmanaged_flags (self, NM_UNMANAGED_EXTERNAL_DOWN)) {
1532                         /* Ensure the assume check is queued before any queued state changes
1533                          * from the transition to UNAVAILABLE.
1534                          */
1535                         nm_device_queue_recheck_assume (self);
1536                 }
1537
1538                 /* In case of @priv->up, resetting the EXTERNAL_DOWN flag may change the device's
1539                  * state to UNAVAILABLE. To ensure that the state change doesn't touch
1540                  * the device before assumption occurs, pass NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED
1541                  * as the reason.
1542                  *
1543                  * In case of !@priv->up, and the device is already unmanaged for other reasons, the
1544                  * state-change-reason has no effect.
1545                  * If the device is managed for an explict user-request, the state-change-reason
1546                  * also has no effect, because the device stays managed.
1547                  *
1548                  * The state-change-reason only has effect if the device was assumed
1549                  * and is now to be unmanaged. */
1550                 nm_device_set_unmanaged_by_flags (self,
1551                                                   NM_UNMANAGED_EXTERNAL_DOWN,
1552                                                   !priv->up,
1553                                                   NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED);
1554         }
1555
1556         device_recheck_slave_status (self, &info);
1557         return G_SOURCE_REMOVE;
1558 }
1559
1560 static gboolean
1561 device_ip_link_changed (NMDevice *self)
1562 {
1563         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
1564         const NMPlatformLink *pllink;
1565
1566         priv->device_ip_link_changed_id = 0;
1567
1568         if (!priv->ip_ifindex)
1569                 return G_SOURCE_REMOVE;
1570
1571         pllink = nm_platform_link_get (NM_PLATFORM_GET, priv->ip_ifindex);
1572         if (!pllink)
1573                 return G_SOURCE_REMOVE;
1574
1575         if (pllink->name[0] && g_strcmp0 (priv->ip_iface, pllink->name)) {
1576                 _LOGI (LOGD_DEVICE, "interface index %d renamed ip_iface (%d) from '%s' to '%s'",
1577                        priv->ifindex, nm_device_get_ip_ifindex (self),
1578                        priv->ip_iface, pllink->name);
1579                 g_free (priv->ip_iface);
1580                 priv->ip_iface = g_strdup (pllink->name);
1581
1582                 _notify (self, PROP_IP_IFACE);
1583                 update_dynamic_ip_setup (self);
1584         }
1585         return G_SOURCE_REMOVE;
1586 }
1587
1588 static void
1589 link_changed_cb (NMPlatform *platform,
1590                  NMPObjectType obj_type,
1591                  int ifindex,
1592                  NMPlatformLink *info,
1593                  NMPlatformSignalChangeType change_type,
1594                  NMDevice *self)
1595 {
1596         NMDevicePrivate *priv;
1597
1598         if (change_type != NM_PLATFORM_SIGNAL_CHANGED)
1599                 return;
1600
1601         priv = NM_DEVICE_GET_PRIVATE (self);
1602
1603         if (ifindex == nm_device_get_ifindex (self)) {
1604                 if (!priv->device_link_changed_id) {
1605                         priv->device_link_changed_id = g_idle_add ((GSourceFunc) device_link_changed, self);
1606                         _LOGD (LOGD_DEVICE, "queued link change for ifindex %d", ifindex);
1607                 }
1608         } else if (ifindex == nm_device_get_ip_ifindex (self)) {
1609                 if (!priv->device_ip_link_changed_id) {
1610                         priv->device_ip_link_changed_id = g_idle_add ((GSourceFunc) device_ip_link_changed, self);
1611                         _LOGD (LOGD_DEVICE, "queued link change for ip-ifindex %d", ifindex);
1612                 }
1613         }
1614 }
1615
1616 static void
1617 link_changed (NMDevice *self, NMPlatformLink *info)
1618 {
1619         /* Update carrier from link event if applicable. */
1620         if (   nm_device_has_capability (self, NM_DEVICE_CAP_CARRIER_DETECT)
1621             && !nm_device_has_capability (self, NM_DEVICE_CAP_NONSTANDARD_CARRIER))
1622                 nm_device_set_carrier (self, info->connected);
1623 }
1624
1625 static gboolean
1626 link_type_compatible (NMDevice *self,
1627                       NMLinkType link_type,
1628                       gboolean *out_compatible,
1629                       GError **error)
1630 {
1631         NMDeviceClass *klass;
1632         NMLinkType device_type;
1633         guint i = 0;
1634
1635         g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
1636
1637         klass = NM_DEVICE_GET_CLASS (self);
1638
1639         if (!klass->link_types) {
1640                 NM_SET_OUT (out_compatible, FALSE);
1641                 g_set_error_literal (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_FAILED,
1642                                      "Device does not support platform links");
1643                 return FALSE;
1644         }
1645
1646         device_type = self->priv->link_type;
1647         if (device_type > NM_LINK_TYPE_UNKNOWN && device_type != link_type) {
1648                 g_set_error (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_FAILED,
1649                              "Needed link type 0x%x does not match the platform link type 0x%X",
1650                              device_type, link_type);
1651                 return FALSE;
1652         }
1653
1654         for (i = 0; klass->link_types[i] > NM_LINK_TYPE_UNKNOWN; i++) {
1655                 if (klass->link_types[i] == link_type)
1656                         return TRUE;
1657                 if (klass->link_types[i] == NM_LINK_TYPE_ANY)
1658                         return TRUE;
1659         }
1660
1661         NM_SET_OUT (out_compatible, FALSE);
1662         g_set_error (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_FAILED,
1663                      "Device does not support platform link type 0x%X",
1664                      link_type);
1665         return FALSE;
1666 }
1667
1668 /**
1669  * nm_device_realize_start():
1670  * @self: the #NMDevice
1671  * @plink: an existing platform link or %NULL
1672  * @out_compatible: %TRUE on return if @self is compatible with @plink
1673  * @error: location to store error, or %NULL
1674  *
1675  * Initializes and sets up the device using existing backing resources. Before
1676  * the device is ready for use nm_device_realize_finish() must be called.
1677  * @out_compatible will only be set if @plink is not %NULL, and
1678  *
1679  * Important: if nm_device_realize_start() returns %TRUE, the caller MUST
1680  * also call nm_device_realize_finish() to balance g_object_freeze_notify().
1681  *
1682  * Returns: %TRUE on success, %FALSE on error
1683  */
1684 gboolean
1685 nm_device_realize_start (NMDevice *self,
1686                          const NMPlatformLink *plink,
1687                          gboolean *out_compatible,
1688                          GError **error)
1689 {
1690         NM_SET_OUT (out_compatible, TRUE);
1691
1692         if (plink) {
1693                 if (g_strcmp0 (nm_device_get_iface (self), plink->name) != 0) {
1694                         NM_SET_OUT (out_compatible, FALSE);
1695                         g_set_error_literal (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_FAILED,
1696                                              "Device interface name does not match platform link");
1697                         return FALSE;
1698                 }
1699
1700                 if (!link_type_compatible (self, plink->type, out_compatible, error))
1701                         return FALSE;
1702         }
1703
1704         realize_start_setup (self, plink);
1705
1706         return TRUE;
1707 }
1708
1709 /**
1710  * nm_device_create_and_realize():
1711  * @self: the #NMDevice
1712  * @connection: the #NMConnection being activated
1713  * @parent: the parent #NMDevice if any
1714  * @error: location to store error, or %NULL
1715  *
1716  * Creates any backing resources needed to realize the device to proceed
1717  * with activating @connection.
1718  *
1719  * Returns: %TRUE on success, %FALSE on error
1720  */
1721 gboolean
1722 nm_device_create_and_realize (NMDevice *self,
1723                               NMConnection *connection,
1724                               NMDevice *parent,
1725                               GError **error)
1726 {
1727         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
1728         NMPlatformLink plink_copy;
1729         const NMPlatformLink *plink = NULL;
1730
1731         /* Must be set before device is realized */
1732         priv->is_nm_owned = !nm_platform_link_get_by_ifname (NM_PLATFORM_GET, priv->iface);
1733
1734         _LOGD (LOGD_DEVICE, "create (is %snm-owned)", priv->is_nm_owned ? "" : "not ");
1735
1736         /* Create any resources the device needs */
1737         if (NM_DEVICE_GET_CLASS (self)->create_and_realize) {
1738                 if (!NM_DEVICE_GET_CLASS (self)->create_and_realize (self, connection, parent, &plink, error))
1739                         return FALSE;
1740                 plink_copy = *plink;
1741                 plink = &plink_copy;
1742         }
1743
1744         realize_start_setup (self, plink);
1745         nm_device_realize_finish (self, plink);
1746
1747         if (nm_device_get_managed (self, FALSE)) {
1748                 nm_device_state_changed (self,
1749                                          NM_DEVICE_STATE_UNAVAILABLE,
1750                                          NM_DEVICE_STATE_REASON_NOW_MANAGED);
1751         }
1752         return TRUE;
1753 }
1754
1755 static void
1756 update_device_from_platform_link (NMDevice *self, const NMPlatformLink *plink)
1757 {
1758         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
1759         const char *udi;
1760
1761         g_return_if_fail (plink != NULL);
1762
1763         udi = nm_platform_link_get_udi (NM_PLATFORM_GET, plink->ifindex);
1764         if (udi && !g_strcmp0 (udi, priv->udi)) {
1765                 g_free (priv->udi);
1766                 priv->udi = g_strdup (udi);
1767                 _notify (self, PROP_UDI);
1768         }
1769
1770         if (!g_strcmp0 (plink->name, priv->iface)) {
1771                 g_free (priv->iface);
1772                 priv->iface = g_strdup (plink->name);
1773                 _notify (self, PROP_IFACE);
1774         }
1775
1776         priv->ifindex = plink->ifindex;
1777         _notify (self, PROP_IFINDEX);
1778
1779         priv->up = NM_FLAGS_HAS (plink->n_ifi_flags, IFF_UP);
1780         if (plink->driver && g_strcmp0 (plink->driver, priv->driver) != 0) {
1781                 g_free (priv->driver);
1782                 priv->driver = g_strdup (plink->driver);
1783                 _notify (self, PROP_DRIVER);
1784         }
1785 }
1786
1787 static void
1788 config_changed_update_ignore_carrier (NMConfig *config,
1789                                       NMConfigData *config_data,
1790                                       NMConfigChangeFlags changes,
1791                                       NMConfigData *old_data,
1792                                       NMDevice *self)
1793 {
1794         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
1795
1796         if (   priv->state <= NM_DEVICE_STATE_DISCONNECTED
1797             || priv->state > NM_DEVICE_STATE_ACTIVATED)
1798                 priv->ignore_carrier = nm_config_data_get_ignore_carrier (config_data, self);
1799 }
1800
1801 static void
1802 check_carrier (NMDevice *self)
1803 {
1804         int ifindex = nm_device_get_ip_ifindex (self);
1805
1806         if (!nm_device_has_capability (self, NM_DEVICE_CAP_NONSTANDARD_CARRIER))
1807                 nm_device_set_carrier (self, nm_platform_link_is_connected (NM_PLATFORM_GET, ifindex));
1808 }
1809
1810 static void
1811 realize_start_notify (NMDevice *self, const NMPlatformLink *plink)
1812 {
1813         /* Stub implementation for realize_start_notify(). It does nothing,
1814          * but allows derived classes to uniformly invoke the parent
1815          * implementation. */
1816 }
1817
1818 /**
1819  * realize_start_setup():
1820  * @self: the #NMDevice
1821  * @plink: the #NMPlatformLink if backed by a kernel netdevice
1822  *
1823  * Update the device from backing resource properties (like hardware
1824  * addresses, carrier states, driver/firmware info, etc).  This function
1825  * should only change properties for this device, and should not perform
1826  * any tasks that affect other interfaces (like master/slave or parent/child
1827  * stuff).
1828  */
1829 static void
1830 realize_start_setup (NMDevice *self, const NMPlatformLink *plink)
1831 {
1832         NMDevicePrivate *priv;
1833         NMDeviceClass *klass;
1834         static guint32 id = 0;
1835
1836         g_return_if_fail (NM_IS_DEVICE (self));
1837
1838         priv = NM_DEVICE_GET_PRIVATE (self);
1839
1840         /* The device should not be realized */
1841         g_return_if_fail (!priv->real);
1842         g_return_if_fail (nm_device_get_unmanaged_flags (self, NM_UNMANAGED_PLATFORM_INIT));
1843         g_return_if_fail (priv->ip_ifindex <= 0);
1844         g_return_if_fail (priv->ip_iface == NULL);
1845
1846         _LOGD (LOGD_DEVICE, "start setup of %s, kernel ifindex %d", G_OBJECT_TYPE_NAME (self), plink ? plink->ifindex : 0);
1847
1848         klass = NM_DEVICE_GET_CLASS (self);
1849
1850         /* Balanced by a thaw in nm_device_realize_finish() */
1851         g_object_freeze_notify (G_OBJECT (self));
1852
1853         if (plink) {
1854                 g_return_if_fail (link_type_compatible (self, plink->type, NULL, NULL));
1855                 update_device_from_platform_link (self, plink);
1856         }
1857
1858         if (priv->ifindex > 0) {
1859                 priv->physical_port_id = nm_platform_link_get_physical_port_id (NM_PLATFORM_GET, priv->ifindex);
1860                 _notify (self, PROP_PHYSICAL_PORT_ID);
1861
1862                 priv->dev_id = nm_platform_link_get_dev_id (NM_PLATFORM_GET, priv->ifindex);
1863
1864                 if (nm_platform_link_is_software (NM_PLATFORM_GET, priv->ifindex))
1865                         priv->capabilities |= NM_DEVICE_CAP_IS_SOFTWARE;
1866
1867                 priv->mtu = nm_platform_link_get_mtu (NM_PLATFORM_GET, priv->ifindex);
1868                 _notify (self, PROP_MTU);
1869
1870                 nm_platform_link_get_driver_info (NM_PLATFORM_GET,
1871                                                   priv->ifindex,
1872                                                   NULL,
1873                                                   &priv->driver_version,
1874                                                   &priv->firmware_version);
1875                 if (priv->driver_version)
1876                         _notify (self, PROP_DRIVER_VERSION);
1877                 if (priv->firmware_version)
1878                         _notify (self, PROP_FIRMWARE_VERSION);
1879
1880                 if (nm_platform_check_support_user_ipv6ll (NM_PLATFORM_GET))
1881                         priv->nm_ipv6ll = nm_platform_link_get_user_ipv6ll_enabled (NM_PLATFORM_GET, priv->ifindex);
1882         }
1883
1884         if (klass->get_generic_capabilities)
1885                 priv->capabilities |= klass->get_generic_capabilities (self);
1886
1887         if (!priv->udi) {
1888                 /* Use a placeholder UDI until we get a real one */
1889                 priv->udi = g_strdup_printf ("/virtual/device/placeholder/%d", id++);
1890                 _notify (self, PROP_UDI);
1891         }
1892
1893         /* trigger initial ip config change to initialize ip-config */
1894         priv->queued_ip4_config_id = g_idle_add (queued_ip4_config_change, self);
1895         priv->queued_ip6_config_id = g_idle_add (queued_ip6_config_change, self);
1896
1897         nm_device_update_hw_address (self);
1898         nm_device_update_initial_hw_address (self);
1899
1900         /* Note: initial hardware address must be read before calling get_ignore_carrier() */
1901         if (nm_device_has_capability (self, NM_DEVICE_CAP_CARRIER_DETECT)) {
1902                 NMConfig *config = nm_config_get ();
1903
1904                 priv->ignore_carrier = nm_config_data_get_ignore_carrier (nm_config_get_data (config), self);
1905                 g_signal_connect (G_OBJECT (config),
1906                                   NM_CONFIG_SIGNAL_CONFIG_CHANGED,
1907                                   G_CALLBACK (config_changed_update_ignore_carrier),
1908                                   self);
1909
1910                 check_carrier (self);
1911                 _LOGD (LOGD_HW,
1912                        "carrier is %s%s",
1913                        priv->carrier ? "ON" : "OFF",
1914                        priv->ignore_carrier ? " (but ignored)" : "");
1915         } else {
1916                 /* Fake online link when carrier detection is not available. */
1917                 priv->carrier = TRUE;
1918         }
1919
1920         _notify (self, PROP_CAPABILITIES);
1921
1922         klass->realize_start_notify (self, plink);
1923
1924         /* Do not manage externally created software devices until they are IFF_UP */
1925         if (   priv->ifindex > 0
1926             && plink
1927             && !priv->up
1928             && NM_DEVICE_GET_CLASS (self)->can_unmanaged_external_down (self))
1929                 nm_device_set_unmanaged_flags (self, NM_UNMANAGED_EXTERNAL_DOWN, TRUE);
1930
1931         /* Unmanaged the loopback device with an explicit NM_UNMANAGED_LOOPBACK flag.
1932          * Later we might want to manage 'lo' too. Currently that doesn't work because
1933          * NetworkManager might down the interface or remove the 127.0.0.1 address. */
1934         nm_device_set_unmanaged_flags (self, NM_UNMANAGED_LOOPBACK, priv->ifindex == 1);
1935
1936         nm_device_set_unmanaged_by_user_udev (self);
1937
1938         nm_device_set_unmanaged_flags (self, NM_UNMANAGED_PLATFORM_INIT,
1939                                        plink && !plink->initialized);
1940 }
1941
1942 /**
1943  * nm_device_realize_finish():
1944  * @self: the #NMDevice
1945  * @plink: the #NMPlatformLink if backed by a kernel netdevice
1946  *
1947  * Update the device's master/slave or parent/child relationships from
1948  * backing resource properties.  After this function finishes, the device
1949  * is ready for network connectivity.
1950  */
1951 void
1952 nm_device_realize_finish (NMDevice *self, const NMPlatformLink *plink)
1953 {
1954         NMDevicePrivate *priv;
1955
1956         g_return_if_fail (NM_IS_DEVICE (self));
1957         g_return_if_fail (!plink || link_type_compatible (self, plink->type, NULL, NULL));
1958
1959         priv = NM_DEVICE_GET_PRIVATE (self);
1960
1961         g_return_if_fail (!priv->real);
1962
1963         if (plink)
1964                 device_recheck_slave_status (self, plink);
1965
1966         priv->real = TRUE;
1967         _notify (self, PROP_REAL);
1968
1969         nm_device_recheck_available_connections (self);
1970
1971         /* Balanced by a freeze in realize_start_setup(). */
1972         g_object_thaw_notify (G_OBJECT (self));
1973 }
1974
1975 static void
1976 unrealize_notify (NMDevice *self)
1977 {
1978         /* Stub implementation for unrealize_notify(). It does nothing,
1979          * but allows derived classes to uniformly invoke the parent
1980          * implementation. */
1981 }
1982
1983 static gboolean
1984 available_connections_check_delete_unrealized_on_idle (gpointer user_data)
1985 {
1986         NMDevice *self = user_data;
1987         NMDevicePrivate *priv;
1988
1989         g_return_val_if_fail (NM_IS_DEVICE (self), G_SOURCE_REMOVE);
1990
1991         priv = NM_DEVICE_GET_PRIVATE (self);
1992
1993         priv->check_delete_unrealized_id = 0;
1994
1995         if (   g_hash_table_size (priv->available_connections) == 0
1996             && !nm_device_is_real (self))
1997                 g_signal_emit (self, signals[REMOVED], 0);
1998
1999         return G_SOURCE_REMOVE;
2000 }
2001
2002 static void
2003 available_connections_check_delete_unrealized (NMDevice *self)
2004 {
2005         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
2006
2007         /* always rescheadule the remove signal. */
2008         nm_clear_g_source (&priv->check_delete_unrealized_id);
2009
2010         if (   g_hash_table_size (priv->available_connections) == 0
2011             && !nm_device_is_real (self))
2012                 priv->check_delete_unrealized_id = g_idle_add (available_connections_check_delete_unrealized_on_idle, self);
2013 }
2014
2015 /**
2016  * nm_device_unrealize():
2017  * @self: the #NMDevice
2018  * @remove_resources: if %TRUE, remove backing resources
2019  * @error: location to store error, or %NULL
2020  *
2021  * Clears any properties that depend on backing resources (kernel devices,
2022  * etc) and removes those resources if @remove_resources is %TRUE.
2023  *
2024  * Returns: %TRUE on success, %FALSE on error
2025  */
2026 gboolean
2027 nm_device_unrealize (NMDevice *self, gboolean remove_resources, GError **error)
2028 {
2029         NMDevicePrivate *priv;
2030         int ifindex;
2031
2032         g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
2033
2034         if (!nm_device_is_software (self) || !nm_device_is_real (self)) {
2035                 g_set_error_literal (error,
2036                                      NM_DEVICE_ERROR,
2037                                      NM_DEVICE_ERROR_NOT_SOFTWARE,
2038                                      "This device is not a software device or is not realized");
2039                 return FALSE;
2040         }
2041
2042         priv = NM_DEVICE_GET_PRIVATE (self);
2043
2044         g_return_val_if_fail (priv->iface != NULL, FALSE);
2045         g_return_val_if_fail (priv->real, FALSE);
2046
2047         g_object_freeze_notify (G_OBJECT (self));
2048
2049         ifindex = nm_device_get_ifindex (self);
2050
2051         _LOGD (LOGD_DEVICE, "unrealize (ifindex %d)", ifindex > 0 ? ifindex : 0);
2052
2053         if (remove_resources) {
2054                 if (ifindex > 0)
2055                         nm_platform_link_delete (NM_PLATFORM_GET, ifindex);
2056         }
2057
2058         NM_DEVICE_GET_CLASS (self)->unrealize_notify (self);
2059
2060         if (priv->ifindex > 0) {
2061                 priv->ifindex = 0;
2062                 _notify (self, PROP_IFINDEX);
2063         }
2064         priv->ip_ifindex = 0;
2065         if (priv->ip_iface) {
2066                 g_clear_pointer (&priv->ip_iface, g_free);
2067                 _notify (self, PROP_IP_IFACE);
2068         }
2069         if (priv->driver_version) {
2070                 g_clear_pointer (&priv->driver_version, g_free);
2071                 _notify (self, PROP_DRIVER_VERSION);
2072         }
2073         if (priv->firmware_version) {
2074                 g_clear_pointer (&priv->firmware_version, g_free);
2075                 _notify (self, PROP_FIRMWARE_VERSION);
2076         }
2077         if (priv->udi) {
2078                 g_clear_pointer (&priv->udi, g_free);
2079                 _notify (self, PROP_UDI);
2080         }
2081         if (priv->hw_addr) {
2082                 g_clear_pointer (&priv->hw_addr, g_free);
2083                 _notify (self, PROP_HW_ADDRESS);
2084         }
2085         if (priv->physical_port_id) {
2086                 g_clear_pointer (&priv->physical_port_id, g_free);
2087                 _notify (self, PROP_PHYSICAL_PORT_ID);
2088         }
2089
2090         g_clear_pointer (&priv->perm_hw_addr, g_free);
2091         g_clear_pointer (&priv->initial_hw_addr, g_free);
2092
2093         priv->capabilities = NM_DEVICE_CAP_NM_SUPPORTED;
2094         if (NM_DEVICE_GET_CLASS (self)->get_generic_capabilities)
2095                 priv->capabilities |= NM_DEVICE_GET_CLASS (self)->get_generic_capabilities (self);
2096         _notify (self, PROP_CAPABILITIES);
2097
2098         priv->real = FALSE;
2099         _notify (self, PROP_REAL);
2100
2101         nm_device_set_autoconnect (self, DEFAULT_AUTOCONNECT);
2102
2103         g_object_thaw_notify (G_OBJECT (self));
2104
2105         nm_device_set_unmanaged_flags (self,
2106                                        NM_UNMANAGED_PLATFORM_INIT,
2107                                        TRUE);
2108
2109         nm_device_set_unmanaged_flags (self,
2110                                        NM_UNMANAGED_PARENT |
2111                                        NM_UNMANAGED_LOOPBACK |
2112                                        NM_UNMANAGED_USER_UDEV |
2113                                        NM_UNMANAGED_EXTERNAL_DOWN |
2114                                        NM_UNMANAGED_IS_SLAVE,
2115                                        NM_UNMAN_FLAG_OP_FORGET);
2116
2117         nm_device_state_changed (self,
2118                                  NM_DEVICE_STATE_UNMANAGED,
2119                                  remove_resources ?
2120                                      NM_DEVICE_STATE_REASON_USER_REQUESTED : NM_DEVICE_STATE_REASON_NOW_UNMANAGED);
2121
2122         /* Garbage-collect unneeded unrealized devices. */
2123         nm_device_recheck_available_connections (self);
2124
2125         return TRUE;
2126 }
2127
2128 /**
2129  * nm_device_notify_new_device_added():
2130  * @self: the #NMDevice
2131  * @device: the newly added device
2132  *
2133  * Called by the manager to notify the device that a new device has
2134  * been found and added.
2135  */
2136 void
2137 nm_device_notify_new_device_added (NMDevice *self, NMDevice *device)
2138 {
2139         NMDeviceClass *klass;
2140
2141         g_return_if_fail (NM_IS_DEVICE (self));
2142         g_return_if_fail (NM_IS_DEVICE (device));
2143
2144         klass = NM_DEVICE_GET_CLASS (self);
2145         if (klass->notify_new_device_added)
2146                 klass->notify_new_device_added (self, device);
2147 }
2148
2149 /**
2150  * nm_device_notify_component_added():
2151  * @self: the #NMDevice
2152  * @component: the component being added by a plugin
2153  *
2154  * Called by the manager to notify the device that a new component has
2155  * been found.  The device implementation should return %TRUE if it
2156  * wishes to claim the component, or %FALSE if it cannot.
2157  *
2158  * Returns: %TRUE to claim the component, %FALSE if the component cannot be
2159  * claimed.
2160  */
2161 gboolean
2162 nm_device_notify_component_added (NMDevice *self, GObject *component)
2163 {
2164         NMDeviceClass *klass;
2165
2166         g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
2167         g_return_val_if_fail (G_IS_OBJECT (component), FALSE);
2168
2169         klass = NM_DEVICE_GET_CLASS (self);
2170         if (klass->component_added)
2171                 return klass->component_added (self, component);
2172         return FALSE;
2173 }
2174
2175 /**
2176  * nm_device_owns_iface():
2177  * @self: the #NMDevice
2178  * @iface: an interface name
2179  *
2180  * Called by the manager to ask if the device or any of its components owns
2181  * @iface.  For example, a WWAN implementation would return %TRUE for an
2182  * ethernet interface name that was owned by the WWAN device's modem component,
2183  * because that ethernet interface is controlled by the WWAN device and cannot
2184  * be used independently of the WWAN device.
2185  *
2186  * Returns: %TRUE if @self or it's components owns the interface name,
2187  * %FALSE if not
2188  */
2189 gboolean
2190 nm_device_owns_iface (NMDevice *self, const char *iface)
2191 {
2192         if (NM_DEVICE_GET_CLASS (self)->owns_iface)
2193                 return NM_DEVICE_GET_CLASS (self)->owns_iface (self, iface);
2194         return FALSE;
2195 }
2196
2197 NMConnection *
2198 nm_device_new_default_connection (NMDevice *self)
2199 {
2200         if (NM_DEVICE_GET_CLASS (self)->new_default_connection)
2201                 return NM_DEVICE_GET_CLASS (self)->new_default_connection (self);
2202         return NULL;
2203 }
2204
2205 static void
2206 slave_state_changed (NMDevice *slave,
2207                      NMDeviceState slave_new_state,
2208                      NMDeviceState slave_old_state,
2209                      NMDeviceStateReason reason,
2210                      NMDevice *self)
2211 {
2212         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
2213         gboolean release = FALSE;
2214
2215         _LOGD (LOGD_DEVICE, "slave %s state change %d (%s) -> %d (%s)",
2216                nm_device_get_iface (slave),
2217                slave_old_state,
2218                state_to_string (slave_old_state),
2219                slave_new_state,
2220                state_to_string (slave_new_state));
2221
2222         /* Don't try to enslave slaves until the master is ready */
2223         if (priv->state < NM_DEVICE_STATE_CONFIG)
2224                 return;
2225
2226         if (slave_new_state == NM_DEVICE_STATE_IP_CONFIG)
2227                 nm_device_master_enslave_slave (self, slave, nm_device_get_applied_connection (slave));
2228         else if (slave_new_state > NM_DEVICE_STATE_ACTIVATED)
2229                 release = TRUE;
2230         else if (   slave_new_state <= NM_DEVICE_STATE_DISCONNECTED
2231                  && slave_old_state > NM_DEVICE_STATE_DISCONNECTED) {
2232                 /* Catch failures due to unavailable or unmanaged */
2233                 release = TRUE;
2234         }
2235
2236         if (release) {
2237                 nm_device_master_release_one_slave (self, slave, TRUE, reason);
2238                 /* Bridge/bond/team interfaces are left up until manually deactivated */
2239                 if (priv->slaves == NULL && priv->state == NM_DEVICE_STATE_ACTIVATED)
2240                         _LOGD (LOGD_DEVICE, "last slave removed; remaining activated");
2241         }
2242 }
2243
2244 /**
2245  * nm_device_master_add_slave:
2246  * @self: the master device
2247  * @slave: the slave device to enslave
2248  * @configure: pass %TRUE if the slave should be configured by the master, or
2249  * %FALSE if it is already configured outside NetworkManager
2250  *
2251  * If @self is capable of enslaving other devices (ie it's a bridge, bond, team,
2252  * etc) then this function adds @slave to the slave list for later enslavement.
2253  */
2254 static void
2255 nm_device_master_add_slave (NMDevice *self, NMDevice *slave, gboolean configure)
2256 {
2257         NMDevicePrivate *priv;
2258         NMDevicePrivate *slave_priv;
2259         SlaveInfo *info;
2260
2261         g_return_if_fail (NM_IS_DEVICE (self));
2262         g_return_if_fail (NM_IS_DEVICE (slave));
2263         g_return_if_fail (NM_DEVICE_GET_CLASS (self)->enslave_slave != NULL);
2264
2265         priv = NM_DEVICE_GET_PRIVATE (self);
2266         slave_priv = NM_DEVICE_GET_PRIVATE (slave);
2267
2268         info = find_slave_info (self, slave);
2269
2270         _LOGt (LOGD_CORE, "master: add one slave %p/%s%s", slave, nm_device_get_iface (slave),
2271                info ? " (already registered)" : "");
2272
2273         if (configure)
2274                 g_return_if_fail (nm_device_get_state (slave) >= NM_DEVICE_STATE_DISCONNECTED);
2275
2276         if (!info) {
2277                 g_return_if_fail (!slave_priv->master);
2278                 g_return_if_fail (!slave_priv->is_enslaved);
2279
2280                 info = g_slice_new0 (SlaveInfo);
2281                 info->slave = g_object_ref (slave);
2282                 info->configure = configure;
2283                 info->watch_id = g_signal_connect (slave,
2284                                                    NM_DEVICE_STATE_CHANGED,
2285                                                    G_CALLBACK (slave_state_changed), self);
2286                 priv->slaves = g_slist_append (priv->slaves, info);
2287                 slave_priv->master = g_object_ref (self);
2288
2289                 /* no need to emit
2290                  *
2291                  *   _notify (slave, PROP_MASTER);
2292                  *
2293                  * because slave_priv->is_enslaved is not true, thus the value
2294                  * didn't change yet. */
2295
2296                 g_warn_if_fail (!NM_FLAGS_HAS (slave_priv->unmanaged_mask, NM_UNMANAGED_IS_SLAVE));
2297                 nm_device_set_unmanaged_by_flags (slave, NM_UNMANAGED_IS_SLAVE, FALSE, NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED);
2298         } else
2299                 g_return_if_fail (slave_priv->master == self);
2300
2301         nm_device_queue_recheck_assume (self);
2302         nm_device_queue_recheck_assume (slave);
2303 }
2304
2305
2306 /**
2307  * nm_device_master_get_slaves:
2308  * @self: the master device
2309  *
2310  * Returns: any slaves of which @self is the master.  Caller owns returned list.
2311  */
2312 static GSList *
2313 nm_device_master_get_slaves (NMDevice *self)
2314 {
2315         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
2316         GSList *slaves = NULL, *iter;
2317
2318         for (iter = priv->slaves; iter; iter = g_slist_next (iter))
2319                 slaves = g_slist_prepend (slaves, ((SlaveInfo *) iter->data)->slave);
2320
2321         return slaves;
2322 }
2323
2324 /**
2325  * nm_device_master_get_slave_by_ifindex:
2326  * @self: the master device
2327  * @ifindex: the slave's interface index
2328  *
2329  * Returns: the slave with the given @ifindex of which @self is the master,
2330  *   or %NULL if no device with @ifindex is a slave of @self.
2331  */
2332 NMDevice *
2333 nm_device_master_get_slave_by_ifindex (NMDevice *self, int ifindex)
2334 {
2335         GSList *iter;
2336
2337         for (iter = NM_DEVICE_GET_PRIVATE (self)->slaves; iter; iter = g_slist_next (iter)) {
2338                 SlaveInfo *info = iter->data;
2339
2340                 if (nm_device_get_ip_ifindex (info->slave) == ifindex)
2341                         return info->slave;
2342         }
2343         return NULL;
2344 }
2345
2346 /**
2347  * nm_device_master_check_slave_physical_port:
2348  * @self: the master device
2349  * @slave: a slave device
2350  * @log_domain: domain to log a warning in
2351  *
2352  * Checks if @self already has a slave with the same #NMDevice:physical-port-id
2353  * as @slave, and logs a warning if so.
2354  */
2355 void
2356 nm_device_master_check_slave_physical_port (NMDevice *self, NMDevice *slave,
2357                                             NMLogDomain log_domain)
2358 {
2359         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
2360         const char *slave_physical_port_id, *existing_physical_port_id;
2361         SlaveInfo *info;
2362         GSList *iter;
2363
2364         slave_physical_port_id = nm_device_get_physical_port_id (slave);
2365         if (!slave_physical_port_id)
2366                 return;
2367
2368         for (iter = priv->slaves; iter; iter = iter->next) {
2369                 info = iter->data;
2370                 if (info->slave == slave)
2371                         continue;
2372
2373                 existing_physical_port_id = nm_device_get_physical_port_id (info->slave);
2374                 if (!g_strcmp0 (slave_physical_port_id, existing_physical_port_id)) {
2375                         _LOGW (log_domain, "slave %s shares a physical port with existing slave %s",
2376                                nm_device_get_ip_iface (slave),
2377                                nm_device_get_ip_iface (info->slave));
2378                         /* Since this function will get called for every slave, we only have
2379                          * to warn about the first match we find; if there are other matches
2380                          * later in the list, we will have already warned about them matching
2381                          * @existing earlier.
2382                          */
2383                         return;
2384                 }
2385         }
2386 }
2387
2388 /* release all slaves */
2389 static void
2390 nm_device_master_release_slaves (NMDevice *self)
2391 {
2392         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
2393         NMDeviceStateReason reason;
2394         gboolean configure = TRUE;
2395
2396         /* Don't release the slaves if this connection doesn't belong to NM. */
2397         if (nm_device_uses_generated_assumed_connection (self))
2398                 return;
2399
2400         reason = priv->state_reason;
2401         if (priv->state == NM_DEVICE_STATE_FAILED)
2402                 reason = NM_DEVICE_STATE_REASON_DEPENDENCY_FAILED;
2403
2404         if (!nm_platform_link_get (NM_PLATFORM_GET, priv->ifindex))
2405                 configure = FALSE;
2406
2407         while (priv->slaves) {
2408                 SlaveInfo *info = priv->slaves->data;
2409
2410                 nm_device_master_release_one_slave (self, info->slave, configure, reason);
2411         }
2412 }
2413
2414 /**
2415  * nm_device_is_master:
2416  * @self: the device
2417  *
2418  * Returns: %TRUE if the device can have slaves
2419  */
2420 gboolean
2421 nm_device_is_master (NMDevice *self)
2422 {
2423         return NM_DEVICE_GET_PRIVATE (self)->is_master;
2424 }
2425
2426 /**
2427  * nm_device_get_master:
2428  * @self: the device
2429  *
2430  * If @self has been enslaved by another device, this returns that
2431  * device. Otherwise it returns %NULL. (In particular, note that if
2432  * @self is in the process of activating as a slave, but has not yet
2433  * been enslaved by its master, this will return %NULL.)
2434  *
2435  * Returns: (transfer none): @self's master, or %NULL
2436  */
2437 NMDevice *
2438 nm_device_get_master (NMDevice *self)
2439 {
2440         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
2441
2442         if (priv->is_enslaved) {
2443                 g_return_val_if_fail (priv->master, NULL);
2444                 return priv->master;
2445         }
2446         return NULL;
2447 }
2448
2449 /**
2450  * nm_device_slave_notify_enslave:
2451  * @self: the slave device
2452  * @success: whether the enslaving operation succeeded
2453  *
2454  * Notifies a slave that either it has been enslaved, or else its master tried
2455  * to enslave it and failed.
2456  */
2457 static void
2458 nm_device_slave_notify_enslave (NMDevice *self, gboolean success)
2459 {
2460         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
2461         NMConnection *connection = nm_device_get_applied_connection (self);
2462         gboolean activating = (priv->state == NM_DEVICE_STATE_IP_CONFIG);
2463
2464         g_return_if_fail (priv->master);
2465
2466         if (!priv->is_enslaved) {
2467                 if (success) {
2468                         if (activating) {
2469                                 _LOGI (LOGD_DEVICE, "Activation: connection '%s' enslaved, continuing activation",
2470                                        nm_connection_get_id (connection));
2471                         } else
2472                                 _LOGI (LOGD_DEVICE, "enslaved to %s", nm_device_get_iface (priv->master));
2473
2474                         priv->is_enslaved = TRUE;
2475                         _notify (self, PROP_MASTER);
2476                         _notify (priv->master, PROP_SLAVES);
2477                 } else if (activating) {
2478                         _LOGW (LOGD_DEVICE, "Activation: connection '%s' could not be enslaved",
2479                                nm_connection_get_id (connection));
2480                 }
2481         }
2482
2483         if (activating) {
2484                 priv->ip4_state = IP_DONE;
2485                 priv->ip6_state = IP_DONE;
2486                 if (success)
2487                         nm_device_queue_state (self, NM_DEVICE_STATE_SECONDARIES, NM_DEVICE_STATE_REASON_NONE);
2488                 else
2489                         nm_device_queue_state (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_UNKNOWN);
2490         } else
2491                 nm_device_queue_recheck_assume (self);
2492 }
2493
2494 /**
2495  * nm_device_slave_notify_release:
2496  * @self: the slave device
2497  * @reason: the reason associated with the state change
2498  *
2499  * Notifies a slave that it has been released, and why.
2500  */
2501 static void
2502 nm_device_slave_notify_release (NMDevice *self, NMDeviceStateReason reason)
2503 {
2504         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
2505         NMConnection *connection = nm_device_get_applied_connection (self);
2506         NMDeviceState new_state;
2507         const char *master_status;
2508
2509         g_return_if_fail (priv->master);
2510
2511         if (   priv->state > NM_DEVICE_STATE_DISCONNECTED
2512             && priv->state <= NM_DEVICE_STATE_ACTIVATED) {
2513                 if (reason == NM_DEVICE_STATE_REASON_DEPENDENCY_FAILED) {
2514                         new_state = NM_DEVICE_STATE_FAILED;
2515                         master_status = "failed";
2516                 } else if (reason == NM_DEVICE_STATE_REASON_USER_REQUESTED) {
2517                         new_state = NM_DEVICE_STATE_DEACTIVATING;
2518                         master_status = "deactivated by user request";
2519                 } else {
2520                         new_state = NM_DEVICE_STATE_DISCONNECTED;
2521                         master_status = "deactivated";
2522                 }
2523
2524                 _LOGD (LOGD_DEVICE, "Activation: connection '%s' master %s",
2525                        nm_connection_get_id (connection),
2526                        master_status);
2527
2528                 nm_device_queue_state (self, new_state, reason);
2529         } else
2530                 _LOGI (LOGD_DEVICE, "released from master device %s", nm_device_get_iface (priv->master));
2531
2532         if (priv->is_enslaved) {
2533                 priv->is_enslaved = FALSE;
2534                 _notify (self, PROP_MASTER);
2535                 _notify (priv->master, PROP_SLAVES);
2536         }
2537 }
2538
2539 /**
2540  * nm_device_get_enslaved:
2541  * @self: the #NMDevice
2542  *
2543  * Returns: %TRUE if the device is enslaved to a master device (eg bridge or
2544  * bond or team), %FALSE if not
2545  */
2546 gboolean
2547 nm_device_get_enslaved (NMDevice *self)
2548 {
2549         return NM_DEVICE_GET_PRIVATE (self)->is_enslaved;
2550 }
2551
2552 /**
2553  * nm_device_removed:
2554  * @self: the #NMDevice
2555  *
2556  * Called by the manager when the device was removed. Releases the device from
2557  * the master in case it's enslaved.
2558  */
2559 void
2560 nm_device_removed (NMDevice *self)
2561 {
2562         NMDevicePrivate *priv;
2563
2564         g_return_if_fail (NM_IS_DEVICE (self));
2565
2566         priv = NM_DEVICE_GET_PRIVATE (self);
2567         if (priv->master) {
2568                 /* this is called when something externally messes with the slave or during shut-down.
2569                  * Release the slave from master, but don't touch the device. */
2570                 nm_device_master_release_one_slave (priv->master, self, FALSE, NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED);
2571         }
2572 }
2573
2574 static gboolean
2575 is_available (NMDevice *self, NMDeviceCheckDevAvailableFlags flags)
2576 {
2577         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
2578
2579         if (priv->carrier || priv->ignore_carrier)
2580                 return TRUE;
2581
2582         if (NM_FLAGS_HAS (flags, _NM_DEVICE_CHECK_DEV_AVAILABLE_IGNORE_CARRIER))
2583                 return TRUE;
2584
2585         return FALSE;
2586 }
2587
2588 /**
2589  * nm_device_is_available:
2590  * @self: the #NMDevice
2591  * @flags: additional flags to influence the check. Flags have the
2592  *   meaning to increase the availability of a device.
2593  *
2594  * Checks if @self would currently be capable of activating a
2595  * connection. In particular, it checks that the device is ready (eg,
2596  * is not missing firmware), that it has carrier (if necessary), and
2597  * that any necessary external software (eg, ModemManager,
2598  * wpa_supplicant) is available.
2599  *
2600  * @self can only be in a state higher than
2601  * %NM_DEVICE_STATE_UNAVAILABLE when nm_device_is_available() returns
2602  * %TRUE. (But note that it can still be %NM_DEVICE_STATE_UNMANAGED
2603  * when it is available.)
2604  *
2605  * Returns: %TRUE or %FALSE
2606  */
2607 gboolean
2608 nm_device_is_available (NMDevice *self, NMDeviceCheckDevAvailableFlags flags)
2609 {
2610         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
2611
2612         if (priv->firmware_missing)
2613                 return FALSE;
2614
2615         return NM_DEVICE_GET_CLASS (self)->is_available (self, flags);
2616 }
2617
2618 gboolean
2619 nm_device_get_enabled (NMDevice *self)
2620 {
2621         g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
2622
2623         if (NM_DEVICE_GET_CLASS (self)->get_enabled)
2624                 return NM_DEVICE_GET_CLASS (self)->get_enabled (self);
2625         return TRUE;
2626 }
2627
2628 void
2629 nm_device_set_enabled (NMDevice *self, gboolean enabled)
2630 {
2631         g_return_if_fail (NM_IS_DEVICE (self));
2632
2633         if (NM_DEVICE_GET_CLASS (self)->set_enabled)
2634                 NM_DEVICE_GET_CLASS (self)->set_enabled (self, enabled);
2635 }
2636
2637 /**
2638  * nm_device_get_autoconnect:
2639  * @self: the #NMDevice
2640  *
2641  * Returns: %TRUE if the device allows autoconnect connections, or %FALSE if the
2642  * device is explicitly blocking all autoconnect connections.  Does not take
2643  * into account transient conditions like companion devices that may wish to
2644  * block the device.
2645  */
2646 gboolean
2647 nm_device_get_autoconnect (NMDevice *self)
2648 {
2649         g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
2650
2651         return NM_DEVICE_GET_PRIVATE (self)->autoconnect;
2652 }
2653
2654 void
2655 nm_device_set_autoconnect (NMDevice *self, gboolean autoconnect)
2656 {
2657         NMDevicePrivate *priv;
2658
2659         g_return_if_fail (NM_IS_DEVICE (self));
2660
2661         autoconnect = !!autoconnect;
2662
2663         priv = NM_DEVICE_GET_PRIVATE (self);
2664         if (priv->autoconnect != autoconnect) {
2665                 priv->autoconnect = autoconnect;
2666                 _notify (self, PROP_AUTOCONNECT);
2667         }
2668 }
2669
2670 static gboolean
2671 autoconnect_allowed_accumulator (GSignalInvocationHint *ihint,
2672                                  GValue *return_accu,
2673                                  const GValue *handler_return, gpointer data)
2674 {
2675         if (!g_value_get_boolean (handler_return))
2676                 g_value_set_boolean (return_accu, FALSE);
2677         return TRUE;
2678 }
2679
2680 /**
2681  * nm_device_autoconnect_allowed:
2682  * @self: the #NMDevice
2683  *
2684  * Returns: %TRUE if the device can be auto-connected immediately, taking
2685  * transient conditions into account (like companion devices that may wish to
2686  * block autoconnect for a time).
2687  */
2688 gboolean
2689 nm_device_autoconnect_allowed (NMDevice *self)
2690 {
2691         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
2692         GValue instance = G_VALUE_INIT;
2693         GValue retval = G_VALUE_INIT;
2694
2695         if (!priv->autoconnect)
2696                 return FALSE;
2697
2698         /* Unrealized devices can always autoconnect. */
2699         if (nm_device_is_real (self) && priv->state < NM_DEVICE_STATE_DISCONNECTED)
2700                 return FALSE;
2701
2702         /* The 'autoconnect-allowed' signal is emitted on a device to allow
2703          * other listeners to block autoconnect on the device if they wish.
2704          * This is mainly used by the OLPC Mesh devices to block autoconnect
2705          * on their companion WiFi device as they share radio resources and
2706          * cannot be connected at the same time.
2707          */
2708
2709         g_value_init (&instance, G_TYPE_OBJECT);
2710         g_value_set_object (&instance, self);
2711
2712         g_value_init (&retval, G_TYPE_BOOLEAN);
2713         g_value_set_boolean (&retval, TRUE);
2714
2715         /* Use g_signal_emitv() rather than g_signal_emit() to avoid the return
2716          * value being changed if no handlers are connected */
2717         g_signal_emitv (&instance, signals[AUTOCONNECT_ALLOWED], 0, &retval);
2718         g_value_unset (&instance);
2719
2720         return g_value_get_boolean (&retval);
2721 }
2722
2723 static gboolean
2724 can_auto_connect (NMDevice *self,
2725                   NMConnection *connection,
2726                   char **specific_object)
2727 {
2728         NMSettingConnection *s_con;
2729
2730         s_con = nm_connection_get_setting_connection (connection);
2731         if (!nm_setting_connection_get_autoconnect (s_con))
2732                 return FALSE;
2733
2734         return nm_device_check_connection_available (self, connection, NM_DEVICE_CHECK_CON_AVAILABLE_NONE, NULL);
2735 }
2736
2737 /**
2738  * nm_device_can_auto_connect:
2739  * @self: an #NMDevice
2740  * @connection: a #NMConnection
2741  * @specific_object: (out) (transfer full): on output, the path of an
2742  *   object associated with the returned connection, to be passed to
2743  *   nm_manager_activate_connection(), or %NULL.
2744  *
2745  * Checks if @connection can be auto-activated on @self right now.
2746  * This requires, at a minimum, that the connection be compatible with
2747  * @self, and that it have the #NMSettingConnection:autoconnect property
2748  * set, and that the device allow auto connections. Some devices impose
2749  * additional requirements. (Eg, a Wi-Fi connection can only be activated
2750  * if its SSID was seen in the last scan.)
2751  *
2752  * Returns: %TRUE, if the @connection can be auto-activated.
2753  **/
2754 gboolean
2755 nm_device_can_auto_connect (NMDevice *self,
2756                             NMConnection *connection,
2757                             char **specific_object)
2758 {
2759         g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
2760         g_return_val_if_fail (NM_IS_CONNECTION (connection), FALSE);
2761         g_return_val_if_fail (specific_object && !*specific_object, FALSE);
2762
2763         if (nm_device_autoconnect_allowed (self))
2764                 return NM_DEVICE_GET_CLASS (self)->can_auto_connect (self, connection, specific_object);
2765         return FALSE;
2766 }
2767
2768 static gboolean
2769 device_has_config (NMDevice *self)
2770 {
2771         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
2772
2773         /* Check for IP configuration. */
2774         if (priv->ip4_config && nm_ip4_config_get_num_addresses (priv->ip4_config))
2775                 return TRUE;
2776         if (priv->ip6_config && nm_ip6_config_get_num_addresses (priv->ip6_config))
2777                 return TRUE;
2778
2779         /* The existence of a software device is good enough. */
2780         if (nm_device_is_software (self) && nm_device_is_real (self))
2781                 return TRUE;
2782
2783         /* Slaves are also configured by definition */
2784         if (nm_platform_link_get_master (NM_PLATFORM_GET, priv->ifindex) > 0)
2785                 return TRUE;
2786
2787         return FALSE;
2788 }
2789
2790 /**
2791  * nm_device_master_update_slave_connection:
2792  * @self: the master #NMDevice
2793  * @slave: the slave #NMDevice
2794  * @connection: the #NMConnection to update with the slave settings
2795  * @GError: (out): error description
2796  *
2797  * Reads the slave configuration for @slave and updates @connection with those
2798  * properties. This invokes a virtual function on the master device @self.
2799  *
2800  * Returns: %TRUE if the configuration was read and @connection updated,
2801  * %FALSE on failure.
2802  */
2803 gboolean
2804 nm_device_master_update_slave_connection (NMDevice *self,
2805                                           NMDevice *slave,
2806                                           NMConnection *connection,
2807                                           GError **error)
2808 {
2809         NMDeviceClass *klass;
2810         gboolean success;
2811
2812         g_return_val_if_fail (self, FALSE);
2813         g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
2814         g_return_val_if_fail (slave, FALSE);
2815         g_return_val_if_fail (connection, FALSE);
2816         g_return_val_if_fail (!error || !*error, FALSE);
2817         g_return_val_if_fail (nm_connection_get_setting_connection (connection), FALSE);
2818
2819         g_return_val_if_fail (nm_device_get_iface (self), FALSE);
2820
2821         klass = NM_DEVICE_GET_CLASS (self);
2822         if (klass->master_update_slave_connection) {
2823                 success = klass->master_update_slave_connection (self, slave, connection, error);
2824
2825                 g_return_val_if_fail (!error || (success && !*error) || *error, success);
2826                 return success;
2827         }
2828
2829         g_set_error (error,
2830                      NM_DEVICE_ERROR,
2831                      NM_DEVICE_ERROR_FAILED,
2832                      "master device '%s' cannot update a slave connection for slave device '%s' (master type not supported?)",
2833                      nm_device_get_iface (self), nm_device_get_iface (slave));
2834         return FALSE;
2835 }
2836
2837 NMConnection *
2838 nm_device_generate_connection (NMDevice *self, NMDevice *master)
2839 {
2840         NMDeviceClass *klass = NM_DEVICE_GET_CLASS (self);
2841         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
2842         const char *ifname = nm_device_get_iface (self);
2843         NMConnection *connection;
2844         NMSetting *s_con;
2845         NMSetting *s_ip4;
2846         NMSetting *s_ip6;
2847         gs_free char *uuid = NULL;
2848         const char *ip4_method, *ip6_method;
2849         GError *error = NULL;
2850
2851         /* If update_connection() is not implemented, just fail. */
2852         if (!klass->update_connection)
2853                 return NULL;
2854
2855         /* Return NULL if device is unconfigured. */
2856         if (!device_has_config (self)) {
2857                 _LOGD (LOGD_DEVICE, "device has no existing configuration");
2858                 return NULL;
2859         }
2860
2861         connection = nm_simple_connection_new ();
2862         s_con = nm_setting_connection_new ();
2863         uuid = nm_utils_uuid_generate ();
2864
2865         g_object_set (s_con,
2866                       NM_SETTING_CONNECTION_UUID, uuid,
2867                       NM_SETTING_CONNECTION_ID, ifname,
2868                       NM_SETTING_CONNECTION_AUTOCONNECT, FALSE,
2869                       NM_SETTING_CONNECTION_INTERFACE_NAME, ifname,
2870                       NM_SETTING_CONNECTION_TIMESTAMP, (guint64) time (NULL),
2871                       NULL);
2872         if (klass->connection_type)
2873                 g_object_set (s_con, NM_SETTING_CONNECTION_TYPE, klass->connection_type, NULL);
2874         nm_connection_add_setting (connection, s_con);
2875
2876         /* If the device is a slave, update various slave settings */
2877         if (master) {
2878                 if (!nm_device_master_update_slave_connection (master,
2879                                                                self,
2880                                                                connection,
2881                                                                &error))
2882                 {
2883                         _LOGE (LOGD_DEVICE, "master device '%s' failed to update slave connection: %s",
2884                                nm_device_get_iface (master), error->message);
2885                         g_error_free (error);
2886                         g_object_unref (connection);
2887                         return NULL;
2888                 }
2889         } else {
2890                 /* Only regular and master devices get IP configuration; slaves do not */
2891                 s_ip4 = nm_ip4_config_create_setting (priv->ip4_config);
2892                 nm_connection_add_setting (connection, s_ip4);
2893
2894                 s_ip6 = nm_ip6_config_create_setting (priv->ip6_config);
2895                 nm_connection_add_setting (connection, s_ip6);
2896         }
2897
2898         klass->update_connection (self, connection);
2899
2900         /* Check the connection in case of update_connection() bug. */
2901         if (!nm_connection_verify (connection, &error)) {
2902                 _LOGE (LOGD_DEVICE, "Generated connection does not verify: %s", error->message);
2903                 g_clear_error (&error);
2904                 g_object_unref (connection);
2905                 return NULL;
2906         }
2907
2908         /* Ignore the connection if it has no IP configuration,
2909          * no slave configuration, and is not a master interface.
2910          */
2911         ip4_method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG);
2912         ip6_method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG);
2913         if (   g_strcmp0 (ip4_method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED) == 0
2914             && g_strcmp0 (ip6_method, NM_SETTING_IP6_CONFIG_METHOD_IGNORE) == 0
2915             && !nm_setting_connection_get_master (NM_SETTING_CONNECTION (s_con))
2916             && !priv->slaves) {
2917                 _LOGD (LOGD_DEVICE, "ignoring generated connection (no IP and not in master-slave relationship)");
2918                 g_object_unref (connection);
2919                 connection = NULL;
2920         }
2921
2922         /* Ignore any IPv6LL-only, not master connections without slaves,
2923          * unless they are in the assume-ipv6ll-only list.
2924          */
2925         if (   connection
2926             && g_strcmp0 (ip4_method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED) == 0
2927             && g_strcmp0 (ip6_method, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL) == 0
2928             && !nm_setting_connection_get_master (NM_SETTING_CONNECTION (s_con))
2929             && !priv->slaves
2930             && !nm_config_data_get_assume_ipv6ll_only (NM_CONFIG_GET_DATA, self)) {
2931                 _LOGD (LOGD_DEVICE, "ignoring generated connection (IPv6LL-only and not in master-slave relationship)");
2932                 g_object_unref (connection);
2933                 connection = NULL;
2934         }
2935
2936         return connection;
2937 }
2938
2939 gboolean
2940 nm_device_complete_connection (NMDevice *self,
2941                                NMConnection *connection,
2942                                const char *specific_object,
2943                                const GSList *existing_connections,
2944                                GError **error)
2945 {
2946         gboolean success = FALSE;
2947
2948         g_return_val_if_fail (self != NULL, FALSE);
2949         g_return_val_if_fail (connection != NULL, FALSE);
2950
2951         if (!NM_DEVICE_GET_CLASS (self)->complete_connection) {
2952                 g_set_error (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_INVALID_CONNECTION,
2953                              "Device class %s had no complete_connection method",
2954                              G_OBJECT_TYPE_NAME (self));
2955                 return FALSE;
2956         }
2957
2958         success = NM_DEVICE_GET_CLASS (self)->complete_connection (self,
2959                                                                    connection,
2960                                                                    specific_object,
2961                                                                    existing_connections,
2962                                                                    error);
2963         if (success)
2964                 success = nm_connection_verify (connection, error);
2965
2966         return success;
2967 }
2968
2969 static gboolean
2970 check_connection_compatible (NMDevice *self, NMConnection *connection)
2971 {
2972         const char *device_iface = nm_device_get_iface (self);
2973         gs_free char *conn_iface = nm_manager_get_connection_iface (nm_manager_get (),
2974                                                                     connection,
2975                                                                     NULL, NULL);
2976
2977         /* We always need a interface name for virtual devices, but for
2978          * physical ones a connection without interface name is fine for
2979          * any device. */
2980         if (!conn_iface)
2981                 return !nm_connection_is_virtual (connection);
2982
2983         if (strcmp (conn_iface, device_iface) != 0)
2984                 return FALSE;
2985
2986         return TRUE;
2987 }
2988
2989 /**
2990  * nm_device_check_connection_compatible:
2991  * @self: an #NMDevice
2992  * @connection: an #NMConnection
2993  *
2994  * Checks if @connection could potentially be activated on @self.
2995  * This means only that @self has the proper capabilities, and that
2996  * @connection is not locked to some other device. It does not
2997  * necessarily mean that @connection could be activated on @self
2998  * right now. (Eg, it might refer to a Wi-Fi network that is not
2999  * currently available.)
3000  *
3001  * Returns: #TRUE if @connection could potentially be activated on
3002  *   @self.
3003  */
3004 gboolean
3005 nm_device_check_connection_compatible (NMDevice *self, NMConnection *connection)
3006 {
3007         g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
3008         g_return_val_if_fail (NM_IS_CONNECTION (connection), FALSE);
3009
3010         return NM_DEVICE_GET_CLASS (self)->check_connection_compatible (self, connection);
3011 }
3012
3013 gboolean
3014 nm_device_check_slave_connection_compatible (NMDevice *self, NMConnection *slave)
3015 {
3016         NMDevicePrivate *priv;
3017         NMSettingConnection *s_con;
3018         const char *connection_type, *slave_type;
3019
3020         g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
3021         g_return_val_if_fail (NM_IS_CONNECTION (slave), FALSE);
3022
3023         priv = NM_DEVICE_GET_PRIVATE (self);
3024
3025         if (!priv->is_master)
3026                 return FALSE;
3027
3028         /* All masters should have connection type set */
3029         connection_type = NM_DEVICE_GET_CLASS (self)->connection_type;
3030         g_return_val_if_fail (connection_type, FALSE);
3031
3032         s_con = nm_connection_get_setting_connection (slave);
3033         g_assert (s_con);
3034         slave_type = nm_setting_connection_get_slave_type (s_con);
3035         if (!slave_type)
3036                 return FALSE;
3037
3038         return strcmp (connection_type, slave_type) == 0;
3039 }
3040
3041 /**
3042  * nm_device_can_assume_connections:
3043  * @self: #NMDevice instance
3044  *
3045  * This is a convenience function to determine whether connection assumption
3046  * is available for this device.
3047  *
3048  * Returns: %TRUE if the device is capable of assuming connections, %FALSE if not
3049  */
3050 static gboolean
3051 nm_device_can_assume_connections (NMDevice *self)
3052 {
3053         return   !!NM_DEVICE_GET_CLASS (self)->update_connection
3054               && !NM_DEVICE_GET_PRIVATE (self)->is_nm_owned;
3055 }
3056
3057 /**
3058  * nm_device_can_assume_active_connection:
3059  * @self: #NMDevice instance
3060  *
3061  * This is a convenience function to determine whether the device's active
3062  * connection can be assumed if NetworkManager restarts.  This method returns
3063  * %TRUE if and only if the device can assume connections, and the device has
3064  * an active connection, and that active connection can be assumed.
3065  *
3066  * Returns: %TRUE if the device's active connection can be assumed, or %FALSE
3067  * if there is no active connection or the active connection cannot be
3068  * assumed.
3069  */
3070 gboolean
3071 nm_device_can_assume_active_connection (NMDevice *self)
3072 {
3073         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
3074         NMConnection *connection;
3075         const char *method;
3076         const char *assumable_ip6_methods[] = {
3077                 NM_SETTING_IP6_CONFIG_METHOD_IGNORE,
3078                 NM_SETTING_IP6_CONFIG_METHOD_AUTO,
3079                 NM_SETTING_IP6_CONFIG_METHOD_DHCP,
3080                 NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL,
3081                 NM_SETTING_IP6_CONFIG_METHOD_MANUAL,
3082                 NULL
3083         };
3084         const char *assumable_ip4_methods[] = {
3085                 NM_SETTING_IP4_CONFIG_METHOD_DISABLED,
3086                 NM_SETTING_IP6_CONFIG_METHOD_AUTO,
3087                 NM_SETTING_IP6_CONFIG_METHOD_MANUAL,
3088                 NULL
3089         };
3090
3091         if (!nm_device_can_assume_connections (self))
3092                 return FALSE;
3093
3094         connection = nm_device_get_applied_connection (self);
3095         if (!connection)
3096                 return FALSE;
3097
3098         /* Can't assume connections that aren't yet configured
3099          * FIXME: what about bridges/bonds waiting for slaves?
3100          */
3101         if (priv->state < NM_DEVICE_STATE_IP_CONFIG)
3102                 return FALSE;
3103         if (priv->ip4_state != IP_DONE && priv->ip6_state != IP_DONE)
3104                 return FALSE;
3105
3106         method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG);
3107         if (!_nm_utils_string_in_list (method, assumable_ip6_methods))
3108                 return FALSE;
3109
3110         method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG);
3111         if (!_nm_utils_string_in_list (method, assumable_ip4_methods))
3112                 return FALSE;
3113
3114         return TRUE;
3115 }
3116
3117 static gboolean
3118 nm_device_emit_recheck_assume (gpointer user_data)
3119 {
3120         NMDevice *self = user_data;
3121         NMDevicePrivate *priv;
3122
3123         g_return_val_if_fail (NM_IS_DEVICE (self), G_SOURCE_REMOVE);
3124
3125         priv = NM_DEVICE_GET_PRIVATE (self);
3126
3127         priv->recheck_assume_id = 0;
3128         if (!nm_device_get_act_request (self)) {
3129                 _LOGD (LOGD_DEVICE, "emit RECHECK_ASSUME signal");
3130                 g_signal_emit (self, signals[RECHECK_ASSUME], 0);
3131         }
3132         return G_SOURCE_REMOVE;
3133 }
3134
3135 void
3136 nm_device_queue_recheck_assume (NMDevice *self)
3137 {
3138         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
3139
3140         if (   !priv->recheck_assume_id
3141             && nm_device_can_assume_connections (self))
3142                 priv->recheck_assume_id = g_idle_add (nm_device_emit_recheck_assume, self);
3143 }
3144
3145 static gboolean
3146 recheck_available (gpointer user_data)
3147 {
3148         NMDevice *self = NM_DEVICE (user_data);
3149         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
3150         gboolean now_available = nm_device_is_available (self, NM_DEVICE_CHECK_DEV_AVAILABLE_NONE);
3151         NMDeviceState state = nm_device_get_state (self);
3152         NMDeviceState new_state = NM_DEVICE_STATE_UNKNOWN;
3153
3154         priv->recheck_available.call_id = 0;
3155
3156         if (state == NM_DEVICE_STATE_UNAVAILABLE && now_available) {
3157                 new_state = NM_DEVICE_STATE_DISCONNECTED;
3158                 nm_device_queue_state (self, new_state, priv->recheck_available.available_reason);
3159         } else if (state >= NM_DEVICE_STATE_DISCONNECTED && !now_available) {
3160                 new_state = NM_DEVICE_STATE_UNAVAILABLE;
3161                 nm_device_queue_state (self, new_state, priv->recheck_available.unavailable_reason);
3162         }
3163
3164         if (new_state > NM_DEVICE_STATE_UNKNOWN) {
3165                 _LOGD (LOGD_DEVICE, "is %savailable, %s %s",
3166                            now_available ? "" : "not ",
3167                            new_state == NM_DEVICE_STATE_UNAVAILABLE ? "no change required for" : "will transition to",
3168                            state_to_string (new_state == NM_DEVICE_STATE_UNAVAILABLE ? state : new_state));
3169
3170                 priv->recheck_available.available_reason = NM_DEVICE_STATE_REASON_NONE;
3171                 priv->recheck_available.unavailable_reason = NM_DEVICE_STATE_REASON_NONE;
3172         }
3173
3174         return G_SOURCE_REMOVE;
3175 }
3176
3177 void
3178 nm_device_queue_recheck_available (NMDevice *self,
3179                                    NMDeviceStateReason available_reason,
3180                                    NMDeviceStateReason unavailable_reason)
3181 {
3182         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
3183
3184         priv->recheck_available.available_reason = available_reason;
3185         priv->recheck_available.unavailable_reason = unavailable_reason;
3186         if (!priv->recheck_available.call_id)
3187                 priv->recheck_available.call_id = g_idle_add (recheck_available, self);
3188 }
3189
3190 void
3191 nm_device_emit_recheck_auto_activate (NMDevice *self)
3192 {
3193         g_signal_emit (self, signals[RECHECK_AUTO_ACTIVATE], 0);
3194 }
3195
3196 static void
3197 dnsmasq_state_changed_cb (NMDnsMasqManager *manager, guint32 status, gpointer user_data)
3198 {
3199         NMDevice *self = NM_DEVICE (user_data);
3200
3201         switch (status) {
3202         case NM_DNSMASQ_STATUS_DEAD:
3203                 nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_SHARED_START_FAILED);
3204                 break;
3205         default:
3206                 break;
3207         }
3208 }
3209
3210 /*****************************************************************************/
3211
3212 static gboolean
3213 activation_source_handle_cb4 (gpointer user_data)
3214 {
3215         activation_source_handle_cb (user_data, AF_INET);
3216         return G_SOURCE_REMOVE;
3217 }
3218
3219 static gboolean
3220 activation_source_handle_cb6 (gpointer user_data)
3221 {
3222         activation_source_handle_cb (user_data, AF_INET6);
3223         return G_SOURCE_REMOVE;
3224 }
3225
3226 static ActivationHandleData *
3227 activation_source_get_by_family (NMDevice *self,
3228                                  int family,
3229                                  GSourceFunc *out_idle_func)
3230 {
3231         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
3232
3233         if (family == AF_INET6) {
3234                 NM_SET_OUT (out_idle_func, activation_source_handle_cb6);
3235                 return &priv->act_handle6;
3236         } else {
3237                 NM_SET_OUT (out_idle_func, activation_source_handle_cb4);
3238                 g_return_val_if_fail (family == AF_INET, &priv->act_handle4);
3239                 return &priv->act_handle4;
3240         }
3241 }
3242
3243 static void
3244 activation_source_clear (NMDevice *self, int family)
3245 {
3246         ActivationHandleData *act_data;
3247
3248         act_data = activation_source_get_by_family (self, family, NULL);
3249
3250         if (act_data->id) {
3251                 _LOGD (LOGD_DEVICE, "activation-stage: clear %s,%d (id %u)",
3252                        _activation_func_to_string (act_data->func), family, act_data->id);
3253                 nm_clear_g_source (&act_data->id);
3254                 act_data->func = NULL;
3255         }
3256 }
3257
3258 static void
3259 activation_source_handle_cb (NMDevice *self, int family)
3260 {
3261         ActivationHandleData *act_data, a;
3262
3263         g_return_if_fail (NM_IS_DEVICE (self));
3264
3265         act_data = activation_source_get_by_family (self, family, NULL);
3266
3267         g_return_if_fail (act_data->id);
3268         g_return_if_fail (act_data->func);
3269
3270         a = *act_data;
3271
3272         act_data->func = NULL;
3273         act_data->id = 0;
3274
3275         _LOGD (LOGD_DEVICE, "activation-stage: invoke %s,%d (id %u)",
3276                _activation_func_to_string (a.func), family, a.id);
3277
3278         a.func (self);
3279
3280         _LOGD (LOGD_DEVICE, "activation-stage: complete %s,%d (id %u)",
3281                _activation_func_to_string (a.func), family, a.id);
3282 }
3283
3284 static void
3285 activation_source_schedule (NMDevice *self, ActivationHandleFunc func, int family)
3286 {
3287         ActivationHandleData *act_data;
3288         GSourceFunc source_func;
3289         guint new_id = 0;
3290
3291         act_data = activation_source_get_by_family (self, family, &source_func);
3292
3293         if (act_data->id && act_data->func != func) {
3294                 /* Don't bother rescheduling the same function that's about to
3295                  * run anyway.  Fixes issues with crappy wireless drivers sending
3296                  * streams of associate events before NM has had a chance to process
3297                  * the first one.
3298                  */
3299                 _LOGD (LOGD_DEVICE, "activation-stage: already scheduled %s,%d (id %u)",
3300                        _activation_func_to_string (func), family, act_data->id);
3301                 return;
3302         }
3303
3304         new_id = g_idle_add (source_func, self);
3305
3306         if (act_data->id) {
3307                 _LOGW (LOGD_DEVICE, "activation-stage: schedule %s,%d which replaces %s,%d (id %u -> %u)",
3308                        _activation_func_to_string (func), family,
3309                        _activation_func_to_string (act_data->func), family,
3310                        act_data->id, new_id);
3311                 nm_clear_g_source (&act_data->id);
3312         } else {
3313                 _LOGD (LOGD_DEVICE, "activation-stage: schedule %s,%d (id %u)",
3314                        _activation_func_to_string (func), family, new_id);
3315         }
3316
3317         act_data->func = func;
3318         act_data->id = new_id;
3319 }
3320
3321 /*****************************************************************************/
3322
3323 static gboolean
3324 get_ip_config_may_fail (NMDevice *self, int family)
3325 {
3326         NMConnection *connection;
3327         NMSettingIPConfig *s_ip = NULL;
3328
3329         g_return_val_if_fail (self != NULL, TRUE);
3330
3331         connection = nm_device_get_applied_connection (self);
3332         g_assert (connection);
3333
3334         /* Fail the connection if the failed IP method is required to complete */
3335         switch (family) {
3336         case AF_INET:
3337                 s_ip = nm_connection_get_setting_ip4_config (connection);
3338                 break;
3339         case AF_INET6:
3340                 s_ip = nm_connection_get_setting_ip6_config (connection);
3341                 break;
3342         default:
3343                 g_assert_not_reached ();
3344         }
3345
3346         return nm_setting_ip_config_get_may_fail (s_ip);
3347 }
3348
3349 static void
3350 master_ready (NMDevice *self,
3351               NMActiveConnection *active)
3352 {
3353         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
3354         NMActiveConnection *master_connection;
3355         NMDevice *master;
3356
3357         g_return_if_fail (priv->state == NM_DEVICE_STATE_PREPARE);
3358         g_return_if_fail (!priv->master_ready_handled);
3359
3360         /* Notify a master device that it has a new slave */
3361         g_return_if_fail (nm_active_connection_get_master_ready (active));
3362         master_connection = nm_active_connection_get_master (active);
3363
3364         priv->master_ready_handled = TRUE;
3365         nm_clear_g_signal_handler (active, &priv->master_ready_id);
3366
3367         master = nm_active_connection_get_device (master_connection);
3368
3369         _LOGD (LOGD_DEVICE, "master connection ready; master device %s",
3370                nm_device_get_iface (master));
3371
3372         if (priv->master && priv->master != master)
3373                 nm_device_master_release_one_slave (priv->master, self, FALSE, NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED);
3374
3375         /* If the master didn't change, add-slave only rechecks whether to assume a connection. */
3376         nm_device_master_add_slave (master,
3377                                     self,
3378                                     nm_active_connection_get_assumed (active) ? FALSE : TRUE);
3379 }
3380
3381 static void
3382 master_ready_cb (NMActiveConnection *active,
3383                  GParamSpec *pspec,
3384                  NMDevice *self)
3385 {
3386         master_ready (self, active);
3387         nm_device_activate_schedule_stage2_device_config (self);
3388 }
3389
3390 static void
3391 lldp_neighbors_changed (NMLldpListener *lldp_listener, GParamSpec *pspec,
3392                         gpointer user_data)
3393 {
3394         NMDevice *self = NM_DEVICE (user_data);
3395
3396         _notify (self, PROP_LLDP_NEIGHBORS);
3397 }
3398
3399 static gboolean
3400 lldp_rx_enabled (NMDevice *self)
3401 {
3402         NMConnection *connection;
3403         NMSettingConnection *s_con;
3404         NMSettingConnectionLldp lldp = NM_SETTING_CONNECTION_LLDP_DEFAULT;
3405
3406         connection = nm_device_get_applied_connection (self);
3407         g_return_val_if_fail (connection, FALSE);
3408
3409         s_con = nm_connection_get_setting_connection (connection);
3410         g_return_val_if_fail (s_con, FALSE);
3411
3412         lldp = nm_setting_connection_get_lldp (s_con);
3413         if (lldp == NM_SETTING_CONNECTION_LLDP_DEFAULT) {
3414                 gs_free char *value = NULL;
3415
3416                 value = nm_config_data_get_connection_default (NM_CONFIG_GET_DATA,
3417                                                                "connection.lldp",
3418                                                                self);
3419                 lldp = _nm_utils_ascii_str_to_int64 (value, 10,
3420                                                      NM_SETTING_CONNECTION_LLDP_DEFAULT,
3421                                                      NM_SETTING_CONNECTION_LLDP_ENABLE_RX,
3422                                                      NM_SETTING_CONNECTION_LLDP_DEFAULT);
3423                 if (lldp == NM_SETTING_CONNECTION_LLDP_DEFAULT)
3424                         lldp = NM_SETTING_CONNECTION_LLDP_DISABLE;
3425         }
3426         return lldp == NM_SETTING_CONNECTION_LLDP_ENABLE_RX;
3427 }
3428
3429 static NMActStageReturn
3430 act_stage1_prepare (NMDevice *self, NMDeviceStateReason *reason)
3431 {
3432         return NM_ACT_STAGE_RETURN_SUCCESS;
3433 }
3434
3435 /*
3436  * activate_stage1_device_prepare
3437  *
3438  * Prepare for device activation
3439  *
3440  */
3441 static void
3442 activate_stage1_device_prepare (NMDevice *self)
3443 {
3444         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
3445         NMActStageReturn ret = NM_ACT_STAGE_RETURN_SUCCESS;
3446         NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE;
3447         NMActiveConnection *active = NM_ACTIVE_CONNECTION (priv->act_request);
3448
3449         priv->ip4_state = priv->ip6_state = IP_NONE;
3450
3451         /* Notify the new ActiveConnection along with the state change */
3452         _notify (self, PROP_ACTIVE_CONNECTION);
3453
3454         nm_device_state_changed (self, NM_DEVICE_STATE_PREPARE, NM_DEVICE_STATE_REASON_NONE);
3455
3456         /* Assumed connections were already set up outside NetworkManager */
3457         if (!nm_active_connection_get_assumed (active)) {
3458                 ret = NM_DEVICE_GET_CLASS (self)->act_stage1_prepare (self, &reason);
3459                 if (ret == NM_ACT_STAGE_RETURN_POSTPONE) {
3460                         return;
3461                 } else if (ret == NM_ACT_STAGE_RETURN_FAILURE) {
3462                         nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason);
3463                         return;
3464                 }
3465                 g_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS);
3466         }
3467
3468         nm_device_activate_schedule_stage2_device_config (self);
3469 }
3470
3471
3472 /*
3473  * nm_device_activate_schedule_stage1_device_prepare
3474  *
3475  * Prepare a device for activation
3476  *
3477  */
3478 void
3479 nm_device_activate_schedule_stage1_device_prepare (NMDevice *self)
3480 {
3481         NMDevicePrivate *priv;
3482
3483         g_return_if_fail (NM_IS_DEVICE (self));
3484
3485         priv = NM_DEVICE_GET_PRIVATE (self);
3486         g_return_if_fail (priv->act_request);
3487
3488         activation_source_schedule (self, activate_stage1_device_prepare, AF_INET);
3489 }
3490
3491 static NMActStageReturn
3492 act_stage2_config (NMDevice *self, NMDeviceStateReason *reason)
3493 {
3494         /* Nothing to do */
3495         return NM_ACT_STAGE_RETURN_SUCCESS;
3496 }
3497
3498 /*
3499  * activate_stage2_device_config
3500  *
3501  * Determine device parameters and set those on the device, ie
3502  * for wireless devices, set SSID, keys, etc.
3503  *
3504  */
3505 static void
3506 activate_stage2_device_config (NMDevice *self)
3507 {
3508         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
3509         NMActStageReturn ret;
3510         NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE;
3511         gboolean no_firmware = FALSE;
3512         NMActiveConnection *active = NM_ACTIVE_CONNECTION (priv->act_request);
3513         GSList *iter;
3514
3515         nm_device_state_changed (self, NM_DEVICE_STATE_CONFIG, NM_DEVICE_STATE_REASON_NONE);
3516
3517         /* Assumed connections were already set up outside NetworkManager */
3518         if (!nm_active_connection_get_assumed (active)) {
3519                 if (!nm_device_bring_up (self, FALSE, &no_firmware)) {
3520                         if (no_firmware)
3521                                 nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_FIRMWARE_MISSING);
3522                         else
3523                                 nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_CONFIG_FAILED);
3524                         return;
3525                 }
3526
3527                 ret = NM_DEVICE_GET_CLASS (self)->act_stage2_config (self, &reason);
3528                 if (ret == NM_ACT_STAGE_RETURN_POSTPONE)
3529                         return;
3530                 else if (ret == NM_ACT_STAGE_RETURN_FAILURE) {
3531                         nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason);
3532                         return;
3533                 }
3534                 g_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS);
3535         }
3536
3537         /* If we have slaves that aren't yet enslaved, do that now */
3538         for (iter = priv->slaves; iter; iter = g_slist_next (iter)) {
3539                 SlaveInfo *info = iter->data;
3540                 NMDeviceState slave_state = nm_device_get_state (info->slave);
3541
3542                 if (slave_state == NM_DEVICE_STATE_IP_CONFIG)
3543                         nm_device_master_enslave_slave (self, info->slave, nm_device_get_applied_connection (info->slave));
3544                 else if (   nm_device_uses_generated_assumed_connection (self)
3545                          && slave_state <= NM_DEVICE_STATE_DISCONNECTED)
3546                         nm_device_queue_recheck_assume (info->slave);
3547         }
3548
3549         if (lldp_rx_enabled (self)) {
3550                 gs_free_error GError *error = NULL;
3551                 gconstpointer addr;
3552                 size_t addr_length;
3553
3554                 if (priv->lldp_listener)
3555                         nm_lldp_listener_stop (priv->lldp_listener);
3556                 else {
3557                         priv->lldp_listener = nm_lldp_listener_new ();
3558                         g_signal_connect (priv->lldp_listener,
3559                                           "notify::" NM_LLDP_LISTENER_NEIGHBORS,
3560                                           G_CALLBACK (lldp_neighbors_changed),
3561                                           self);
3562                 }
3563
3564                 addr = nm_platform_link_get_address (NM_PLATFORM_GET, priv->ifindex, &addr_length);
3565
3566                 if (nm_lldp_listener_start (priv->lldp_listener, nm_device_get_ifindex (self), &error))
3567                         _LOGD (LOGD_DEVICE, "LLDP listener %p started", priv->lldp_listener);
3568                 else {
3569                         _LOGD (LOGD_DEVICE, "LLDP listener %p could not be started: %s",
3570                                priv->lldp_listener, error->message);
3571                 }
3572         }
3573
3574         nm_device_activate_schedule_stage3_ip_config_start (self);
3575 }
3576
3577
3578 /*
3579  * nm_device_activate_schedule_stage2_device_config
3580  *
3581  * Schedule setup of the hardware device
3582  *
3583  */
3584 void
3585 nm_device_activate_schedule_stage2_device_config (NMDevice *self)
3586 {
3587         NMDevicePrivate *priv;
3588
3589         g_return_if_fail (NM_IS_DEVICE (self));
3590
3591         priv = NM_DEVICE_GET_PRIVATE (self);
3592         g_return_if_fail (priv->act_request);
3593
3594         if (!priv->master_ready_handled) {
3595                 NMActiveConnection *active = NM_ACTIVE_CONNECTION (priv->act_request);
3596
3597                 if (!nm_active_connection_get_master (active)) {
3598                         g_warn_if_fail (!priv->master_ready_id);
3599                         priv->master_ready_handled = TRUE;
3600                 } else {
3601                         /* If the master connection is ready for slaves, attach ourselves */
3602                         if (nm_active_connection_get_master_ready (active))
3603                                 master_ready (self, active);
3604                         else {
3605                                 _LOGD (LOGD_DEVICE, "waiting for master connection to become ready");
3606
3607                                 if (priv->master_ready_id == 0) {
3608                                         priv->master_ready_id = g_signal_connect (active,
3609                                                                                   "notify::" NM_ACTIVE_CONNECTION_INT_MASTER_READY,
3610                                                                                   (GCallback) master_ready_cb,
3611                                                                                   self);
3612                                 }
3613                                 /* Postpone */
3614                                 return;
3615                         }
3616                 }
3617         }
3618
3619         activation_source_schedule (self, activate_stage2_device_config, AF_INET);
3620 }
3621
3622 /*
3623  * check_ip_failed
3624  *
3625  * Progress the device to appropriate state if both IPv4 and IPv6 failed
3626  */
3627 static void
3628 check_ip_failed (NMDevice *self, gboolean may_fail)
3629 {
3630         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
3631         NMDeviceState state;
3632
3633         if (   priv->ip4_state != IP_FAIL
3634             || priv->ip6_state != IP_FAIL)
3635                 return;
3636
3637         if (nm_device_uses_assumed_connection (self)) {
3638                 /* We have assumed configuration, but couldn't
3639                  * redo it. No problem, move to check state. */
3640                 priv->ip4_state = priv->ip6_state = IP_DONE;
3641                 state = NM_DEVICE_STATE_IP_CHECK;
3642         } else if (   may_fail
3643                    && get_ip_config_may_fail (self, AF_INET)
3644                    && get_ip_config_may_fail (self, AF_INET6)) {
3645                 /* Couldn't start either IPv6 and IPv4 autoconfiguration,
3646                  * but both are allowed to fail. */
3647                 state = NM_DEVICE_STATE_SECONDARIES;
3648         } else {
3649                 /* Autoconfiguration attempted without success. */
3650                 state = NM_DEVICE_STATE_FAILED;
3651         }
3652
3653         nm_device_state_changed (self,
3654                                  state,
3655                                  NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE);
3656 }
3657
3658 /*
3659  * check_ip_done
3660  *
3661  * Progress the device to ip connectivity check state if IPv4 or IPv6 succeeded
3662  */
3663 static void
3664 check_ip_done (NMDevice *self)
3665 {
3666         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
3667
3668         if (nm_device_get_state (self) != NM_DEVICE_STATE_IP_CONFIG)
3669                 return;
3670
3671         if (priv->ip4_state != IP_DONE && !get_ip_config_may_fail (self, AF_INET))
3672                 return;
3673
3674         if (priv->ip6_state != IP_DONE && !get_ip_config_may_fail (self, AF_INET6))
3675                 return;
3676
3677         nm_device_state_changed (self, NM_DEVICE_STATE_IP_CHECK, NM_DEVICE_STATE_REASON_NONE);
3678 }
3679
3680 /*********************************************/
3681 /* IPv4 DAD stuff */
3682
3683 static guint
3684 get_ipv4_dad_timeout (NMDevice *self)
3685 {
3686         NMConnection *connection;
3687         NMSettingIPConfig *s_ip4 = NULL;
3688         gs_free char *value = NULL;
3689         gint ret = 0;
3690
3691         connection = nm_device_get_applied_connection (self);
3692         if (connection)
3693                 s_ip4 = nm_connection_get_setting_ip4_config (connection);
3694
3695         if (s_ip4) {
3696                 ret = nm_setting_ip_config_get_dad_timeout (s_ip4);
3697
3698                 if (ret < 0) {
3699                         value = nm_config_data_get_connection_default (NM_CONFIG_GET_DATA,
3700                                                                        "ipv4.dad-timeout", self);
3701                         ret = _nm_utils_ascii_str_to_int64 (value, 10, -1,
3702                                                             NM_SETTING_IP_CONFIG_DAD_TIMEOUT_MAX,
3703                                                             -1);
3704                         ret = ret < 0 ? 0 : ret;
3705                 }
3706         }
3707
3708         return ret;
3709 }
3710
3711 static void
3712 arping_data_destroy (gpointer ptr, GClosure *closure)
3713 {
3714         ArpingData *data = ptr;
3715         int i;
3716
3717         if (data) {
3718                 for (i = 0; data->configs && data->configs[i]; i++)
3719                         g_object_unref (data->configs[i]);
3720                 g_free (data->configs);
3721                 g_slice_free (ArpingData, data);
3722         }
3723 }
3724
3725 static void
3726 ipv4_manual_method_apply (NMDevice *self, NMIP4Config **configs, gboolean success)
3727 {
3728         NMIP4Config *empty;
3729
3730         if (success) {
3731                 empty = nm_ip4_config_new (nm_device_get_ip_ifindex (self));
3732                 nm_device_activate_schedule_ip4_config_result (self, empty);
3733                 g_object_unref (empty);
3734         } else {
3735                 nm_device_queue_state (self, NM_DEVICE_STATE_FAILED,
3736                                        NM_DEVICE_STATE_REASON_CONFIG_FAILED);
3737         }
3738 }
3739
3740 static void
3741 arping_manager_probe_terminated (NMArpingManager *arping_manager, ArpingData *data)
3742 {
3743         NMDevice *self;
3744         NMDevicePrivate *priv;
3745         const NMPlatformIP4Address *address;
3746         gboolean result, success = TRUE;
3747         int i, j;
3748
3749         g_assert (data);
3750         self = data->device;
3751         priv = NM_DEVICE_GET_PRIVATE (self);
3752
3753         for (i = 0; data->configs && data->configs[i]; i++) {
3754                 for (j = 0; j < nm_ip4_config_get_num_addresses (data->configs[i]); j++) {
3755                         address = nm_ip4_config_get_address (data->configs[i], j);
3756                         result = nm_arping_manager_check_address (arping_manager, address->address);
3757                         success &= result;
3758
3759                         _NMLOG (result ? LOGL_DEBUG : LOGL_WARN,
3760                                 LOGD_DEVICE,
3761                                 "IPv4 DAD result: address %s is %s",
3762                                 nm_utils_inet4_ntop (address->address, NULL),
3763                                 result ? "unique" : "duplicate");
3764                 }
3765         }
3766
3767         data->callback (self, data->configs, success);
3768
3769         priv->arping.dad_list = g_slist_remove (priv->arping.dad_list, arping_manager);
3770         nm_arping_manager_destroy (arping_manager);
3771 }
3772
3773 /**
3774  * ipv4_dad_start:
3775  * @self: device instance
3776  * @configs: NULL-terminated array of IPv4 configurations
3777  * @cb: callback function
3778  *
3779  * Start IPv4 DAD on device @self, check addresses in @configs and call @cb
3780  * when the procedure ends. @cb will be called in any case, even if DAD can't
3781  * be started. @configs will be unreferenced after @cb has been called.
3782  */
3783 static void
3784 ipv4_dad_start (NMDevice *self, NMIP4Config **configs, ArpingCallback cb)
3785 {
3786         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
3787         NMArpingManager *arping_manager;
3788         const NMPlatformIP4Address *address;
3789         ArpingData *data;
3790         guint timeout;
3791         gboolean ret, addr_found;
3792         const guint8 *hw_addr;
3793         size_t hw_addr_len = 0;
3794         GError *error = NULL;
3795         guint i, j;
3796
3797         g_return_if_fail (NM_IS_DEVICE (self));
3798         g_return_if_fail (configs);
3799         g_return_if_fail (cb);
3800
3801         for (i = 0, addr_found = FALSE; configs[i]; i++) {
3802                 if (nm_ip4_config_get_num_addresses (configs[i]) > 0) {
3803                         addr_found = TRUE;
3804                         break;
3805                 }
3806         }
3807
3808         timeout = get_ipv4_dad_timeout (self);
3809         hw_addr = nm_platform_link_get_address (NM_PLATFORM_GET,
3810                                                 nm_device_get_ip_ifindex (self),
3811                                                 &hw_addr_len);
3812
3813         if (   !timeout
3814             || !hw_addr
3815             || !hw_addr_len
3816             || !addr_found
3817             || nm_device_uses_assumed_connection (self)) {
3818
3819                 /* DAD not needed, signal success */
3820                 cb (self, configs, TRUE);
3821
3822                 for (i = 0; configs[i]; i++)
3823                         g_object_unref (configs[i]);
3824                 g_free (configs);
3825
3826                 return;
3827         }
3828
3829         /* don't take additional references of @arping_manager that outlive @self.
3830          * Otherwise, the callback can be invoked on a dangling pointer as we don't
3831          * disconnect the handler. */
3832         arping_manager = nm_arping_manager_new (nm_device_get_ip_ifindex (self));
3833         priv->arping.dad_list = g_slist_append (priv->arping.dad_list, arping_manager);
3834
3835         data = g_slice_new0 (ArpingData);
3836         data->configs = configs;
3837         data->callback = cb;
3838         data->device = self;
3839
3840         for (i = 0; configs[i]; i++) {
3841                 for (j = 0; j < nm_ip4_config_get_num_addresses (configs[i]); j++) {
3842                         address = nm_ip4_config_get_address (configs[i], j);
3843                         nm_arping_manager_add_address (arping_manager, address->address);
3844                 }
3845         }
3846
3847         g_signal_connect_data (arping_manager, NM_ARPING_MANAGER_PROBE_TERMINATED,
3848                                G_CALLBACK (arping_manager_probe_terminated), data,
3849                                arping_data_destroy, 0);
3850
3851         ret = nm_arping_manager_start_probe (arping_manager, timeout, &error);
3852
3853         if (!ret) {
3854                 _LOGW (LOGD_DEVICE, "arping probe failed: %s", error->message);
3855
3856                 /* DAD could not be started, signal success */
3857                 cb (self, configs, TRUE);
3858
3859                 priv->arping.dad_list = g_slist_remove (priv->arping.dad_list, arping_manager);
3860                 nm_arping_manager_destroy (arping_manager);
3861         }
3862 }
3863
3864 /*********************************************/
3865 /* IPv4LL stuff */
3866
3867 static void
3868 ipv4ll_cleanup (NMDevice *self)
3869 {
3870         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
3871
3872         if (priv->ipv4ll) {
3873                 sd_ipv4ll_set_callback (priv->ipv4ll, NULL, NULL);
3874                 sd_ipv4ll_stop (priv->ipv4ll);
3875                 priv->ipv4ll = sd_ipv4ll_unref (priv->ipv4ll);
3876         }
3877
3878         nm_clear_g_source (&priv->ipv4ll_timeout);
3879 }
3880
3881 static NMIP4Config *
3882 ipv4ll_get_ip4_config (NMDevice *self, guint32 lla)
3883 {
3884         NMIP4Config *config = NULL;
3885         NMPlatformIP4Address address;
3886         NMPlatformIP4Route route;
3887
3888         config = nm_ip4_config_new (nm_device_get_ip_ifindex (self));
3889         g_assert (config);
3890
3891         memset (&address, 0, sizeof (address));
3892         nm_platform_ip4_address_set_addr (&address, lla, 16);
3893         address.source = NM_IP_CONFIG_SOURCE_IP4LL;
3894         nm_ip4_config_add_address (config, &address);
3895
3896         /* Add a multicast route for link-local connections: destination= 224.0.0.0, netmask=240.0.0.0 */
3897         memset (&route, 0, sizeof (route));
3898         route.network = htonl (0xE0000000L);
3899         route.plen = 4;
3900         route.source = NM_IP_CONFIG_SOURCE_IP4LL;
3901         route.metric = nm_device_get_ip4_route_metric (self);
3902         nm_ip4_config_add_route (config, &route);
3903
3904         return config;
3905 }
3906
3907 #define IPV4LL_NETWORK (htonl (0xA9FE0000L))
3908 #define IPV4LL_NETMASK (htonl (0xFFFF0000L))
3909
3910 static void
3911 nm_device_handle_ipv4ll_event (sd_ipv4ll *ll, int event, void *data)
3912 {
3913         NMDevice *self = data;
3914         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
3915         NMConnection *connection = NULL;
3916         const char *method;
3917         struct in_addr address;
3918         NMIP4Config *config;
3919         int r;
3920
3921         if (priv->act_request == NULL)
3922                 return;
3923
3924         connection = nm_act_request_get_applied_connection (priv->act_request);
3925         g_assert (connection);
3926
3927         /* Ignore if the connection isn't an AutoIP connection */
3928         method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG);
3929         if (g_strcmp0 (method, NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL) != 0)
3930                 return;
3931
3932         switch (event) {
3933         case SD_IPV4LL_EVENT_BIND:
3934                 r = sd_ipv4ll_get_address (ll, &address);
3935                 if (r < 0) {
3936                         _LOGE (LOGD_AUTOIP4, "invalid IPv4 link-local address received, error %d.", r);
3937                         priv->ip4_state = IP_FAIL;
3938                         check_ip_failed (self, FALSE);
3939                         return;
3940                 }
3941
3942                 if ((address.s_addr & IPV4LL_NETMASK) != IPV4LL_NETWORK) {
3943                         _LOGE (LOGD_AUTOIP4, "invalid address %08x received (not link-local).", address.s_addr);
3944                         priv->ip4_state = IP_FAIL;
3945                         check_ip_failed (self, FALSE);
3946                         return;
3947                 }
3948
3949                 config = ipv4ll_get_ip4_config (self, address.s_addr);
3950                 if (config == NULL) {
3951                         _LOGE (LOGD_AUTOIP4, "failed to get IPv4LL config");
3952                         priv->ip4_state = IP_FAIL;
3953                         check_ip_failed (self, FALSE);
3954                         return;
3955                 }
3956
3957                 if (priv->ip4_state == IP_CONF) {
3958                         nm_clear_g_source (&priv->ipv4ll_timeout);
3959                         nm_device_activate_schedule_ip4_config_result (self, config);
3960                 } else if (priv->ip4_state == IP_DONE) {
3961                         if (!ip4_config_merge_and_apply (self, config, TRUE, NULL)) {
3962                                 _LOGE (LOGD_AUTOIP4, "failed to update IP4 config for autoip change.");
3963                                 priv->ip4_state = IP_FAIL;
3964                                 check_ip_failed (self, FALSE);
3965                         }
3966                 } else
3967                         g_assert_not_reached ();
3968
3969                 g_object_unref (config);
3970                 break;
3971         default:
3972                 _LOGW (LOGD_AUTOIP4, "IPv4LL address no longer valid after event %d.", event);
3973                 priv->ip4_state = IP_FAIL;
3974                 check_ip_failed (self, FALSE);
3975         }
3976 }
3977
3978 static gboolean
3979 ipv4ll_timeout_cb (gpointer user_data)
3980 {
3981         NMDevice *self = NM_DEVICE (user_data);
3982         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
3983
3984         if (priv->ipv4ll_timeout) {
3985                 _LOGI (LOGD_AUTOIP4, "IPv4LL configuration timed out.");
3986                 priv->ipv4ll_timeout = 0;
3987                 ipv4ll_cleanup (self);
3988
3989                 if (priv->ip4_state == IP_CONF)
3990                         nm_device_activate_schedule_ip4_config_timeout (self);
3991         }
3992
3993         return FALSE;
3994 }
3995
3996 static NMActStageReturn
3997 ipv4ll_start (NMDevice *self, NMDeviceStateReason *reason)
3998 {
3999         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
4000         const struct ether_addr *addr;
4001         int ifindex, r;
4002         size_t addr_len;
4003
4004         ipv4ll_cleanup (self);
4005
4006         r = sd_ipv4ll_new (&priv->ipv4ll);
4007         if (r < 0) {
4008                 _LOGE (LOGD_AUTOIP4, "IPv4LL: new() failed with error %d", r);
4009                 goto fail;
4010         }
4011
4012         r = sd_ipv4ll_attach_event (priv->ipv4ll, NULL, 0);
4013         if (r < 0) {
4014                 _LOGE (LOGD_AUTOIP4, "IPv4LL: attach_event() failed with error %d", r);
4015                 goto fail;
4016         }
4017
4018         ifindex = nm_device_get_ip_ifindex (self);
4019         addr = nm_platform_link_get_address (NM_PLATFORM_GET, ifindex, &addr_len);
4020         if (!addr || addr_len != ETH_ALEN) {
4021                 _LOGE (LOGD_AUTOIP4, "IPv4LL: can't retrieve hardware address");
4022                 goto fail;
4023         }
4024
4025         r = sd_ipv4ll_set_mac (priv->ipv4ll, addr);
4026         if (r < 0) {
4027                 _LOGE (LOGD_AUTOIP4, "IPv4LL: set_mac() failed with error %d", r);
4028                 goto fail;
4029         }
4030
4031         r = sd_ipv4ll_set_index (priv->ipv4ll, ifindex);
4032         if (r < 0) {
4033                 _LOGE (LOGD_AUTOIP4, "IPv4LL: set_index() failed with error %d", r);
4034                 goto fail;
4035         }
4036
4037         r = sd_ipv4ll_set_callback (priv->ipv4ll, nm_device_handle_ipv4ll_event, self);
4038         if (r < 0) {
4039                 _LOGE (LOGD_AUTOIP4, "IPv4LL: set_callback() failed with error %d", r);
4040                 goto fail;
4041         }
4042
4043         r = sd_ipv4ll_start (priv->ipv4ll);
4044         if (r < 0) {
4045                 _LOGE (LOGD_AUTOIP4, "IPv4LL: start() failed with error %d", r);
4046                 goto fail;
4047         }
4048
4049         _LOGI (LOGD_DEVICE | LOGD_AUTOIP4, "IPv4LL: started");
4050
4051         /* Start a timeout to bound the address attempt */
4052         priv->ipv4ll_timeout = g_timeout_add_seconds (20, ipv4ll_timeout_cb, self);
4053
4054         return NM_ACT_STAGE_RETURN_POSTPONE;
4055 fail:
4056         *reason = NM_DEVICE_STATE_REASON_AUTOIP_START_FAILED;
4057         return NM_ACT_STAGE_RETURN_FAILURE;
4058 }
4059
4060 /*********************************************/
4061
4062 static gboolean
4063 _device_get_default_route_from_platform (NMDevice *self, int addr_family, NMPlatformIPRoute *out_route)
4064 {
4065         gboolean success = FALSE;
4066         int ifindex = nm_device_get_ip_ifindex (self);
4067         GArray *routes;
4068
4069         if (addr_family == AF_INET)
4070                 routes = nm_platform_ip4_route_get_all (NM_PLATFORM_GET, ifindex, NM_PLATFORM_GET_ROUTE_FLAGS_WITH_DEFAULT);
4071         else
4072                 routes = nm_platform_ip6_route_get_all (NM_PLATFORM_GET, ifindex, NM_PLATFORM_GET_ROUTE_FLAGS_WITH_DEFAULT);
4073
4074         if (routes) {
4075                 guint route_metric = G_MAXUINT32, m;
4076                 const NMPlatformIPRoute *route = NULL, *r;
4077                 guint i;
4078
4079                 /* if there are several default routes, find the one with the best metric */
4080                 for (i = 0; i < routes->len; i++) {
4081                         if (addr_family == AF_INET) {
4082                                 r = (const NMPlatformIPRoute *) &g_array_index (routes, NMPlatformIP4Route, i);
4083                                 m = r->metric;
4084                         } else {
4085                                 r = (const NMPlatformIPRoute *) &g_array_index (routes, NMPlatformIP6Route, i);
4086                                 m = nm_utils_ip6_route_metric_normalize (r->metric);
4087                         }
4088                         if (!route || m < route_metric) {
4089                                 route = r;
4090                                 route_metric = m;
4091                         }
4092                 }
4093
4094                 if (route) {
4095                         if (addr_family == AF_INET)
4096                                 *((NMPlatformIP4Route *) out_route) = *((NMPlatformIP4Route *) route);
4097                         else
4098                                 *((NMPlatformIP6Route *) out_route) = *((NMPlatformIP6Route *) route);
4099                         success = TRUE;
4100                 }
4101                 g_array_free (routes, TRUE);
4102         }
4103         return success;
4104 }
4105
4106 /*********************************************/
4107
4108 static void
4109 ensure_con_ip4_config (NMDevice *self)
4110 {
4111         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
4112         int ip_ifindex = nm_device_get_ip_ifindex (self);
4113         NMConnection *connection;
4114
4115         if (priv->con_ip4_config)
4116                 return;
4117
4118         connection = nm_device_get_applied_connection (self);
4119         if (!connection)
4120                 return;
4121
4122         priv->con_ip4_config = nm_ip4_config_new (ip_ifindex);
4123         nm_ip4_config_merge_setting (priv->con_ip4_config,
4124                                      nm_connection_get_setting_ip4_config (connection),
4125                                      nm_device_get_ip4_route_metric (self));
4126
4127         if (nm_device_uses_assumed_connection (self)) {
4128                 /* For assumed connections ignore all addresses and routes. */
4129                 nm_ip4_config_reset_addresses (priv->con_ip4_config);
4130                 nm_ip4_config_reset_routes (priv->con_ip4_config);
4131         }
4132 }
4133
4134 static void
4135 ensure_con_ip6_config (NMDevice *self)
4136 {
4137         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
4138         int ip_ifindex = nm_device_get_ip_ifindex (self);
4139         NMConnection *connection;
4140
4141         if (priv->con_ip6_config)
4142                 return;
4143
4144         connection = nm_device_get_applied_connection (self);
4145         if (!connection)
4146                 return;
4147
4148         priv->con_ip6_config = nm_ip6_config_new (ip_ifindex);
4149         nm_ip6_config_merge_setting (priv->con_ip6_config,
4150                                      nm_connection_get_setting_ip6_config (connection),
4151                                      nm_device_get_ip6_route_metric (self));
4152
4153         if (nm_device_uses_assumed_connection (self)) {
4154                 /* For assumed connections ignore all addresses and routes. */
4155                 nm_ip6_config_reset_addresses (priv->con_ip6_config);
4156                 nm_ip6_config_reset_routes (priv->con_ip6_config);
4157         }
4158 }
4159
4160 /*********************************************/
4161 /* DHCPv4 stuff */
4162
4163 static void
4164 dhcp4_cleanup (NMDevice *self, CleanupType cleanup_type, gboolean release)
4165 {
4166         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
4167
4168         nm_clear_g_source (&priv->dhcp4_restart_id);
4169
4170         if (priv->dhcp4_client) {
4171                 /* Stop any ongoing DHCP transaction on this device */
4172                 nm_clear_g_signal_handler (priv->dhcp4_client, &priv->dhcp4_state_sigid);
4173
4174                 nm_device_remove_pending_action (self, PENDING_ACTION_DHCP4, FALSE);
4175
4176                 if (   cleanup_type == CLEANUP_TYPE_DECONFIGURE
4177                     || cleanup_type == CLEANUP_TYPE_REMOVED)
4178                         nm_dhcp_client_stop (priv->dhcp4_client, release);
4179
4180                 g_clear_object (&priv->dhcp4_client);
4181         }
4182
4183         if (priv->dhcp4_config) {
4184                 nm_exported_object_clear_and_unexport (&priv->dhcp4_config);
4185                 _notify (self, PROP_DHCP4_CONFIG);
4186         }
4187 }
4188
4189 static void
4190 _ip4_config_merge_default (gpointer value, gpointer user_data)
4191 {
4192         NMIP4Config *src = (NMIP4Config *) value;
4193         NMIP4Config *dst = (NMIP4Config *) user_data;
4194
4195         nm_ip4_config_merge (dst, src, NM_IP_CONFIG_MERGE_DEFAULT);
4196 }
4197
4198 static gboolean
4199 ip4_config_merge_and_apply (NMDevice *self,
4200                             NMIP4Config *config,
4201                             gboolean commit,
4202                             NMDeviceStateReason *out_reason)
4203 {
4204         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
4205         NMConnection *connection;
4206         gboolean success;
4207         NMIP4Config *composite;
4208         gboolean has_direct_route;
4209         const guint32 default_route_metric = nm_device_get_ip4_route_metric (self);
4210         guint32 gateway;
4211         gboolean connection_has_default_route, connection_is_never_default;
4212         gboolean routes_full_sync;
4213         gboolean ignore_auto_routes = FALSE;
4214         gboolean ignore_auto_dns = FALSE;
4215
4216         /* Merge all the configs into the composite config */
4217         if (config) {
4218                 g_clear_object (&priv->dev_ip4_config);
4219                 priv->dev_ip4_config = g_object_ref (config);
4220         }
4221
4222         /* Apply ignore-auto-routes and ignore-auto-dns settings */
4223         connection = nm_device_get_applied_connection (self);
4224         if (connection) {
4225                 NMSettingIPConfig *s_ip4 = nm_connection_get_setting_ip4_config (connection);
4226
4227                 if (s_ip4) {
4228                         ignore_auto_routes = nm_setting_ip_config_get_ignore_auto_routes (s_ip4);
4229                         ignore_auto_dns = nm_setting_ip_config_get_ignore_auto_dns (s_ip4);
4230                 }
4231         }
4232
4233         composite = nm_ip4_config_new (nm_device_get_ip_ifindex (self));
4234
4235         if (commit)
4236                 ensure_con_ip4_config (self);
4237
4238         if (priv->dev_ip4_config) {
4239                 nm_ip4_config_merge (composite, priv->dev_ip4_config,
4240                                        (ignore_auto_routes ? NM_IP_CONFIG_MERGE_NO_ROUTES : 0)
4241                                      | (ignore_auto_dns ? NM_IP_CONFIG_MERGE_NO_DNS : 0));
4242         }
4243
4244         g_slist_foreach (priv->vpn4_configs, _ip4_config_merge_default, composite);
4245
4246         if (priv->ext_ip4_config)
4247                 nm_ip4_config_merge (composite, priv->ext_ip4_config, NM_IP_CONFIG_MERGE_DEFAULT);
4248
4249         /* Merge WWAN config *last* to ensure modem-given settings overwrite
4250          * any external stuff set by pppd or other scripts.
4251          */
4252         if (priv->wwan_ip4_config) {
4253                 nm_ip4_config_merge (composite, priv->wwan_ip4_config,
4254                                        (ignore_auto_routes ? NM_IP_CONFIG_MERGE_NO_ROUTES : 0)
4255                                      | (ignore_auto_dns ? NM_IP_CONFIG_MERGE_NO_DNS : 0));
4256         }
4257
4258         /* Merge user overrides into the composite config. For assumed connections,
4259          * con_ip4_config is empty. */
4260         if (priv->con_ip4_config)
4261                 nm_ip4_config_merge (composite, priv->con_ip4_config, NM_IP_CONFIG_MERGE_DEFAULT);
4262
4263         /* Add the default route.
4264          *
4265          * We keep track of the default route of a device in a private field.
4266          * NMDevice needs to know the default route at this point, because the gateway
4267          * might require a direct route (see below).
4268          *
4269          * But also, we don't want to add the default route to priv->ip4_config,
4270          * because the default route from the setting might not be the same that
4271          * NMDefaultRouteManager eventually configures (because the it might
4272          * tweak the effective metric).
4273          */
4274
4275         /* unless we come to a different conclusion below, we have no default route and
4276          * the route is assumed. */
4277         priv->default_route.v4_has = FALSE;
4278         priv->default_route.v4_is_assumed = TRUE;
4279
4280         if (!commit) {
4281                 /* during a non-commit event, we always pickup whatever is configured. */
4282                 goto END_ADD_DEFAULT_ROUTE;
4283         }
4284
4285         if (nm_device_uses_generated_assumed_connection (self)) {
4286                 /* a generate-assumed-connection always detects the default route from platform */
4287                 goto END_ADD_DEFAULT_ROUTE;
4288         }
4289
4290         /* At this point, we treat assumed and non-assumed connections alike.
4291          * For assumed connections we do that because we still manage RA and DHCP
4292          * leases for them, so we must extend/update the default route on commits.
4293          */
4294
4295         connection_has_default_route
4296             = nm_default_route_manager_ip4_connection_has_default_route (nm_default_route_manager_get (),
4297                                                                          connection, &connection_is_never_default);
4298
4299         if (   !priv->v4_commit_first_time
4300             && connection_is_never_default) {
4301                 /* If the connection is explicitly configured as never-default, we enforce the (absence of the)
4302                  * default-route only once. That allows the user to configure a connection as never-default,
4303                  * but he can add default routes externally (via a dispatcher script) and NM will not interfere. */
4304                 goto END_ADD_DEFAULT_ROUTE;
4305         }
4306
4307         /* we are about to commit (for a non-assumed connection). Enforce whatever we have
4308          * configured. */
4309         priv->default_route.v4_is_assumed = FALSE;
4310
4311         if (!connection_has_default_route)
4312                 goto END_ADD_DEFAULT_ROUTE;
4313
4314         if (!nm_ip4_config_get_num_addresses (composite)) {
4315                 /* without addresses we can have no default route. */
4316                 goto END_ADD_DEFAULT_ROUTE;
4317         }
4318
4319         gateway = nm_ip4_config_get_gateway (composite);
4320         if (   !nm_ip4_config_has_gateway (composite)
4321             && nm_device_get_device_type (self) != NM_DEVICE_TYPE_MODEM)
4322                 goto END_ADD_DEFAULT_ROUTE;
4323
4324         has_direct_route = (   gateway == 0
4325                             || nm_ip4_config_destination_is_direct (composite, gateway, 32)
4326                             || nm_ip4_config_get_direct_route_for_host (composite, gateway));
4327
4328         priv->default_route.v4_has = TRUE;
4329         memset (&priv->default_route.v4, 0, sizeof (priv->default_route.v4));
4330         priv->default_route.v4.source = NM_IP_CONFIG_SOURCE_USER;
4331         priv->default_route.v4.gateway = gateway;
4332         priv->default_route.v4.metric = default_route_metric;
4333         priv->default_route.v4.mss = nm_ip4_config_get_mss (composite);
4334
4335         if (!has_direct_route) {
4336                 NMPlatformIP4Route r = priv->default_route.v4;
4337
4338                 /* add a direct route to the gateway */
4339                 r.network = gateway;
4340                 r.plen = 32;
4341                 r.gateway = 0;
4342                 nm_ip4_config_add_route (composite, &r);
4343         }
4344
4345 END_ADD_DEFAULT_ROUTE:
4346
4347         if (priv->default_route.v4_is_assumed) {
4348                 /* If above does not explicitly assign a default route, we always pick up the
4349                  * default route based on what is currently configured.
4350                  * That means that even managed connections with never-default, can
4351                  * get a default route (if configured externally).
4352                  */
4353                 priv->default_route.v4_has = _device_get_default_route_from_platform (self, AF_INET, (NMPlatformIPRoute *) &priv->default_route.v4);
4354         }
4355
4356         nm_ip4_config_addresses_sort (composite);
4357
4358         /* Allow setting MTU etc */
4359         if (commit) {
4360                 if (NM_DEVICE_GET_CLASS (self)->ip4_config_pre_commit)
4361                         NM_DEVICE_GET_CLASS (self)->ip4_config_pre_commit (self, composite);
4362         }
4363
4364         routes_full_sync =    commit
4365                            && priv->v4_commit_first_time
4366                            && !nm_device_uses_assumed_connection (self);
4367
4368         success = nm_device_set_ip4_config (self, composite, default_route_metric, commit, routes_full_sync, out_reason);
4369         g_object_unref (composite);
4370
4371         if (commit)
4372                 priv->v4_commit_first_time = FALSE;
4373         return success;
4374 }
4375
4376 static void
4377 dhcp4_lease_change (NMDevice *self, NMIP4Config *config)
4378 {
4379         NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE;
4380
4381         g_return_if_fail (config != NULL);
4382
4383         if (!ip4_config_merge_and_apply (self, config, TRUE, &reason)) {
4384                 _LOGW (LOGD_DHCP4, "failed to update IPv4 config for DHCP change.");
4385                 nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason);
4386         } else {
4387                 /* Notify dispatcher scripts of new DHCP4 config */
4388                 nm_dispatcher_call (DISPATCHER_ACTION_DHCP4_CHANGE,
4389                                     nm_device_get_settings_connection (self),
4390                                     nm_device_get_applied_connection (self),
4391                                     self,
4392                                     NULL,
4393                                     NULL,
4394                                     NULL);
4395         }
4396 }
4397
4398 static gboolean
4399 dhcp4_restart_cb (gpointer user_data)
4400 {
4401         NMDevice *self = user_data;
4402         NMDevicePrivate *priv;
4403         NMDeviceStateReason reason;
4404         NMConnection *connection;
4405
4406         g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
4407
4408         priv = NM_DEVICE_GET_PRIVATE (self);
4409         priv->dhcp4_restart_id = 0;
4410         connection = nm_device_get_applied_connection (self);
4411
4412         if (dhcp4_start (self, connection, &reason) == NM_ACT_STAGE_RETURN_FAILURE)
4413                 priv->dhcp4_restart_id = g_timeout_add_seconds (120, dhcp4_restart_cb, self);
4414
4415         return FALSE;
4416 }
4417
4418 static void
4419 dhcp4_fail (NMDevice *self, gboolean timeout)
4420 {
4421         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
4422
4423         dhcp4_cleanup (self, CLEANUP_TYPE_DECONFIGURE, FALSE);
4424
4425         /* Don't fail if there are static addresses configured on
4426          * the device, instead retry after some time.
4427          */
4428         if (   priv->ip4_state == IP_DONE
4429             && priv->con_ip4_config
4430             && nm_ip4_config_get_num_addresses (priv->con_ip4_config) > 0) {
4431                 _LOGI (LOGD_DHCP4, "Scheduling DHCPv4 restart because device has IP addresses");
4432                 priv->dhcp4_restart_id = g_timeout_add_seconds (120, dhcp4_restart_cb, self);
4433                 return;
4434         }
4435
4436         /* Instead of letting an assumed connection fail (which means that the
4437          * device will transition to the ACTIVATED state without IP configuration),
4438          * retry DHCP again.
4439          */
4440         if (nm_device_uses_assumed_connection (self)) {
4441                 _LOGI (LOGD_DHCP4, "Scheduling DHCPv4 restart because the connection is assumed");
4442                 priv->dhcp4_restart_id = g_timeout_add_seconds (120, dhcp4_restart_cb, self);
4443                 return;
4444         }
4445
4446         if (timeout || (priv->ip4_state == IP_CONF))
4447                 nm_device_activate_schedule_ip4_config_timeout (self);
4448         else if (priv->ip4_state == IP_DONE)
4449                 nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED);
4450         else
4451                 g_warn_if_reached ();
4452 }
4453
4454 static void
4455 dhcp4_dad_cb (NMDevice *self, NMIP4Config **configs, gboolean success)
4456 {
4457         if (success)
4458                 nm_device_activate_schedule_ip4_config_result (self, configs[1]);
4459         else {
4460                 nm_device_state_changed (self, NM_DEVICE_STATE_FAILED,
4461                                          NM_DEVICE_STATE_REASON_CONFIG_FAILED);
4462         }
4463 }
4464
4465 static void
4466 dhcp4_state_changed (NMDhcpClient *client,
4467                      NMDhcpState state,
4468                      NMIP4Config *ip4_config,
4469                      GHashTable *options,
4470                      const char *event_id,
4471                      gpointer user_data)
4472 {
4473         NMDevice *self = NM_DEVICE (user_data);
4474         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
4475         NMIP4Config *manual, **configs;
4476         NMConnection *connection;
4477
4478         g_return_if_fail (nm_dhcp_client_get_ipv6 (client) == FALSE);
4479         g_return_if_fail (!ip4_config || NM_IS_IP4_CONFIG (ip4_config));
4480
4481         _LOGD (LOGD_DHCP4, "new DHCPv4 client state %d", state);
4482
4483         switch (state) {
4484         case NM_DHCP_STATE_BOUND:
4485                 if (!ip4_config) {
4486                         _LOGW (LOGD_DHCP4, "failed to get IPv4 config in response to DHCP event.");
4487                         nm_device_state_changed (self,
4488                                                  NM_DEVICE_STATE_FAILED,
4489                                                  NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE);
4490                         break;
4491                 }
4492
4493                 nm_dhcp4_config_set_options (priv->dhcp4_config, options);
4494                 _notify (self, PROP_DHCP4_CONFIG);
4495
4496                 if (priv->ip4_state == IP_CONF) {
4497                         connection = nm_device_get_applied_connection (self);
4498                         g_assert (connection);
4499
4500                         manual = nm_ip4_config_new (nm_device_get_ip_ifindex (self));
4501                         nm_ip4_config_merge_setting (manual,
4502                                                      nm_connection_get_setting_ip4_config (connection),
4503                                                      nm_device_get_ip4_route_metric (self));
4504
4505                         configs = g_new0 (NMIP4Config *, 3);
4506                         configs[0] = manual;
4507                         configs[1] = g_object_ref (ip4_config);
4508
4509                         ipv4_dad_start (self, configs, dhcp4_dad_cb);
4510                 } else if (priv->ip4_state == IP_DONE) {
4511                         dhcp4_lease_change (self, ip4_config);
4512                         nm_device_update_metered (self);
4513                 }
4514                 break;
4515         case NM_DHCP_STATE_TIMEOUT:
4516                 dhcp4_fail (self, TRUE);
4517                 break;
4518         case NM_DHCP_STATE_EXPIRE:
4519                 /* Ignore expiry before we even have a lease (NAK, old lease, etc) */
4520                 if (priv->ip4_state == IP_CONF)
4521                         break;
4522                 /* Fall through */
4523         case NM_DHCP_STATE_DONE:
4524         case NM_DHCP_STATE_FAIL:
4525                 dhcp4_fail (self, FALSE);
4526                 break;
4527         default:
4528                 break;
4529         }
4530 }
4531
4532 static int
4533 dhcp4_get_timeout (NMDevice *self, NMSettingIP4Config *s_ip4)
4534 {
4535         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
4536         gs_free char *value = NULL;
4537         int timeout;
4538
4539         timeout = nm_setting_ip_config_get_dhcp_timeout (NM_SETTING_IP_CONFIG (s_ip4));
4540         if (timeout)
4541                 return timeout;
4542
4543         value = nm_config_data_get_connection_default (NM_CONFIG_GET_DATA,
4544                                                        "ipv4.dhcp-timeout",
4545                                                        self);
4546         timeout = _nm_utils_ascii_str_to_int64 (value, 10,
4547                                                 0, G_MAXINT32, 0);
4548         if (timeout)
4549                 return timeout;
4550
4551         return priv->dhcp_timeout;
4552 }
4553
4554 static NMActStageReturn
4555 dhcp4_start (NMDevice *self,
4556              NMConnection *connection,
4557              NMDeviceStateReason *reason)
4558 {
4559         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
4560         NMSettingIPConfig *s_ip4;
4561         const guint8 *hw_addr;
4562         size_t hw_addr_len = 0;
4563         GByteArray *tmp = NULL;
4564
4565         s_ip4 = nm_connection_get_setting_ip4_config (connection);
4566
4567         /* Clear old exported DHCP options */
4568         nm_exported_object_clear_and_unexport (&priv->dhcp4_config);
4569         priv->dhcp4_config = nm_dhcp4_config_new ();
4570
4571         hw_addr = nm_platform_link_get_address (NM_PLATFORM_GET, nm_device_get_ip_ifindex (self), &hw_addr_len);
4572         if (hw_addr_len) {
4573                 tmp = g_byte_array_sized_new (hw_addr_len);
4574                 g_byte_array_append (tmp, hw_addr, hw_addr_len);
4575         }
4576
4577         /* Begin DHCP on the interface */
4578         g_warn_if_fail (priv->dhcp4_client == NULL);
4579         priv->dhcp4_client = nm_dhcp_manager_start_ip4 (nm_dhcp_manager_get (),
4580                                                         nm_device_get_ip_iface (self),
4581                                                         nm_device_get_ip_ifindex (self),
4582                                                         tmp,
4583                                                         nm_connection_get_uuid (connection),
4584                                                         nm_device_get_ip4_route_metric (self),
4585                                                         nm_setting_ip_config_get_dhcp_send_hostname (s_ip4),
4586                                                         nm_setting_ip_config_get_dhcp_hostname (s_ip4),
4587                                                         nm_setting_ip4_config_get_dhcp_fqdn (NM_SETTING_IP4_CONFIG (s_ip4)),
4588                                                         nm_setting_ip4_config_get_dhcp_client_id (NM_SETTING_IP4_CONFIG (s_ip4)),
4589                                                         dhcp4_get_timeout (self, NM_SETTING_IP4_CONFIG (s_ip4)),
4590                                                         priv->dhcp_anycast_address,
4591                                                         NULL);
4592
4593         if (tmp)
4594                 g_byte_array_free (tmp, TRUE);
4595
4596         if (!priv->dhcp4_client) {
4597                 *reason = NM_DEVICE_STATE_REASON_DHCP_START_FAILED;
4598                 return NM_ACT_STAGE_RETURN_FAILURE;
4599         }
4600
4601         priv->dhcp4_state_sigid = g_signal_connect (priv->dhcp4_client,
4602                                                     NM_DHCP_CLIENT_SIGNAL_STATE_CHANGED,
4603                                                     G_CALLBACK (dhcp4_state_changed),
4604                                                     self);
4605
4606         nm_device_add_pending_action (self, PENDING_ACTION_DHCP4, TRUE);
4607
4608         /* DHCP devices will be notified by the DHCP manager when stuff happens */
4609         return NM_ACT_STAGE_RETURN_POSTPONE;
4610 }
4611
4612 gboolean
4613 nm_device_dhcp4_renew (NMDevice *self, gboolean release)
4614 {
4615         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
4616         NMActStageReturn ret;
4617         NMDeviceStateReason reason;
4618         NMConnection *connection;
4619
4620         g_return_val_if_fail (priv->dhcp4_client != NULL, FALSE);
4621
4622         _LOGI (LOGD_DHCP4, "DHCPv4 lease renewal requested");
4623
4624         /* Terminate old DHCP instance and release the old lease */
4625         dhcp4_cleanup (self, CLEANUP_TYPE_DECONFIGURE, release);
4626
4627         connection = nm_device_get_applied_connection (self);
4628         g_assert (connection);
4629
4630         /* Start DHCP again on the interface */
4631         ret = dhcp4_start (self, connection, &reason);
4632
4633         return (ret != NM_ACT_STAGE_RETURN_FAILURE);
4634 }
4635
4636 /*********************************************/
4637
4638 static GHashTable *shared_ips = NULL;
4639
4640 static void
4641 release_shared_ip (gpointer data)
4642 {
4643         g_hash_table_remove (shared_ips, data);
4644 }
4645
4646 static gboolean
4647 reserve_shared_ip (NMDevice *self, NMSettingIPConfig *s_ip4, NMPlatformIP4Address *address)
4648 {
4649         if (G_UNLIKELY (shared_ips == NULL))
4650                 shared_ips = g_hash_table_new (g_direct_hash, g_direct_equal);
4651
4652         memset (address, 0, sizeof (*address));
4653
4654         if (s_ip4 && nm_setting_ip_config_get_num_addresses (s_ip4)) {
4655                 /* Use the first user-supplied address */
4656                 NMIPAddress *user = nm_setting_ip_config_get_address (s_ip4, 0);
4657                 in_addr_t a;
4658
4659                 g_assert (user);
4660                 nm_ip_address_get_address_binary (user, &a);
4661                 nm_platform_ip4_address_set_addr (address, a, nm_ip_address_get_prefix (user));
4662         } else {
4663                 /* Find an unused address in the 10.42.x.x range */
4664                 guint32 start = (guint32) ntohl (0x0a2a0001); /* 10.42.0.1 */
4665                 guint32 count = 0;
4666
4667                 while (g_hash_table_lookup (shared_ips, GUINT_TO_POINTER (start + count))) {
4668                         count += ntohl (0x100);
4669                         if (count > ntohl (0xFE00)) {
4670                                 _LOGE (LOGD_SHARING, "ran out of shared IP addresses!");
4671                                 return FALSE;
4672                         }
4673                 }
4674                 nm_platform_ip4_address_set_addr (address, start + count, 24);
4675                 g_hash_table_add (shared_ips, GUINT_TO_POINTER (address->address));
4676         }
4677
4678         return TRUE;
4679 }
4680
4681 static NMIP4Config *
4682 shared4_new_config (NMDevice *self, NMConnection *connection, NMDeviceStateReason *reason)
4683 {
4684         NMIP4Config *config = NULL;
4685         NMPlatformIP4Address address;
4686
4687         g_return_val_if_fail (self != NULL, NULL);
4688
4689         if (!reserve_shared_ip (self, nm_connection_get_setting_ip4_config (connection), &address)) {
4690                 *reason = NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE;
4691                 return NULL;
4692         }
4693
4694         config = nm_ip4_config_new (nm_device_get_ip_ifindex (self));
4695         address.source = NM_IP_CONFIG_SOURCE_SHARED;
4696         nm_ip4_config_add_address (config, &address);
4697
4698         /* Remove the address lock when the object gets disposed */
4699         g_object_set_data_full (G_OBJECT (config), "shared-ip",
4700                                 GUINT_TO_POINTER (address.address),
4701                                 release_shared_ip);
4702
4703         return config;
4704 }
4705
4706 /*********************************************/
4707
4708 static gboolean
4709 connection_ip4_method_requires_carrier (NMConnection *connection,
4710                                         gboolean *out_ip4_enabled)
4711 {
4712         const char *method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG);
4713         static const char *ip4_carrier_methods[] = {
4714                 NM_SETTING_IP4_CONFIG_METHOD_AUTO,
4715                 NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL,
4716                 NULL
4717         };
4718
4719         if (out_ip4_enabled)
4720                 *out_ip4_enabled = !!strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED);
4721         return _nm_utils_string_in_list (method, ip4_carrier_methods);
4722 }
4723
4724 static gboolean
4725 connection_ip6_method_requires_carrier (NMConnection *connection,
4726                                         gboolean *out_ip6_enabled)
4727 {
4728         const char *method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG);
4729         static const char *ip6_carrier_methods[] = {
4730                 NM_SETTING_IP6_CONFIG_METHOD_AUTO,
4731                 NM_SETTING_IP6_CONFIG_METHOD_DHCP,
4732                 NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL,
4733                 NULL
4734         };
4735
4736         if (out_ip6_enabled)
4737                 *out_ip6_enabled = !!strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_IGNORE);
4738         return _nm_utils_string_in_list (method, ip6_carrier_methods);
4739 }
4740
4741 static gboolean
4742 connection_requires_carrier (NMConnection *connection)
4743 {
4744         NMSettingIPConfig *s_ip4, *s_ip6;
4745         gboolean ip4_carrier_wanted, ip6_carrier_wanted;
4746         gboolean ip4_used = FALSE, ip6_used = FALSE;
4747
4748         ip4_carrier_wanted = connection_ip4_method_requires_carrier (connection, &ip4_used);
4749         if (ip4_carrier_wanted) {
4750                 /* If IPv4 wants a carrier and cannot fail, the whole connection
4751                  * requires a carrier regardless of the IPv6 method.
4752                  */
4753                 s_ip4 = nm_connection_get_setting_ip4_config (connection);
4754                 if (s_ip4 && !nm_setting_ip_config_get_may_fail (s_ip4))
4755                         return TRUE;
4756         }
4757
4758         ip6_carrier_wanted = connection_ip6_method_requires_carrier (connection, &ip6_used);
4759         if (ip6_carrier_wanted) {
4760                 /* If IPv6 wants a carrier and cannot fail, the whole connection
4761                  * requires a carrier regardless of the IPv4 method.
4762                  */
4763                 s_ip6 = nm_connection_get_setting_ip6_config (connection);
4764                 if (s_ip6 && !nm_setting_ip_config_get_may_fail (s_ip6))
4765                         return TRUE;
4766         }
4767
4768         /* If an IP version wants a carrier and and the other IP version isn't
4769          * used, the connection requires carrier since it will just fail without one.
4770          */
4771         if (ip4_carrier_wanted && !ip6_used)
4772                 return TRUE;
4773         if (ip6_carrier_wanted && !ip4_used)
4774                 return TRUE;
4775
4776         /* If both want a carrier, the whole connection wants a carrier */
4777         return ip4_carrier_wanted && ip6_carrier_wanted;
4778 }
4779
4780 static gboolean
4781 have_any_ready_slaves (NMDevice *self, const GSList *slaves)
4782 {
4783         const GSList *iter;
4784
4785         /* Any enslaved slave is "ready" in the generic case as it's
4786          * at least >= NM_DEVCIE_STATE_IP_CONFIG and has had Layer 2
4787          * properties set up.
4788          */
4789         for (iter = slaves; iter; iter = g_slist_next (iter)) {
4790                 if (nm_device_get_enslaved (iter->data))
4791                         return TRUE;
4792         }
4793         return FALSE;
4794 }
4795
4796 static gboolean
4797 ip4_requires_slaves (NMConnection *connection)
4798 {
4799         const char *method;
4800
4801         method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG);
4802         return strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO) == 0;
4803 }
4804
4805 static NMActStageReturn
4806 act_stage3_ip4_config_start (NMDevice *self,
4807                              NMIP4Config **out_config,
4808                              NMDeviceStateReason *reason)
4809 {
4810         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
4811         NMConnection *connection;
4812         NMActStageReturn ret = NM_ACT_STAGE_RETURN_FAILURE;
4813         const char *method;
4814         GSList *slaves;
4815         gboolean ready_slaves;
4816
4817         g_return_val_if_fail (reason != NULL, NM_ACT_STAGE_RETURN_FAILURE);
4818
4819         connection = nm_device_get_applied_connection (self);
4820         g_assert (connection);
4821
4822         if (   connection_ip4_method_requires_carrier (connection, NULL)
4823             && priv->is_master
4824             && !priv->carrier) {
4825                 _LOGI (LOGD_IP4 | LOGD_DEVICE,
4826                        "IPv4 config waiting until carrier is on");
4827                 return NM_ACT_STAGE_RETURN_WAIT;
4828         }
4829
4830         if (priv->is_master && ip4_requires_slaves (connection)) {
4831                 /* If the master has no ready slaves, and depends on slaves for
4832                  * a successful IPv4 attempt, then postpone IPv4 addressing.
4833                  */
4834                 slaves = nm_device_master_get_slaves (self);
4835                 ready_slaves = NM_DEVICE_GET_CLASS (self)->have_any_ready_slaves (self, slaves);
4836                 g_slist_free (slaves);
4837
4838                 if (ready_slaves == FALSE) {
4839                         _LOGI (LOGD_DEVICE | LOGD_IP4,
4840                                "IPv4 config waiting until slaves are ready");
4841                         return NM_ACT_STAGE_RETURN_WAIT;
4842                 }
4843         }
4844
4845         method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG);
4846
4847         /* Start IPv4 addressing based on the method requested */
4848         if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO) == 0)
4849                 ret = dhcp4_start (self, connection, reason);
4850         else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL) == 0)
4851                 ret = ipv4ll_start (self, reason);
4852         else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_MANUAL) == 0) {
4853                 NMIP4Config **configs, *config;
4854
4855                 config = nm_ip4_config_new (nm_device_get_ip_ifindex (self));
4856                 nm_ip4_config_merge_setting (config,
4857                                              nm_connection_get_setting_ip4_config (connection),
4858                                              nm_device_get_ip4_route_metric (self));
4859
4860                 configs = g_new0 (NMIP4Config *, 2);
4861                 configs[0] = config;
4862                 ipv4_dad_start (self, configs, ipv4_manual_method_apply);
4863                 ret = NM_ACT_STAGE_RETURN_POSTPONE;
4864         } else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_SHARED) == 0) {
4865                 *out_config = shared4_new_config (self, connection, reason);
4866                 if (*out_config) {
4867                         priv->dnsmasq_manager = nm_dnsmasq_manager_new (nm_device_get_ip_iface (self));
4868                         ret = NM_ACT_STAGE_RETURN_SUCCESS;
4869                 } else
4870                         ret = NM_ACT_STAGE_RETURN_FAILURE;
4871         } else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED) == 0) {
4872                 /* Nothing to do... */
4873                 ret = NM_ACT_STAGE_RETURN_STOP;
4874         } else
4875                 _LOGW (LOGD_IP4, "unhandled IPv4 config method '%s'; will fail", method);
4876
4877         return ret;
4878 }
4879
4880 /*********************************************/
4881 /* DHCPv6 stuff */
4882
4883 static void
4884 dhcp6_cleanup (NMDevice *self, CleanupType cleanup_type, gboolean release)
4885 {
4886         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
4887
4888         priv->dhcp6_mode = NM_RDISC_DHCP_LEVEL_NONE;
4889         g_clear_object (&priv->dhcp6_ip6_config);
4890         g_clear_pointer (&priv->dhcp6_event_id, g_free);
4891         nm_clear_g_source (&priv->dhcp6_restart_id);
4892
4893         if (priv->dhcp6_client) {
4894                 nm_clear_g_signal_handler (priv->dhcp6_client, &priv->dhcp6_state_sigid);
4895
4896                 if (   cleanup_type == CLEANUP_TYPE_DECONFIGURE
4897                     || cleanup_type == CLEANUP_TYPE_REMOVED)
4898                         nm_dhcp_client_stop (priv->dhcp6_client, release);
4899
4900                 g_clear_object (&priv->dhcp6_client);
4901         }
4902
4903         nm_device_remove_pending_action (self, PENDING_ACTION_DHCP6, FALSE);
4904
4905         if (priv->dhcp6_config) {
4906                 nm_exported_object_clear_and_unexport (&priv->dhcp6_config);
4907                 _notify (self, PROP_DHCP6_CONFIG);
4908         }
4909 }
4910
4911 static void
4912 _ip6_config_merge_default (gpointer value, gpointer user_data)
4913 {
4914         NMIP6Config *src = (NMIP6Config *) value;
4915         NMIP6Config *dst = (NMIP6Config *) user_data;
4916
4917         nm_ip6_config_merge (dst, src, NM_IP_CONFIG_MERGE_DEFAULT);
4918 }
4919
4920 static gboolean
4921 ip6_config_merge_and_apply (NMDevice *self,
4922                             gboolean commit,
4923                             NMDeviceStateReason *out_reason)
4924 {
4925         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
4926         NMConnection *connection;
4927         gboolean success;
4928         NMIP6Config *composite;
4929         gboolean has_direct_route;
4930         const struct in6_addr *gateway;
4931         gboolean connection_has_default_route, connection_is_never_default;
4932         gboolean routes_full_sync;
4933         gboolean ignore_auto_routes = FALSE;
4934         gboolean ignore_auto_dns = FALSE;
4935
4936         /* Apply ignore-auto-routes and ignore-auto-dns settings */
4937         connection = nm_device_get_applied_connection (self);
4938         if (connection) {
4939                 NMSettingIPConfig *s_ip6 = nm_connection_get_setting_ip6_config (connection);
4940
4941                 if (s_ip6) {
4942                         ignore_auto_routes = nm_setting_ip_config_get_ignore_auto_routes (s_ip6);
4943                         ignore_auto_dns = nm_setting_ip_config_get_ignore_auto_dns (s_ip6);
4944                 }
4945         }
4946
4947         /* If no config was passed in, create a new one */
4948         composite = nm_ip6_config_new (nm_device_get_ip_ifindex (self));
4949
4950         if (commit)
4951                 ensure_con_ip6_config (self);
4952         g_assert (composite);
4953
4954         /* Merge all the IP configs into the composite config */
4955         if (priv->ac_ip6_config) {
4956                 nm_ip6_config_merge (composite, priv->ac_ip6_config,
4957                                        (ignore_auto_routes ? NM_IP_CONFIG_MERGE_NO_ROUTES : 0)
4958                                      | (ignore_auto_dns ? NM_IP_CONFIG_MERGE_NO_DNS : 0));
4959         }
4960         if (priv->dhcp6_ip6_config) {
4961                 nm_ip6_config_merge (composite, priv->dhcp6_ip6_config,
4962                                        (ignore_auto_routes ? NM_IP_CONFIG_MERGE_NO_ROUTES : 0)
4963                                      | (ignore_auto_dns ? NM_IP_CONFIG_MERGE_NO_DNS : 0));
4964         }
4965
4966         g_slist_foreach (priv->vpn6_configs, _ip6_config_merge_default, composite);
4967
4968         if (priv->ext_ip6_config)
4969                 nm_ip6_config_merge (composite, priv->ext_ip6_config, NM_IP_CONFIG_MERGE_DEFAULT);
4970
4971         /* Merge WWAN config *last* to ensure modem-given settings overwrite
4972          * any external stuff set by pppd or other scripts.
4973          */
4974         if (priv->wwan_ip6_config) {
4975                 nm_ip6_config_merge (composite, priv->wwan_ip6_config,
4976                                        (ignore_auto_routes ? NM_IP_CONFIG_MERGE_NO_ROUTES : 0)
4977                                      | (ignore_auto_dns ? NM_IP_CONFIG_MERGE_NO_DNS : 0));
4978         }
4979
4980         /* Merge user overrides into the composite config. For assumed connections,
4981          * con_ip6_config is empty. */
4982         if (priv->con_ip6_config)
4983                 nm_ip6_config_merge (composite, priv->con_ip6_config, NM_IP_CONFIG_MERGE_DEFAULT);
4984
4985         /* Add the default route.
4986          *
4987          * We keep track of the default route of a device in a private field.
4988          * NMDevice needs to know the default route at this point, because the gateway
4989          * might require a direct route (see below).
4990          *
4991          * But also, we don't want to add the default route to priv->ip6_config,
4992          * because the default route from the setting might not be the same that
4993          * NMDefaultRouteManager eventually configures (because the it might
4994          * tweak the effective metric).
4995          */
4996
4997         /* unless we come to a different conclusion below, we have no default route and
4998          * the route is assumed. */
4999         priv->default_route.v6_has = FALSE;
5000         priv->default_route.v6_is_assumed = TRUE;
5001
5002         if (!commit) {
5003                 /* during a non-commit event, we always pickup whatever is configured. */
5004                 goto END_ADD_DEFAULT_ROUTE;
5005         }
5006
5007         if (nm_device_uses_generated_assumed_connection (self)) {
5008                 /* a generate-assumed-connection always detects the default route from platform */
5009                 goto END_ADD_DEFAULT_ROUTE;
5010         }
5011
5012         /* At this point, we treat assumed and non-assumed connections alike.
5013          * For assumed connections we do that because we still manage RA and DHCP
5014          * leases for them, so we must extend/update the default route on commits.
5015          */
5016
5017         connection_has_default_route
5018             = nm_default_route_manager_ip6_connection_has_default_route (nm_default_route_manager_get (),
5019                                                                          connection, &connection_is_never_default);
5020
5021         if (   !priv->v6_commit_first_time
5022             && connection_is_never_default) {
5023                 /* If the connection is explicitly configured as never-default, we enforce the (absence of the)
5024                  * default-route only once. That allows the user to configure a connection as never-default,
5025                  * but he can add default routes externally (via a dispatcher script) and NM will not interfere. */
5026                 goto END_ADD_DEFAULT_ROUTE;
5027         }
5028
5029         /* we are about to commit (for a non-assumed connection). Enforce whatever we have
5030          * configured. */
5031         priv->default_route.v6_is_assumed = FALSE;
5032
5033         if (!connection_has_default_route)
5034                 goto END_ADD_DEFAULT_ROUTE;
5035
5036         if (!nm_ip6_config_get_num_addresses (composite)) {
5037                 /* without addresses we can have no default route. */
5038                 goto END_ADD_DEFAULT_ROUTE;
5039         }
5040
5041         gateway = nm_ip6_config_get_gateway (composite);
5042         if (!gateway)
5043                 goto END_ADD_DEFAULT_ROUTE;
5044
5045
5046         has_direct_route = nm_ip6_config_get_direct_route_for_host (composite, gateway) != NULL;
5047
5048
5049
5050         priv->default_route.v6_has = TRUE;
5051         memset (&priv->default_route.v6, 0, sizeof (priv->default_route.v6));
5052         priv->default_route.v6.source = NM_IP_CONFIG_SOURCE_USER;
5053         priv->default_route.v6.gateway = *gateway;
5054         priv->default_route.v6.metric = nm_device_get_ip6_route_metric (self);
5055         priv->default_route.v6.mss = nm_ip6_config_get_mss (composite);
5056
5057         if (!has_direct_route) {
5058                 NMPlatformIP6Route r = priv->default_route.v6;
5059
5060                 /* add a direct route to the gateway */
5061                 r.network = *gateway;
5062                 r.plen = 128;
5063                 r.gateway = in6addr_any;
5064                 nm_ip6_config_add_route (composite, &r);
5065         }
5066
5067 END_ADD_DEFAULT_ROUTE:
5068
5069         if (priv->default_route.v6_is_assumed) {
5070                 /* If above does not explicitly assign a default route, we always pick up the
5071                  * default route based on what is currently configured.
5072                  * That means that even managed connections with never-default, can
5073                  * get a default route (if configured externally).
5074                  */
5075                 priv->default_route.v6_has = _device_get_default_route_from_platform (self, AF_INET6, (NMPlatformIPRoute *) &priv->default_route.v6);
5076         }
5077
5078         nm_ip6_config_addresses_sort (composite,
5079             priv->rdisc ? priv->rdisc_use_tempaddr : NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN);
5080
5081         /* Allow setting MTU etc */
5082         if (commit) {
5083                 if (NM_DEVICE_GET_CLASS (self)->ip6_config_pre_commit)
5084                         NM_DEVICE_GET_CLASS (self)->ip6_config_pre_commit (self, composite);
5085         }
5086
5087         routes_full_sync =    commit
5088                            && priv->v6_commit_first_time
5089                            && !nm_device_uses_assumed_connection (self);
5090
5091         success = nm_device_set_ip6_config (self, composite, commit, routes_full_sync, out_reason);
5092         g_object_unref (composite);
5093         if (commit)
5094                 priv->v6_commit_first_time = FALSE;
5095         return success;
5096 }
5097
5098 static void
5099 dhcp6_lease_change (NMDevice *self)
5100 {
5101         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
5102         NMSettingsConnection *settings_connection;
5103         NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE;
5104
5105         if (priv->dhcp6_ip6_config == NULL) {
5106                 _LOGW (LOGD_DHCP6, "failed to get DHCPv6 config for rebind");
5107                 nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED);
5108                 return;
5109         }
5110
5111         g_assert (priv->dhcp6_client);  /* sanity check */
5112
5113         settings_connection = nm_device_get_settings_connection (self);
5114         g_assert (settings_connection);
5115
5116         /* Apply the updated config */
5117         if (ip6_config_merge_and_apply (self, TRUE, &reason) == FALSE) {
5118                 _LOGW (LOGD_DHCP6, "failed to update IPv6 config in response to DHCP event.");
5119                 nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason);
5120         } else {
5121                 /* Notify dispatcher scripts of new DHCPv6 config */
5122                 nm_dispatcher_call (DISPATCHER_ACTION_DHCP6_CHANGE,
5123                                     settings_connection,
5124                                     nm_device_get_applied_connection (self),
5125                                     self, NULL, NULL, NULL);
5126         }
5127 }
5128
5129 static gboolean
5130 dhcp6_restart_cb (gpointer user_data)
5131 {
5132         NMDevice *self = user_data;
5133         NMDevicePrivate *priv;
5134         NMDeviceStateReason reason;
5135
5136         g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
5137
5138         priv = NM_DEVICE_GET_PRIVATE (self);
5139         priv->dhcp6_restart_id = 0;
5140
5141         if (!dhcp6_start (self, FALSE, &reason))
5142                 priv->dhcp6_restart_id = g_timeout_add_seconds (120, dhcp6_restart_cb, self);
5143
5144         return FALSE;
5145 }
5146
5147 static void
5148 dhcp6_fail (NMDevice *self, gboolean timeout)
5149 {
5150         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
5151
5152         dhcp6_cleanup (self, CLEANUP_TYPE_DECONFIGURE, FALSE);
5153
5154         if (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_MANAGED) {
5155                 /* Don't fail if there are static addresses configured on
5156                  * the device, instead retry after some time.
5157                  */
5158                 if (   priv->ip6_state == IP_DONE
5159                     && priv->con_ip6_config
5160                     && nm_ip6_config_get_num_addresses (priv->con_ip6_config)) {
5161                         _LOGI (LOGD_DHCP6, "Scheduling DHCPv6 restart because device has IP addresses");
5162                         priv->dhcp6_restart_id = g_timeout_add_seconds (120, dhcp6_restart_cb, self);
5163                         return;
5164                 }
5165
5166                 /* Instead of letting an assumed connection fail (which means that the
5167                  * device will transition to the ACTIVATED state without IP configuration),
5168                  * retry DHCP again.
5169                  */
5170                 if (nm_device_uses_assumed_connection (self)) {
5171                         _LOGI (LOGD_DHCP6, "Scheduling DHCPv6 restart because the connection is assumed");
5172                         priv->dhcp6_restart_id = g_timeout_add_seconds (120, dhcp6_restart_cb, self);
5173                         return;
5174                 }
5175
5176                 if (timeout || (priv->ip6_state == IP_CONF))
5177                         nm_device_activate_schedule_ip6_config_timeout (self);
5178                 else if (priv->ip6_state == IP_DONE)
5179                         nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED);
5180                 else
5181                         g_warn_if_reached ();
5182         } else {
5183                 /* not a hard failure; just live with the RA info */
5184                 if (priv->ip6_state == IP_CONF)
5185                         nm_device_activate_schedule_ip6_config_result (self);
5186         }
5187 }
5188
5189 static void
5190 dhcp6_timeout (NMDevice *self, NMDhcpClient *client)
5191 {
5192         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
5193
5194         if (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_MANAGED)
5195                 dhcp6_fail (self, TRUE);
5196         else {
5197                 /* not a hard failure; just live with the RA info */
5198                 dhcp6_cleanup (self, CLEANUP_TYPE_DECONFIGURE, FALSE);
5199                 if (priv->ip6_state == IP_CONF)
5200                         nm_device_activate_schedule_ip6_config_result (self);
5201         }
5202 }
5203
5204 static void
5205 dhcp6_state_changed (NMDhcpClient *client,
5206                      NMDhcpState state,
5207                      NMIP6Config *ip6_config,
5208                      GHashTable *options,
5209                      const char *event_id,
5210                      gpointer user_data)
5211 {
5212         NMDevice *self = NM_DEVICE (user_data);
5213         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
5214         guint i;
5215
5216         g_return_if_fail (nm_dhcp_client_get_ipv6 (client) == TRUE);
5217         g_return_if_fail (!ip6_config || NM_IS_IP6_CONFIG (ip6_config));
5218
5219         _LOGD (LOGD_DHCP6, "new DHCPv6 client state %d", state);
5220
5221         switch (state) {
5222         case NM_DHCP_STATE_BOUND:
5223                 /* If the server sends multiple IPv6 addresses, we receive a state
5224                  * changed event for each of them. Use the event ID to merge IPv6
5225                  * addresses from the same transaction into a single configuration.
5226                  */
5227                 if (   ip6_config
5228                     && event_id
5229                     && priv->dhcp6_event_id
5230                     && !strcmp (event_id, priv->dhcp6_event_id)) {
5231                         for (i = 0; i < nm_ip6_config_get_num_addresses (ip6_config); i++) {
5232                                 nm_ip6_config_add_address (priv->dhcp6_ip6_config,
5233                                                            nm_ip6_config_get_address (ip6_config, i));
5234                         }
5235                 } else {
5236                         g_clear_object (&priv->dhcp6_ip6_config);
5237                         g_clear_pointer (&priv->dhcp6_event_id, g_free);
5238                         if (ip6_config) {
5239                                 priv->dhcp6_ip6_config = g_object_ref (ip6_config);
5240                                 priv->dhcp6_event_id = g_strdup (event_id);
5241                                 nm_dhcp6_config_set_options (priv->dhcp6_config, options);
5242                                 _notify (self, PROP_DHCP6_CONFIG);
5243                         }
5244                 }
5245
5246                 if (priv->ip6_state == IP_CONF) {
5247                         if (priv->dhcp6_ip6_config == NULL) {
5248                                 /* FIXME: Initial DHCP failed; should we fail IPv6 entirely then? */
5249                                 nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_DHCP_FAILED);
5250                                 break;
5251                         }
5252                         nm_device_activate_schedule_ip6_config_result (self);
5253                 } else if (priv->ip6_state == IP_DONE)
5254                         dhcp6_lease_change (self);
5255                 break;
5256         case NM_DHCP_STATE_TIMEOUT:
5257                 dhcp6_timeout (self, client);
5258                 break;
5259         case NM_DHCP_STATE_EXPIRE:
5260                 /* Ignore expiry before we even have a lease (NAK, old lease, etc) */
5261                 if (priv->ip6_state != IP_CONF)
5262                         dhcp6_fail (self, FALSE);
5263                 break;
5264         case NM_DHCP_STATE_DONE:
5265                 /* In IPv6 info-only mode, the client doesn't handle leases so it
5266                  * may exit right after getting a response from the server.  That's
5267                  * normal.  In that case we just ignore the exit.
5268                  */
5269                 if (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_OTHERCONF)
5270                         break;
5271                 /* Otherwise, fall through */
5272         case NM_DHCP_STATE_FAIL:
5273                 dhcp6_fail (self, FALSE);
5274                 break;
5275         default:
5276                 break;
5277         }
5278 }
5279
5280 static gboolean
5281 dhcp6_start_with_link_ready (NMDevice *self, NMConnection *connection)
5282 {
5283         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
5284         NMSettingIPConfig *s_ip6;
5285         GByteArray *tmp = NULL;
5286         const guint8 *hw_addr;
5287         size_t hw_addr_len = 0;
5288         const NMPlatformIP6Address *ll_addr = NULL;
5289
5290         g_assert (connection);
5291         s_ip6 = nm_connection_get_setting_ip6_config (connection);
5292         g_assert (s_ip6);
5293
5294         hw_addr = nm_platform_link_get_address (NM_PLATFORM_GET, nm_device_get_ip_ifindex (self), &hw_addr_len);
5295         if (hw_addr_len) {
5296                 tmp = g_byte_array_sized_new (hw_addr_len);
5297                 g_byte_array_append (tmp, hw_addr, hw_addr_len);
5298         }
5299
5300         if (priv->ext_ip6_config_captured)
5301                 ll_addr = nm_ip6_config_get_address_first_nontentative (priv->ext_ip6_config_captured, TRUE);
5302
5303         g_return_val_if_fail (ll_addr, FALSE);
5304
5305         priv->dhcp6_client = nm_dhcp_manager_start_ip6 (nm_dhcp_manager_get (),
5306                                                         nm_device_get_ip_iface (self),
5307                                                         nm_device_get_ip_ifindex (self),
5308                                                         tmp,
5309                                                         &ll_addr->address,
5310                                                         nm_connection_get_uuid (connection),
5311                                                         nm_device_get_ip6_route_metric (self),
5312                                                         nm_setting_ip_config_get_dhcp_send_hostname (s_ip6),
5313                                                         nm_setting_ip_config_get_dhcp_hostname (s_ip6),
5314                                                         priv->dhcp_timeout,
5315                                                         priv->dhcp_anycast_address,
5316                                                         (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_OTHERCONF) ? TRUE : FALSE,
5317                                                         nm_setting_ip6_config_get_ip6_privacy (NM_SETTING_IP6_CONFIG (s_ip6)));
5318         if (tmp)
5319                 g_byte_array_free (tmp, TRUE);
5320
5321         if (priv->dhcp6_client) {
5322                 priv->dhcp6_state_sigid = g_signal_connect (priv->dhcp6_client,
5323                                                             NM_DHCP_CLIENT_SIGNAL_STATE_CHANGED,
5324                                                             G_CALLBACK (dhcp6_state_changed),
5325                                                             self);
5326         }
5327
5328         return !!priv->dhcp6_client;
5329 }
5330
5331 static gboolean
5332 dhcp6_start (NMDevice *self, gboolean wait_for_ll, NMDeviceStateReason *reason)
5333 {
5334         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
5335         NMConnection *connection;
5336         NMSettingIPConfig *s_ip6;
5337
5338         nm_exported_object_clear_and_unexport (&priv->dhcp6_config);
5339         priv->dhcp6_config = nm_dhcp6_config_new ();
5340
5341         g_warn_if_fail (priv->dhcp6_ip6_config == NULL);
5342         g_clear_object (&priv->dhcp6_ip6_config);
5343         g_clear_pointer (&priv->dhcp6_event_id, g_free);
5344
5345         connection = nm_device_get_applied_connection (self);
5346         g_assert (connection);
5347         s_ip6 = nm_connection_get_setting_ip6_config (connection);
5348         if (!nm_setting_ip_config_get_may_fail (s_ip6) ||
5349             !strcmp (nm_setting_ip_config_get_method (s_ip6), NM_SETTING_IP6_CONFIG_METHOD_DHCP))
5350                 nm_device_add_pending_action (self, PENDING_ACTION_DHCP6, TRUE);
5351
5352         if (wait_for_ll) {
5353                 NMActStageReturn ret;
5354
5355                 /* ensure link local is ready... */
5356                 ret = linklocal6_start (self);
5357                 if (ret == NM_ACT_STAGE_RETURN_POSTPONE) {
5358                         /* success; wait for the LL address to show up */
5359                         return TRUE;
5360                 }
5361
5362                 /* success; already have the LL address; kick off DHCP */
5363                 g_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS || ret == NM_ACT_STAGE_RETURN_FINISH);
5364         }
5365
5366         if (!dhcp6_start_with_link_ready (self, connection)) {
5367                 *reason = NM_DEVICE_STATE_REASON_DHCP_START_FAILED;
5368                 return FALSE;
5369         }
5370
5371         return TRUE;
5372 }
5373
5374 gboolean
5375 nm_device_dhcp6_renew (NMDevice *self, gboolean release)
5376 {
5377         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
5378
5379         g_return_val_if_fail (priv->dhcp6_client != NULL, FALSE);
5380
5381         _LOGI (LOGD_DHCP6, "DHCPv6 lease renewal requested");
5382
5383         /* Terminate old DHCP instance and release the old lease */
5384         dhcp6_cleanup (self, CLEANUP_TYPE_DECONFIGURE, release);
5385
5386         /* Start DHCP again on the interface */
5387         return dhcp6_start (self, FALSE, NULL);
5388 }
5389
5390 /******************************************/
5391
5392 static void
5393 linklocal6_cleanup (NMDevice *self)
5394 {
5395         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
5396
5397         nm_clear_g_source (&priv->linklocal6_timeout_id);
5398 }
5399
5400 static void
5401 linklocal6_failed (NMDevice *self)
5402 {
5403         linklocal6_cleanup (self);
5404         nm_device_activate_schedule_ip6_config_timeout (self);
5405 }
5406
5407 static gboolean
5408 linklocal6_timeout_cb (gpointer user_data)
5409 {
5410         NMDevice *self = user_data;
5411
5412         _LOGD (LOGD_DEVICE, "linklocal6: waiting for link-local addresses failed due to timeout");
5413         linklocal6_failed (self);
5414         return G_SOURCE_REMOVE;
5415 }
5416
5417 static void
5418 linklocal6_complete (NMDevice *self)
5419 {
5420         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
5421         NMConnection *connection;
5422         const char *method;
5423
5424         g_assert (priv->linklocal6_timeout_id);
5425         g_assert (nm_ip6_config_get_address_first_nontentative (priv->ip6_config, TRUE));
5426
5427         linklocal6_cleanup (self);
5428
5429         connection = nm_device_get_applied_connection (self);
5430         g_assert (connection);
5431
5432         method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG);
5433
5434         _LOGD (LOGD_DEVICE, "linklocal6: waiting for link-local addresses successful, continue with method %s", method);
5435
5436         if (strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_AUTO) == 0) {
5437                 if (!addrconf6_start_with_link_ready (self)) {
5438                         /* Time out IPv6 instead of failing the entire activation */
5439                         nm_device_activate_schedule_ip6_config_timeout (self);
5440                 }
5441         } else if (strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_DHCP) == 0) {
5442                 if (!dhcp6_start_with_link_ready (self, connection)) {
5443                         /* Time out IPv6 instead of failing the entire activation */
5444                         nm_device_activate_schedule_ip6_config_timeout (self);
5445                 }
5446         } else if (strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL) == 0)
5447                 nm_device_activate_schedule_ip6_config_result (self);
5448         else
5449                 g_return_if_fail (FALSE);
5450 }
5451
5452 static void
5453 check_and_add_ipv6ll_addr (NMDevice *self)
5454 {
5455         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
5456         int ip_ifindex = nm_device_get_ip_ifindex (self);
5457         struct in6_addr lladdr;
5458         guint i, n;
5459         NMConnection *connection;
5460         NMSettingIP6Config *s_ip6 = NULL;
5461         GError *error = NULL;
5462
5463         if (priv->nm_ipv6ll == FALSE)
5464                 return;
5465
5466         if (priv->ip6_config) {
5467                 n = nm_ip6_config_get_num_addresses (priv->ip6_config);
5468                 for (i = 0; i < n; i++) {
5469                         const NMPlatformIP6Address *addr;
5470
5471                         addr = nm_ip6_config_get_address (priv->ip6_config, i);
5472                         if (   IN6_IS_ADDR_LINKLOCAL (&addr->address)
5473                             && !(addr->n_ifa_flags & IFA_F_DADFAILED)) {
5474                                 /* Already have an LL address, nothing to do */
5475                                 return;
5476                         }
5477                 }
5478         }
5479
5480         memset (&lladdr, 0, sizeof (lladdr));
5481         lladdr.s6_addr16[0] = htons (0xfe80);
5482
5483         connection = nm_device_get_applied_connection (self);
5484         if (connection)
5485                 s_ip6 = NM_SETTING_IP6_CONFIG (nm_connection_get_setting_ip6_config (connection));
5486
5487         if (s_ip6 && nm_setting_ip6_config_get_addr_gen_mode (s_ip6) == NM_SETTING_IP6_CONFIG_ADDR_GEN_MODE_STABLE_PRIVACY) {
5488                 if (!nm_utils_ipv6_addr_set_stable_privacy (&lladdr,
5489                                                             nm_device_get_iface (self),
5490                                                             nm_connection_get_uuid (connection),
5491                                                             priv->linklocal6_dad_counter++,
5492                                                             &error)) {
5493                         _LOGW (LOGD_IP6, "linklocal6: failed to generate an address: %s", error->message);
5494                         g_clear_error (&error);
5495                         linklocal6_failed (self);
5496                         return;
5497                 }
5498                 _LOGD (LOGD_IP6, "linklocal6: using IPv6 stable-privacy addressing");
5499         } else {
5500                 NMUtilsIPv6IfaceId iid;
5501
5502                 if (priv->linklocal6_timeout_id) {
5503                         /* We already started and attempt to add a LL address. For the EUI-64
5504                          * mode we can't pick a new one, we'll just fail. */
5505                         _LOGW (LOGD_IP6, "linklocal6: DAD failed for an EUI-64 address");
5506                         linklocal6_failed (self);
5507                         return;
5508                 }
5509
5510                 if (!nm_device_get_ip_iface_identifier (self, &iid)) {
5511                         _LOGW (LOGD_IP6, "linklocal6: failed to get interface identifier; IPv6 cannot continue");
5512                         return;
5513                 }
5514                 _LOGD (LOGD_IP6, "linklocal6: using EUI-64 identifier to generate IPv6LL address");
5515
5516                 nm_utils_ipv6_addr_set_interface_identfier (&lladdr, iid);
5517         }
5518
5519         _LOGD (LOGD_IP6, "linklocal6: adding IPv6LL address %s", nm_utils_inet6_ntop (&lladdr, NULL));
5520         if (!nm_platform_ip6_address_add (NM_PLATFORM_GET,
5521                                           ip_ifindex,
5522                                           lladdr,
5523                                           64,
5524                                           in6addr_any,
5525                                           NM_PLATFORM_LIFETIME_PERMANENT,
5526                                           NM_PLATFORM_LIFETIME_PERMANENT,
5527                                           0)) {
5528                 _LOGW (LOGD_IP6, "failed to add IPv6 link-local address %s",
5529                        nm_utils_inet6_ntop (&lladdr, NULL));
5530         }
5531 }
5532
5533 static NMActStageReturn
5534 linklocal6_start (NMDevice *self)
5535 {
5536         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
5537         NMConnection *connection;
5538         const char *method;
5539
5540         linklocal6_cleanup (self);
5541
5542         if (   priv->ip6_config
5543             && nm_ip6_config_get_address_first_nontentative (priv->ip6_config, TRUE))
5544                 return NM_ACT_STAGE_RETURN_FINISH;
5545
5546         connection = nm_device_get_applied_connection (self);
5547         g_assert (connection);
5548
5549         method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG);
5550         _LOGD (LOGD_DEVICE, "linklocal6: starting IPv6 with method '%s', but the device has no link-local addresses configured. Wait.", method);
5551
5552         check_and_add_ipv6ll_addr (self);
5553
5554         /* Depending on the network and what the 'dad_transmits' and 'retrans_time_ms'
5555          * sysctl values are, DAD for the IPv6LL address may take quite a while.
5556          * FIXME: use dad/retrans sysctl values if they are higher than a minimum time.
5557          * (rh #1101809)
5558          */
5559         priv->linklocal6_timeout_id = g_timeout_add_seconds (15, linklocal6_timeout_cb, self);
5560
5561         return NM_ACT_STAGE_RETURN_POSTPONE;
5562 }
5563
5564 /******************************************/
5565
5566 static void nm_device_ipv6_set_mtu (NMDevice *self, guint32 mtu);
5567
5568 static void
5569 nm_device_set_mtu (NMDevice *self, guint32 mtu)
5570 {
5571         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
5572         int ifindex = nm_device_get_ip_ifindex (self);
5573
5574         if (mtu)
5575                 priv->mtu = mtu;
5576
5577         /* Ensure the IPv6 MTU is still alright. */
5578         if (priv->ip6_mtu)
5579                 nm_device_ipv6_set_mtu (self, priv->ip6_mtu);
5580
5581         if (priv->mtu && priv->mtu != nm_platform_link_get_mtu (NM_PLATFORM_GET, ifindex))
5582                 nm_platform_link_set_mtu (NM_PLATFORM_GET, ifindex, priv->mtu);
5583 }
5584
5585 static void
5586 nm_device_ipv6_set_mtu (NMDevice *self, guint32 mtu)
5587 {
5588         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
5589         guint32 plat_mtu = nm_device_ipv6_sysctl_get_int32 (self, "mtu", priv->mtu);
5590         char val[16];
5591
5592         priv->ip6_mtu = mtu ?: plat_mtu;
5593
5594         if (priv->ip6_mtu && priv->mtu && priv->mtu < priv->ip6_mtu) {
5595                 _LOGI (LOGD_DEVICE | LOGD_IP6, "Lowering IPv6 MTU (%d) to match device MTU (%d)",
5596                        priv->ip6_mtu, priv->mtu);
5597                 priv->ip6_mtu = priv->mtu;
5598         }
5599
5600         if (priv->ip6_mtu && priv->ip6_mtu < 1280) {
5601                 _LOGI (LOGD_DEVICE | LOGD_IP6, "IPv6 MTU (%d) smaller than 1280, adjusting",
5602                        priv->ip6_mtu);
5603                 priv->ip6_mtu = 1280;
5604         }
5605
5606         if (priv->ip6_mtu && priv->mtu && priv->mtu < priv->ip6_mtu) {
5607                 _LOGI (LOGD_DEVICE | LOGD_IP6, "Raising device MTU (%d) to match IPv6 MTU (%d)",
5608                        priv->mtu, priv->ip6_mtu);
5609                 nm_device_set_mtu (self, priv->ip6_mtu);
5610         }
5611
5612         if (priv->ip6_mtu != plat_mtu) {
5613                 g_snprintf (val, sizeof (val), "%d", mtu);
5614                 nm_device_ipv6_sysctl_set (self, "mtu", val);
5615         }
5616 }
5617
5618 static void
5619 rdisc_config_changed (NMRDisc *rdisc, NMRDiscConfigMap changed, NMDevice *self)
5620 {
5621         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
5622         int i;
5623         int system_support;
5624         guint32 ifa_flags = 0x00;
5625
5626         /*
5627          * Check, whether kernel is recent enough to help user space handling RA.
5628          * If it's not supported, we have no ipv6-privacy and must add autoconf
5629          * addresses as /128. The reason for the /128 is to prevent the kernel
5630          * from adding a prefix route for this address.
5631          **/
5632         system_support = nm_platform_check_support_kernel_extended_ifa_flags (NM_PLATFORM_GET);
5633
5634         if (system_support)
5635                 ifa_flags = IFA_F_NOPREFIXROUTE;
5636         if (   priv->rdisc_use_tempaddr == NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_TEMP_ADDR
5637             || priv->rdisc_use_tempaddr == NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_PUBLIC_ADDR)
5638         {
5639                 /* without system_support, this flag will be ignored. Still set it, doesn't seem to do any harm. */
5640                 ifa_flags |= IFA_F_MANAGETEMPADDR;
5641         }
5642
5643         g_return_if_fail (priv->act_request);
5644
5645         if (!priv->ac_ip6_config)
5646                 priv->ac_ip6_config = nm_ip6_config_new (nm_device_get_ip_ifindex (self));
5647
5648         if (changed & NM_RDISC_CONFIG_GATEWAYS) {
5649                 /* Use the first gateway as ordered in router discovery cache. */
5650                 if (rdisc->gateways->len) {
5651                         NMRDiscGateway *gateway = &g_array_index (rdisc->gateways, NMRDiscGateway, 0);
5652
5653                         nm_ip6_config_set_gateway (priv->ac_ip6_config, &gateway->address);
5654                 } else
5655                         nm_ip6_config_set_gateway (priv->ac_ip6_config, NULL);
5656         }
5657
5658         if (changed & NM_RDISC_CONFIG_ADDRESSES) {
5659                 /* Rebuild address list from router discovery cache. */
5660                 nm_ip6_config_reset_addresses (priv->ac_ip6_config);
5661
5662                 /* rdisc->addresses contains at most max_addresses entries.
5663                  * This is different from what the kernel does, which
5664                  * also counts static and temporary addresses when checking
5665                  * max_addresses.
5666                  **/
5667                 for (i = 0; i < rdisc->addresses->len; i++) {
5668                         NMRDiscAddress *discovered_address = &g_array_index (rdisc->addresses, NMRDiscAddress, i);
5669                         NMPlatformIP6Address address;
5670
5671                         memset (&address, 0, sizeof (address));
5672                         address.address = discovered_address->address;
5673                         address.plen = system_support ? 64 : 128;
5674                         address.timestamp = discovered_address->timestamp;
5675                         address.lifetime = discovered_address->lifetime;
5676                         address.preferred = discovered_address->preferred;
5677                         if (address.preferred > address.lifetime)
5678                                 address.preferred = address.lifetime;
5679                         address.source = NM_IP_CONFIG_SOURCE_RDISC;
5680                         address.n_ifa_flags = ifa_flags;
5681
5682                         nm_ip6_config_add_address (priv->ac_ip6_config, &address);
5683                 }
5684         }
5685
5686         if (changed & NM_RDISC_CONFIG_ROUTES) {
5687                 /* Rebuild route list from router discovery cache. */
5688                 nm_ip6_config_reset_routes (priv->ac_ip6_config);
5689
5690                 for (i = 0; i < rdisc->routes->len; i++) {
5691                         NMRDiscRoute *discovered_route = &g_array_index (rdisc->routes, NMRDiscRoute, i);
5692                         NMPlatformIP6Route route;
5693
5694                         /* Only accept non-default routes.  The router has no idea what the
5695                          * local configuration or user preferences are, so sending routes
5696                          * with a prefix length of 0 is quite rude and thus ignored.
5697                          */
5698                         if (discovered_route->plen > 0) {
5699                                 memset (&route, 0, sizeof (route));
5700                                 route.network = discovered_route->network;
5701                                 route.plen = discovered_route->plen;
5702                                 route.gateway = discovered_route->gateway;
5703                                 route.source = NM_IP_CONFIG_SOURCE_RDISC;
5704                                 route.metric = nm_device_get_ip6_route_metric (self);
5705
5706                                 nm_ip6_config_add_route (priv->ac_ip6_config, &route);
5707                         }
5708                 }
5709         }
5710
5711         if (changed & NM_RDISC_CONFIG_DNS_SERVERS) {
5712                 /* Rebuild DNS server list from router discovery cache. */
5713                 nm_ip6_config_reset_nameservers (priv->ac_ip6_config);
5714
5715                 for (i = 0; i < rdisc->dns_servers->len; i++) {
5716                         NMRDiscDNSServer *discovered_server = &g_array_index (rdisc->dns_servers, NMRDiscDNSServer, i);
5717
5718                         nm_ip6_config_add_nameserver (priv->ac_ip6_config, &discovered_server->address);
5719                 }
5720         }
5721
5722         if (changed & NM_RDISC_CONFIG_DNS_DOMAINS) {
5723                 /* Rebuild domain list from router discovery cache. */
5724                 nm_ip6_config_reset_domains (priv->ac_ip6_config);
5725
5726                 for (i = 0; i < rdisc->dns_domains->len; i++) {
5727                         NMRDiscDNSDomain *discovered_domain = &g_array_index (rdisc->dns_domains, NMRDiscDNSDomain, i);
5728
5729                         nm_ip6_config_add_domain (priv->ac_ip6_config, discovered_domain->domain);
5730                 }
5731         }
5732
5733         if (changed & NM_RDISC_CONFIG_DHCP_LEVEL) {
5734                 dhcp6_cleanup (self, CLEANUP_TYPE_DECONFIGURE, TRUE);
5735
5736                 priv->dhcp6_mode = rdisc->dhcp_level;
5737                 if (priv->dhcp6_mode != NM_RDISC_DHCP_LEVEL_NONE) {
5738                         NMDeviceStateReason reason;
5739
5740                         _LOGD (LOGD_DEVICE | LOGD_DHCP6,
5741                                "Activation: Stage 3 of 5 (IP Configure Start) starting DHCPv6"
5742                                " as requested by IPv6 router...");
5743                         if (!dhcp6_start (self, FALSE, &reason)) {
5744                                 if (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_MANAGED) {
5745                                         nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason);
5746                                         return;
5747                                 }
5748                         }
5749                 }
5750         }
5751
5752         if (changed & NM_RDISC_CONFIG_HOP_LIMIT)
5753                 nm_platform_sysctl_set_ip6_hop_limit_safe (NM_PLATFORM_GET, nm_device_get_ip_iface (self), rdisc->hop_limit);
5754
5755         if (changed & NM_RDISC_CONFIG_MTU)
5756                 priv->ip6_mtu = rdisc->mtu;
5757
5758         nm_device_activate_schedule_ip6_config_result (self);
5759 }
5760
5761 static void
5762 rdisc_ra_timeout (NMRDisc *rdisc, NMDevice *self)
5763 {
5764         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
5765
5766         /* We don't want to stop listening for router advertisements completely,
5767          * but instead let device activation continue activating.  If an RA
5768          * shows up later, we'll use it as long as the device is not disconnected.
5769          */
5770
5771         _LOGD (LOGD_IP6, "timed out waiting for IPv6 router advertisement");
5772         if (priv->ip6_state == IP_CONF) {
5773                 /* If RA is our only source of addressing information and we don't
5774                  * ever receive one, then time out IPv6.  But if there is other
5775                  * IPv6 configuration, like manual IPv6 addresses or external IPv6
5776                  * config, consider that sufficient for IPv6 success.
5777                  */
5778                 if (   priv->ip6_config
5779                     && nm_ip6_config_get_address_first_nontentative (priv->ip6_config, FALSE))
5780                         nm_device_activate_schedule_ip6_config_result (self);
5781                 else
5782                         nm_device_activate_schedule_ip6_config_timeout (self);
5783         }
5784 }
5785
5786 static gboolean
5787 addrconf6_start_with_link_ready (NMDevice *self)
5788 {
5789         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
5790         NMUtilsIPv6IfaceId iid;
5791
5792         g_assert (priv->rdisc);
5793
5794         if (nm_platform_link_get_ipv6_token (NM_PLATFORM_GET, priv->ifindex, &iid)) {
5795                 _LOGD (LOGD_IP6, "addrconf6: IPv6 tokenized identifier present");
5796                 nm_rdisc_set_iid (priv->rdisc, iid);
5797         } else if (nm_device_get_ip_iface_identifier (self, &iid)) {
5798                 _LOGD (LOGD_IP6, "addrconf6: using the device EUI-64 identifier");
5799                 nm_rdisc_set_iid (priv->rdisc, iid);
5800         } else {
5801                 /* Don't abort the addrconf at this point -- if rdisc needs the iid
5802                  * it will notice this itself. */
5803                 _LOGI (LOGD_IP6, "addrconf6: no interface identifier; IPv6 adddress creation may fail");
5804         }
5805
5806         /* Apply any manual configuration before starting RA */
5807         if (!ip6_config_merge_and_apply (self, TRUE, NULL))
5808                 _LOGW (LOGD_IP6, "failed to apply manual IPv6 configuration");
5809
5810         nm_device_ipv6_sysctl_set (self, "accept_ra", "1");
5811         nm_device_ipv6_sysctl_set (self, "accept_ra_defrtr", "0");
5812         nm_device_ipv6_sysctl_set (self, "accept_ra_pinfo", "0");
5813         nm_device_ipv6_sysctl_set (self, "accept_ra_rtr_pref", "0");
5814
5815         priv->rdisc_changed_id = g_signal_connect (priv->rdisc,
5816                                                    NM_RDISC_CONFIG_CHANGED,
5817                                                    G_CALLBACK (rdisc_config_changed),
5818                                                    self);
5819         priv->rdisc_timeout_id = g_signal_connect (priv->rdisc,
5820                                                    NM_RDISC_RA_TIMEOUT,
5821                                                    G_CALLBACK (rdisc_ra_timeout),
5822                                                    self);
5823
5824         nm_rdisc_start (priv->rdisc);
5825         return TRUE;
5826 }
5827
5828 static gboolean
5829 addrconf6_start (NMDevice *self, NMSettingIP6ConfigPrivacy use_tempaddr)
5830 {
5831         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
5832         NMConnection *connection;
5833         NMActStageReturn ret;
5834         NMSettingIP6Config *s_ip6 = NULL;
5835         GError *error = NULL;
5836
5837         connection = nm_device_get_applied_connection (self);
5838         g_assert (connection);
5839
5840         g_warn_if_fail (priv->ac_ip6_config == NULL);
5841         if (priv->ac_ip6_config) {
5842                 g_object_unref (priv->ac_ip6_config);
5843                 priv->ac_ip6_config = NULL;
5844         }
5845
5846         s_ip6 = NM_SETTING_IP6_CONFIG (nm_connection_get_setting_ip6_config (connection));
5847         g_assert (s_ip6);
5848
5849         priv->rdisc = nm_lndp_rdisc_new (NM_PLATFORM_GET,
5850                                          nm_device_get_ip_ifindex (self),
5851                                          nm_device_get_ip_iface (self),
5852                                          nm_connection_get_uuid (connection),
5853                                          nm_setting_ip6_config_get_addr_gen_mode (s_ip6),
5854                                          &error);
5855         if (!priv->rdisc) {
5856                 _LOGE (LOGD_IP6, "addrconf6: failed to start router discovery: %s", error->message);
5857                 g_error_free (error);
5858                 return FALSE;
5859         }
5860
5861         priv->rdisc_use_tempaddr = use_tempaddr;
5862
5863         if (   NM_IN_SET (use_tempaddr, NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_TEMP_ADDR, NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_PUBLIC_ADDR)
5864             && !nm_platform_check_support_kernel_extended_ifa_flags (NM_PLATFORM_GET)) {
5865                 _LOGW (LOGD_IP6, "The kernel does not support extended IFA_FLAGS needed by NM for "
5866                                  "IPv6 private addresses. This feature is not available");
5867         }
5868
5869         if (!nm_setting_ip_config_get_may_fail (nm_connection_get_setting_ip6_config (connection)))
5870                 nm_device_add_pending_action (self, PENDING_ACTION_AUTOCONF6, TRUE);
5871
5872         /* ensure link local is ready... */
5873         ret = linklocal6_start (self);
5874         if (ret == NM_ACT_STAGE_RETURN_POSTPONE) {
5875                 /* success; wait for the LL address to show up */
5876                 return TRUE;
5877         }
5878
5879         /* success; already have the LL address; kick off router discovery */
5880         g_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS || ret == NM_ACT_STAGE_RETURN_FINISH);
5881         return addrconf6_start_with_link_ready (self);
5882 }
5883
5884 static void
5885 addrconf6_cleanup (NMDevice *self)
5886 {
5887         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
5888
5889         nm_clear_g_signal_handler (priv->rdisc, &priv->rdisc_changed_id);
5890         nm_clear_g_signal_handler (priv->rdisc, &priv->rdisc_timeout_id);
5891
5892         nm_device_remove_pending_action (self, PENDING_ACTION_AUTOCONF6, FALSE);
5893
5894         g_clear_object (&priv->ac_ip6_config);
5895         g_clear_object (&priv->rdisc);
5896 }
5897
5898 /******************************************/
5899
5900 static const char *ip6_properties_to_save[] = {
5901         "accept_ra",
5902         "accept_ra_defrtr",
5903         "accept_ra_pinfo",
5904         "accept_ra_rtr_pref",
5905         "disable_ipv6",
5906         "hop_limit",
5907         "use_tempaddr",
5908 };
5909
5910 static void
5911 save_ip6_properties (NMDevice *self)
5912 {
5913         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
5914         const char *ifname = nm_device_get_ip_iface (self);
5915         char *value;
5916         int i;
5917
5918         g_hash_table_remove_all (priv->ip6_saved_properties);
5919
5920         for (i = 0; i < G_N_ELEMENTS (ip6_properties_to_save); i++) {
5921                 value = nm_platform_sysctl_get (NM_PLATFORM_GET, nm_utils_ip6_property_path (ifname, ip6_properties_to_save[i]));
5922                 if (value) {
5923                         g_hash_table_insert (priv->ip6_saved_properties,
5924                                              (char *) ip6_properties_to_save[i],
5925                                              value);
5926                 }
5927         }
5928 }
5929
5930 static void
5931 restore_ip6_properties (NMDevice *self)
5932 {
5933         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
5934         GHashTableIter iter;
5935         gpointer key, value;
5936
5937         g_hash_table_iter_init (&iter, priv->ip6_saved_properties);
5938         while (g_hash_table_iter_next (&iter, &key, &value)) {
5939                 /* Don't touch "disable_ipv6" if we're doing userland IPv6LL */
5940                 if (priv->nm_ipv6ll && strcmp (key, "disable_ipv6") == 0)
5941                         continue;
5942                 nm_device_ipv6_sysctl_set (self, key, value);
5943         }
5944 }
5945
5946 static inline void
5947 set_disable_ipv6 (NMDevice *self, const char *value)
5948 {
5949         /* We only touch disable_ipv6 when NM is not managing the IPv6LL address */
5950         if (NM_DEVICE_GET_PRIVATE (self)->nm_ipv6ll == FALSE)
5951                 nm_device_ipv6_sysctl_set (self, "disable_ipv6", value);
5952 }
5953
5954 static inline void
5955 set_nm_ipv6ll (NMDevice *self, gboolean enable)
5956 {
5957         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
5958         int ifindex = nm_device_get_ip_ifindex (self);
5959         char *value;
5960
5961         if (!nm_platform_check_support_user_ipv6ll (NM_PLATFORM_GET))
5962                 return;
5963
5964         priv->nm_ipv6ll = enable;
5965         if (ifindex > 0) {
5966                 const char *detail = enable ? "enable" : "disable";
5967
5968                 _LOGD (LOGD_IP6, "will %s userland IPv6LL", detail);
5969                 if (!nm_platform_link_set_user_ipv6ll_enabled (NM_PLATFORM_GET, ifindex, enable))
5970                         _LOGW (LOGD_IP6, "failed to %s userspace IPv6LL address handling", detail);
5971
5972                 if (enable) {
5973                         /* Bounce IPv6 to ensure the kernel stops IPv6LL address generation */
5974                         value = nm_platform_sysctl_get (NM_PLATFORM_GET,
5975                                                         nm_utils_ip6_property_path (nm_device_get_ip_iface (self), "disable_ipv6"));
5976                         if (g_strcmp0 (value, "0") == 0)
5977                                 nm_device_ipv6_sysctl_set (self, "disable_ipv6", "1");
5978                         g_free (value);
5979
5980                         /* Ensure IPv6 is enabled */
5981                         nm_device_ipv6_sysctl_set (self, "disable_ipv6", "0");
5982                 }
5983
5984         }
5985 }
5986
5987 /************************************************************************/
5988
5989 static NMSettingIP6ConfigPrivacy
5990 _ip6_privacy_clamp (NMSettingIP6ConfigPrivacy use_tempaddr)
5991 {
5992         switch (use_tempaddr) {
5993         case NM_SETTING_IP6_CONFIG_PRIVACY_DISABLED:
5994         case NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_TEMP_ADDR:
5995         case NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_PUBLIC_ADDR:
5996                 return use_tempaddr;
5997         default:
5998                 return NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN;
5999         }
6000 }
6001
6002 static NMSettingIP6ConfigPrivacy
6003 _ip6_privacy_get (NMDevice *self)
6004 {
6005         NMSettingIP6ConfigPrivacy ip6_privacy;
6006         gs_free char *value = NULL;
6007         NMConnection *connection;
6008
6009         g_return_val_if_fail (self, NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN);
6010
6011         /* 1.) First look at the per-connection setting. If it is not -1 (unknown),
6012          * use it. */
6013         connection = nm_device_get_applied_connection (self);
6014         if (connection) {
6015                 NMSettingIPConfig *s_ip6 = nm_connection_get_setting_ip6_config (connection);
6016
6017                 if (s_ip6) {
6018                         ip6_privacy = nm_setting_ip6_config_get_ip6_privacy (NM_SETTING_IP6_CONFIG (s_ip6));
6019                         ip6_privacy = _ip6_privacy_clamp (ip6_privacy);
6020                         if (ip6_privacy != NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN)
6021                                 return ip6_privacy;
6022                 }
6023         }
6024
6025         value = nm_config_data_get_connection_default (NM_CONFIG_GET_DATA,
6026                                                        "ipv6.ip6-privacy", self);
6027
6028         /* 2.) use the default value from the configuration. */
6029         ip6_privacy = _nm_utils_ascii_str_to_int64 (value, 10,
6030                                                     NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN,
6031                                                     NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_TEMP_ADDR,
6032                                                     NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN);
6033         if (ip6_privacy != NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN)
6034                 return ip6_privacy;
6035
6036         /* 3.) No valid default-value configured. Fallback to reading sysctl.
6037          *
6038          * Instead of reading static config files in /etc, just read the current sysctl value.
6039          * This works as NM only writes to "/proc/sys/net/ipv6/conf/IFNAME/use_tempaddr", but leaves
6040          * the "default" entry untouched. */
6041         ip6_privacy = nm_platform_sysctl_get_int32 (NM_PLATFORM_GET, "/proc/sys/net/ipv6/conf/default/use_tempaddr", NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN);
6042         return _ip6_privacy_clamp (ip6_privacy);
6043 }
6044
6045 /****************************************************************/
6046
6047 static gboolean
6048 ip6_requires_slaves (NMConnection *connection)
6049 {
6050         const char *method;
6051
6052         method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG);
6053
6054         /* SLAAC, DHCP, and Link-Local depend on connectivity (and thus slaves)
6055          * to complete addressing.  SLAAC and DHCP obviously need a peer to
6056          * provide a prefix, while Link-Local must perform DAD on the local link.
6057          */
6058         return    strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_AUTO) == 0
6059                || strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_DHCP) == 0
6060                || strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL) == 0;
6061 }
6062
6063 static NMActStageReturn
6064 act_stage3_ip6_config_start (NMDevice *self,
6065                              NMIP6Config **out_config,
6066                              NMDeviceStateReason *reason)
6067 {
6068         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
6069         NMActStageReturn ret = NM_ACT_STAGE_RETURN_FAILURE;
6070         NMConnection *connection;
6071         const char *method;
6072         NMSettingIP6ConfigPrivacy ip6_privacy = NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN;
6073         const char *ip6_privacy_str = "0\n";
6074         GSList *slaves;
6075         gboolean ready_slaves;
6076
6077         g_return_val_if_fail (reason != NULL, NM_ACT_STAGE_RETURN_FAILURE);
6078
6079         connection = nm_device_get_applied_connection (self);
6080         g_assert (connection);
6081
6082         if (   connection_ip6_method_requires_carrier (connection, NULL)
6083             && priv->is_master
6084             && !priv->carrier) {
6085                 _LOGI (LOGD_IP6 | LOGD_DEVICE,
6086                        "IPv6 config waiting until carrier is on");
6087                 return NM_ACT_STAGE_RETURN_WAIT;
6088         }
6089
6090         if (priv->is_master && ip6_requires_slaves (connection)) {
6091                 /* If the master has no ready slaves, and depends on slaves for
6092                  * a successful IPv6 attempt, then postpone IPv6 addressing.
6093                  */
6094                 slaves = nm_device_master_get_slaves (self);
6095                 ready_slaves = NM_DEVICE_GET_CLASS (self)->have_any_ready_slaves (self, slaves);
6096                 g_slist_free (slaves);
6097
6098                 if (ready_slaves == FALSE) {
6099                         _LOGI (LOGD_DEVICE | LOGD_IP6,
6100                                "IPv6 config waiting until slaves are ready");
6101                         return NM_ACT_STAGE_RETURN_WAIT;
6102                 }
6103         }
6104
6105         priv->dhcp6_mode = NM_RDISC_DHCP_LEVEL_NONE;
6106
6107         method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG);
6108
6109         if (strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_IGNORE) == 0) {
6110                 if (!priv->master) {
6111                         gboolean old_nm_ipv6ll = priv->nm_ipv6ll;
6112
6113                         /* When activating an IPv6 'ignore' connection we need to revert back
6114                          * to kernel IPv6LL, but the kernel won't actually assign an address
6115                          * to the interface until disable_ipv6 is bounced.
6116                          */
6117                         set_nm_ipv6ll (self, FALSE);
6118                         if (old_nm_ipv6ll == TRUE)
6119                                 nm_device_ipv6_sysctl_set (self, "disable_ipv6", "1");
6120                         restore_ip6_properties (self);
6121                 }
6122                 return NM_ACT_STAGE_RETURN_STOP;
6123         }
6124
6125         /* Ensure the MTU makes sense. If it was below 1280 the kernel would not
6126          * expose any ipv6 sysctls or allow presence of any addresses on the interface,
6127          * including LL, which * would make it impossible to autoconfigure MTU to a
6128          * correct value. */
6129         if (!nm_device_uses_assumed_connection (self))
6130                 nm_device_ipv6_set_mtu (self, priv->ip6_mtu);
6131
6132         /* Any method past this point requires an IPv6LL address. Use NM-controlled
6133          * IPv6LL if this is not an assumed connection, since assumed connections
6134          * will already have IPv6 set up.
6135          */
6136         if (!nm_device_uses_assumed_connection (self))
6137                 set_nm_ipv6ll (self, TRUE);
6138
6139         /* Re-enable IPv6 on the interface */
6140         set_disable_ipv6 (self, "0");
6141
6142         ip6_privacy = _ip6_privacy_get (self);
6143
6144         if (strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_AUTO) == 0) {
6145                 if (!addrconf6_start (self, ip6_privacy)) {
6146                         /* IPv6 might be disabled; allow IPv4 to proceed */
6147                         ret = NM_ACT_STAGE_RETURN_STOP;
6148                 } else
6149                         ret = NM_ACT_STAGE_RETURN_POSTPONE;
6150         } else if (strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL) == 0) {
6151                 ret = linklocal6_start (self);
6152         } else if (strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_DHCP) == 0) {
6153                 priv->dhcp6_mode = NM_RDISC_DHCP_LEVEL_MANAGED;
6154                 if (!dhcp6_start (self, TRUE, reason)) {
6155                         /* IPv6 might be disabled; allow IPv4 to proceed */
6156                         ret = NM_ACT_STAGE_RETURN_STOP;
6157                 } else
6158                         ret = NM_ACT_STAGE_RETURN_POSTPONE;
6159         } else if (strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_MANUAL) == 0) {
6160                 /* New blank config */
6161                 *out_config = nm_ip6_config_new (nm_device_get_ip_ifindex (self));
6162                 g_assert (*out_config);
6163
6164                 ret = NM_ACT_STAGE_RETURN_SUCCESS;
6165         } else
6166                 _LOGW (LOGD_IP6, "unhandled IPv6 config method '%s'; will fail", method);
6167
6168         /* Other methods (shared) aren't implemented yet */
6169
6170         switch (ip6_privacy) {
6171         case NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN:
6172         case NM_SETTING_IP6_CONFIG_PRIVACY_DISABLED:
6173                 ip6_privacy_str = "0";
6174         break;
6175         case NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_PUBLIC_ADDR:
6176                 ip6_privacy_str = "1";
6177         break;
6178         case NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_TEMP_ADDR:
6179                 ip6_privacy_str = "2";
6180         break;
6181         }
6182         nm_device_ipv6_sysctl_set (self, "use_tempaddr", ip6_privacy_str);
6183
6184         return ret;
6185 }
6186
6187 /**
6188  * nm_device_activate_stage3_ip4_start:
6189  * @self: the device
6190  *
6191  * Try starting IPv4 configuration.
6192  */
6193 gboolean
6194 nm_device_activate_stage3_ip4_start (NMDevice *self)
6195 {
6196         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
6197         NMActStageReturn ret;
6198         NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE;
6199         NMIP4Config *ip4_config = NULL;
6200
6201         g_assert (priv->ip4_state == IP_WAIT);
6202
6203         priv->ip4_state = IP_CONF;
6204         ret = NM_DEVICE_GET_CLASS (self)->act_stage3_ip4_config_start (self, &ip4_config, &reason);
6205         if (ret == NM_ACT_STAGE_RETURN_SUCCESS) {
6206                 g_assert (ip4_config);
6207                 nm_device_activate_schedule_ip4_config_result (self, ip4_config);
6208                 g_object_unref (ip4_config);
6209         } else if (ret == NM_ACT_STAGE_RETURN_FAILURE) {
6210                 nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason);
6211                 return FALSE;
6212         } else if (ret == NM_ACT_STAGE_RETURN_STOP) {
6213                 /* Early finish */
6214                 priv->ip4_state = IP_FAIL;
6215         } else if (ret == NM_ACT_STAGE_RETURN_WAIT) {
6216                 /* Wait for something to try IP config again */
6217                 priv->ip4_state = IP_WAIT;
6218         } else
6219                 g_assert (ret == NM_ACT_STAGE_RETURN_POSTPONE);
6220
6221         return TRUE;
6222 }
6223
6224 /**
6225  * nm_device_activate_stage3_ip6_start:
6226  * @self: the device
6227  *
6228  * Try starting IPv6 configuration.
6229  */
6230 gboolean
6231 nm_device_activate_stage3_ip6_start (NMDevice *self)
6232 {
6233         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
6234         NMActStageReturn ret;
6235         NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE;
6236         NMIP6Config *ip6_config = NULL;
6237
6238         g_assert (priv->ip6_state == IP_WAIT);
6239
6240         priv->ip6_state = IP_CONF;
6241         ret = NM_DEVICE_GET_CLASS (self)->act_stage3_ip6_config_start (self, &ip6_config, &reason);
6242         if (ret == NM_ACT_STAGE_RETURN_SUCCESS) {
6243                 g_assert (ip6_config);
6244                 /* Here we get a static IPv6 config, like for Shared where it's
6245                  * autogenerated or from modems where it comes from ModemManager.
6246                  */
6247                 g_warn_if_fail (priv->ac_ip6_config == NULL);
6248                 priv->ac_ip6_config = ip6_config;
6249                 nm_device_activate_schedule_ip6_config_result (self);
6250         } else if (ret == NM_ACT_STAGE_RETURN_FAILURE) {
6251                 nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason);
6252                 return FALSE;
6253         } else if (ret == NM_ACT_STAGE_RETURN_STOP) {
6254                 /* Activation not wanted */
6255                 priv->ip6_state = IP_FAIL;
6256         } else if (ret == NM_ACT_STAGE_RETURN_FINISH) {
6257                 /* Early finish, nothing more to do */
6258                 priv->ip6_state = IP_DONE;
6259                 check_ip_done (self);
6260         } else if (ret == NM_ACT_STAGE_RETURN_WAIT) {
6261                 /* Wait for something to try IP config again */
6262                 priv->ip6_state = IP_WAIT;
6263         } else
6264                 g_assert (ret == NM_ACT_STAGE_RETURN_POSTPONE);
6265
6266         return TRUE;
6267 }
6268
6269 /*
6270  * activate_stage3_ip_config_start
6271  *
6272  * Begin automatic/manual IP configuration
6273  *
6274  */
6275 static void
6276 activate_stage3_ip_config_start (NMDevice *self)
6277 {
6278         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
6279         NMActiveConnection *master;
6280         NMDevice *master_device;
6281
6282         priv->ip4_state = priv->ip6_state = IP_WAIT;
6283
6284         nm_device_state_changed (self, NM_DEVICE_STATE_IP_CONFIG, NM_DEVICE_STATE_REASON_NONE);
6285
6286         /* Device should be up before we can do anything with it */
6287         if (!nm_platform_link_is_up (NM_PLATFORM_GET, nm_device_get_ip_ifindex (self)))
6288                 _LOGW (LOGD_DEVICE, "interface %s not up for IP configuration", nm_device_get_ip_iface (self));
6289
6290         /* If the device is a slave, then we don't do any IP configuration but we
6291          * use the IP config stage to indicate to the master we're ready for
6292          * enslavement.  If the master is already activating, it will have tried to
6293          * enslave us when we changed state to IP_CONFIG, causing us to queue a
6294          * transition to SECONDARIES (or FAILED if the enslavement failed), with
6295          * our IP states set to IP_DONE either way.  If the master isn't yet
6296          * activating, then they'll still be in IP_WAIT.  Either way, we bail out
6297          * of IP config here.
6298          */
6299         master = nm_active_connection_get_master (NM_ACTIVE_CONNECTION (priv->act_request));
6300         if (master) {
6301                 master_device = nm_active_connection_get_device (master);
6302                 if (priv->ip4_state == IP_WAIT && priv->ip6_state == IP_WAIT) {
6303                         _LOGI (LOGD_DEVICE, "Activation: connection '%s' waiting on master '%s'",
6304                                nm_connection_get_id (nm_device_get_applied_connection (self)),
6305                                master_device ? nm_device_get_iface (master_device) : "(unknown)");
6306                 }
6307                 return;
6308         }
6309
6310         /* IPv4 */
6311         if (   nm_device_activate_ip4_state_in_wait (self)
6312             && !nm_device_activate_stage3_ip4_start (self))
6313                 return;
6314
6315         /* IPv6 */
6316         if (   nm_device_activate_ip6_state_in_wait (self)
6317             && !nm_device_activate_stage3_ip6_start (self))
6318                 return;
6319
6320         check_ip_failed (self, TRUE);
6321 }
6322
6323 static gboolean
6324 fw_change_zone_handle (NMDevice *self,
6325                        NMFirewallManagerCallId call_id,
6326                        GError *error)
6327 {
6328         NMDevicePrivate *priv;
6329
6330         g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
6331
6332         priv = NM_DEVICE_GET_PRIVATE (self);
6333
6334         g_return_val_if_fail (priv->fw_call == call_id, FALSE);
6335         priv->fw_call = NULL;
6336
6337         return !nm_utils_error_is_cancelled (error, FALSE);
6338 }
6339
6340 static void
6341 fw_change_zone_cb_stage2 (NMFirewallManager *firewall_manager,
6342                           NMFirewallManagerCallId call_id,
6343                           GError *error,
6344                           gpointer user_data)
6345 {
6346         NMDevice *self = user_data;
6347         NMDevicePrivate *priv;
6348
6349         if (!fw_change_zone_handle (self, call_id, error))
6350                 return;
6351
6352         /* FIXME: fail the device on error? */
6353
6354         priv = NM_DEVICE_GET_PRIVATE (self);
6355         priv->fw_ready = TRUE;
6356
6357         nm_device_activate_schedule_stage3_ip_config_start (self);
6358 }
6359
6360 static void
6361 fw_change_zone_cb_ip_check (NMFirewallManager *firewall_manager,
6362                             NMFirewallManagerCallId call_id,
6363                             GError *error,
6364                             gpointer user_data)
6365 {
6366         NMDevice *self = user_data;
6367
6368         if (!fw_change_zone_handle (self, call_id, error))
6369                 return;
6370
6371         /* FIXME: fail the device on error? */
6372         nm_device_start_ip_check (self);
6373 }
6374
6375 /*
6376  * nm_device_activate_schedule_stage3_ip_config_start
6377  *
6378  * Schedule IP configuration start
6379  */
6380 void
6381 nm_device_activate_schedule_stage3_ip_config_start (NMDevice *self)
6382 {
6383         NMDevicePrivate *priv;
6384         NMConnection *connection;
6385         NMSettingConnection *s_con = NULL;
6386         const char *zone;
6387
6388         g_return_if_fail (NM_IS_DEVICE (self));
6389
6390         priv = NM_DEVICE_GET_PRIVATE (self);
6391         g_return_if_fail (priv->act_request);
6392
6393         /* Add the interface to the specified firewall zone */
6394         connection = nm_device_get_applied_connection (self);
6395         g_assert (connection);
6396         s_con = nm_connection_get_setting_connection (connection);
6397
6398         if (!priv->fw_ready) {
6399                 if (nm_device_uses_assumed_connection (self))
6400                         priv->fw_ready = TRUE;
6401                 else {
6402                         if (!priv->fw_call) {
6403                                 zone = nm_setting_connection_get_zone (s_con);
6404
6405                                 _LOGD (LOGD_DEVICE, "Activation: setting firewall zone '%s'", zone ? zone : "default");
6406                                 priv->fw_call = nm_firewall_manager_add_or_change_zone (nm_firewall_manager_get (),
6407                                                                                         nm_device_get_ip_iface (self),
6408                                                                                         zone,
6409                                                                                         FALSE,
6410                                                                                         fw_change_zone_cb_stage2,
6411                                                                                         self);
6412                         }
6413                         return;
6414                 }
6415         }
6416
6417         activation_source_schedule (self, activate_stage3_ip_config_start, AF_INET);
6418 }
6419
6420 static NMActStageReturn
6421 act_stage4_ip4_config_timeout (NMDevice *self, NMDeviceStateReason *reason)
6422 {
6423         if (!get_ip_config_may_fail (self, AF_INET)) {
6424                 *reason = NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE;
6425                 return NM_ACT_STAGE_RETURN_FAILURE;
6426         }
6427         return NM_ACT_STAGE_RETURN_SUCCESS;
6428 }
6429
6430
6431 /*
6432  * nm_device_activate_stage4_ip4_config_timeout
6433  *
6434  * Time out on retrieving the IPv4 config.
6435  *
6436  */
6437 static void
6438 activate_stage4_ip4_config_timeout (NMDevice *self)
6439 {
6440         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
6441         NMActStageReturn ret = NM_ACT_STAGE_RETURN_FAILURE;
6442         NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE;
6443
6444         ret = NM_DEVICE_GET_CLASS (self)->act_stage4_ip4_config_timeout (self, &reason);
6445         if (ret == NM_ACT_STAGE_RETURN_POSTPONE)
6446                 return;
6447         else if (ret == NM_ACT_STAGE_RETURN_FAILURE) {
6448                 nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason);
6449                 return;
6450         }
6451         g_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS);
6452
6453         priv->ip4_state = IP_FAIL;
6454
6455         check_ip_failed (self, FALSE);
6456 }
6457
6458
6459 /*
6460  * nm_device_activate_schedule_ip4_config_timeout
6461  *
6462  * Deal with a timeout of the IPv4 configuration
6463  *
6464  */
6465 void
6466 nm_device_activate_schedule_ip4_config_timeout (NMDevice *self)
6467 {
6468         NMDevicePrivate *priv;
6469
6470         g_return_if_fail (NM_IS_DEVICE (self));
6471
6472         priv = NM_DEVICE_GET_PRIVATE (self);
6473         g_return_if_fail (priv->act_request);
6474
6475         activation_source_schedule (self, activate_stage4_ip4_config_timeout, AF_INET);
6476 }
6477
6478
6479 static NMActStageReturn
6480 act_stage4_ip6_config_timeout (NMDevice *self, NMDeviceStateReason *reason)
6481 {
6482         if (!get_ip_config_may_fail (self, AF_INET6)) {
6483                 *reason = NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE;
6484                 return NM_ACT_STAGE_RETURN_FAILURE;
6485         }
6486
6487         return NM_ACT_STAGE_RETURN_SUCCESS;
6488 }
6489
6490
6491 /*
6492  * activate_stage4_ip6_config_timeout
6493  *
6494  * Time out on retrieving the IPv6 config.
6495  *
6496  */
6497 static void
6498 activate_stage4_ip6_config_timeout (NMDevice *self)
6499 {
6500         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
6501         NMActStageReturn ret = NM_ACT_STAGE_RETURN_FAILURE;
6502         NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE;
6503
6504         ret = NM_DEVICE_GET_CLASS (self)->act_stage4_ip6_config_timeout (self, &reason);
6505         if (ret == NM_ACT_STAGE_RETURN_POSTPONE)
6506                 return;
6507         if (ret == NM_ACT_STAGE_RETURN_FAILURE) {
6508                 nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason);
6509                 return;
6510         }
6511         g_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS);
6512
6513         priv->ip6_state = IP_FAIL;
6514
6515         check_ip_failed (self, FALSE);
6516 }
6517
6518
6519 /*
6520  * nm_device_activate_schedule_ip6_config_timeout
6521  *
6522  * Deal with a timeout of the IPv6 configuration
6523  *
6524  */
6525 void
6526 nm_device_activate_schedule_ip6_config_timeout (NMDevice *self)
6527 {
6528         NMDevicePrivate *priv;
6529
6530         g_return_if_fail (NM_IS_DEVICE (self));
6531
6532         priv = NM_DEVICE_GET_PRIVATE (self);
6533         g_return_if_fail (priv->act_request);
6534
6535         activation_source_schedule (self, activate_stage4_ip6_config_timeout, AF_INET6);
6536 }
6537
6538 static gboolean
6539 share_init (void)
6540 {
6541         char *modules[] = { "ip_tables", "iptable_nat", "nf_nat_ftp", "nf_nat_irc",
6542                             "nf_nat_sip", "nf_nat_tftp", "nf_nat_pptp", "nf_nat_h323",
6543                             NULL };
6544         char **iter;
6545         int errsv;
6546
6547         if (!nm_platform_sysctl_set (NM_PLATFORM_GET, "/proc/sys/net/ipv4/ip_forward", "1")) {
6548                 errsv = errno;
6549                 nm_log_err (LOGD_SHARING, "share: error starting IP forwarding: (%d) %s",
6550                             errsv, strerror (errsv));
6551                 return FALSE;
6552         }
6553
6554         if (!nm_platform_sysctl_set (NM_PLATFORM_GET, "/proc/sys/net/ipv4/ip_dynaddr", "1")) {
6555                 errsv = errno;
6556                 nm_log_err (LOGD_SHARING, "share: error starting IP forwarding: (%d) %s",
6557                             errsv, strerror (errsv));
6558         }
6559
6560         for (iter = modules; *iter; iter++)
6561                 nm_utils_modprobe (NULL, FALSE, *iter, NULL);
6562
6563         return TRUE;
6564 }
6565
6566 static void
6567 add_share_rule (NMActRequest *req, const char *table, const char *fmt, ...)
6568 {
6569         va_list args;
6570         char *cmd;
6571
6572         va_start (args, fmt);
6573         cmd = g_strdup_vprintf (fmt, args);
6574         va_end (args);
6575
6576         nm_act_request_add_share_rule (req, table, cmd);
6577         g_free (cmd);
6578 }
6579
6580 static gboolean
6581 start_sharing (NMDevice *self, NMIP4Config *config)
6582 {
6583         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
6584         NMActRequest *req;
6585         GError *error = NULL;
6586         char str_addr[INET_ADDRSTRLEN + 1];
6587         char str_mask[INET_ADDRSTRLEN + 1];
6588         guint32 netmask, network;
6589         const NMPlatformIP4Address *ip4_addr;
6590         const char *ip_iface;
6591
6592         g_return_val_if_fail (config != NULL, FALSE);
6593
6594         ip_iface = nm_device_get_ip_iface (self);
6595
6596         ip4_addr = nm_ip4_config_get_address (config, 0);
6597         if (!ip4_addr || !ip4_addr->address)
6598                 return FALSE;
6599
6600         netmask = nm_utils_ip4_prefix_to_netmask (ip4_addr->plen);
6601         if (!inet_ntop (AF_INET, &netmask, str_mask, sizeof (str_mask)))
6602                 return FALSE;
6603
6604         network = ip4_addr->address & netmask;
6605         if (!inet_ntop (AF_INET, &network, str_addr, sizeof (str_addr)))
6606                 return FALSE;
6607
6608         if (!share_init ())
6609                 return FALSE;
6610
6611         req = nm_device_get_act_request (self);
6612         g_assert (req);
6613
6614         add_share_rule (req, "nat", "POSTROUTING --source %s/%s ! --destination %s/%s --jump MASQUERADE", str_addr, str_mask, str_addr, str_mask);
6615         add_share_rule (req, "filter", "FORWARD --destination %s/%s --out-interface %s --match state --state ESTABLISHED,RELATED --jump ACCEPT", str_addr, str_mask, ip_iface);
6616         add_share_rule (req, "filter", "FORWARD --source %s/%s --in-interface %s --jump ACCEPT", str_addr, str_mask, ip_iface);
6617         add_share_rule (req, "filter", "FORWARD --in-interface %s --out-interface %s --jump ACCEPT", ip_iface, ip_iface);
6618         add_share_rule (req, "filter", "FORWARD --out-interface %s --jump REJECT", ip_iface);
6619         add_share_rule (req, "filter", "FORWARD --in-interface %s --jump REJECT", ip_iface);
6620         add_share_rule (req, "filter", "INPUT --in-interface %s --protocol udp --destination-port 67 --jump ACCEPT", ip_iface);
6621         add_share_rule (req, "filter", "INPUT --in-interface %s --protocol tcp --destination-port 67 --jump ACCEPT", ip_iface);
6622         add_share_rule (req, "filter", "INPUT --in-interface %s --protocol udp --destination-port 53 --jump ACCEPT", ip_iface);
6623         add_share_rule (req, "filter", "INPUT --in-interface %s --protocol tcp --destination-port 53 --jump ACCEPT", ip_iface);
6624
6625         nm_act_request_set_shared (req, TRUE);
6626
6627         if (!nm_dnsmasq_manager_start (priv->dnsmasq_manager, config, &error)) {
6628                 _LOGE (LOGD_SHARING, "share: (%s) failed to start dnsmasq: %s",
6629                        ip_iface, error->message);
6630                 g_error_free (error);
6631                 nm_act_request_set_shared (req, FALSE);
6632                 return FALSE;
6633         }
6634
6635         priv->dnsmasq_state_id = g_signal_connect (priv->dnsmasq_manager, NM_DNS_MASQ_MANAGER_STATE_CHANGED,
6636                                                    G_CALLBACK (dnsmasq_state_changed_cb),
6637                                                    self);
6638         return TRUE;
6639 }
6640
6641 static void
6642 arp_cleanup (NMDevice *self)
6643 {
6644         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
6645
6646         if (priv->arping.announcing) {
6647                 nm_arping_manager_destroy (priv->arping.announcing);
6648                 priv->arping.announcing = NULL;
6649         }
6650 }
6651
6652 static void
6653 arp_announce (NMDevice *self)
6654 {
6655         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
6656         NMConnection *connection;
6657         NMSettingIPConfig *s_ip4;
6658         guint num, i;
6659         const guint8 *hw_addr;
6660         size_t hw_addr_len = 0;
6661
6662         arp_cleanup (self);
6663
6664         hw_addr = nm_platform_link_get_address (NM_PLATFORM_GET,
6665                                                 nm_device_get_ip_ifindex (self),
6666                                                 &hw_addr_len);
6667
6668         if (!hw_addr_len || !hw_addr)
6669                 return;
6670
6671         /* We only care about manually-configured addresses; DHCP- and autoip-configured
6672          * ones should already have been seen on the network at this point.
6673          */
6674         connection = nm_device_get_applied_connection (self);
6675         if (!connection)
6676                 return;
6677         s_ip4 = nm_connection_get_setting_ip4_config (connection);
6678         if (!s_ip4)
6679                 return;
6680         num = nm_setting_ip_config_get_num_addresses (s_ip4);
6681         if (num == 0)
6682                 return;
6683
6684         priv->arping.announcing = nm_arping_manager_new (nm_device_get_ip_ifindex (self));
6685
6686         for (i = 0; i < num; i++) {
6687                 NMIPAddress *ip = nm_setting_ip_config_get_address (s_ip4, i);
6688                 in_addr_t addr;
6689
6690                 if (inet_pton (AF_INET, nm_ip_address_get_address (ip), &addr) == 1)
6691                         nm_arping_manager_add_address (priv->arping.announcing, addr);
6692                 else
6693                         g_warn_if_reached ();
6694         }
6695
6696         nm_arping_manager_announce_addresses (priv->arping.announcing);
6697 }
6698
6699 static void
6700 activate_stage5_ip4_config_commit (NMDevice *self)
6701 {
6702         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
6703         NMActRequest *req;
6704         const char *method;
6705         NMConnection *connection;
6706         NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE;
6707         int ip_ifindex;
6708
6709         req = nm_device_get_act_request (self);
6710         g_assert (req);
6711         connection = nm_act_request_get_applied_connection (req);
6712         g_assert (connection);
6713
6714         /* Interface must be IFF_UP before IP config can be applied */
6715         ip_ifindex = nm_device_get_ip_ifindex (self);
6716         if (!nm_platform_link_is_up (NM_PLATFORM_GET, ip_ifindex) && !nm_device_uses_assumed_connection (self)) {
6717                 nm_platform_link_set_up (NM_PLATFORM_GET, ip_ifindex, NULL);
6718                 if (!nm_platform_link_is_up (NM_PLATFORM_GET, ip_ifindex))
6719                         _LOGW (LOGD_DEVICE, "interface %s not up for IP configuration", nm_device_get_ip_iface (self));
6720         }
6721
6722         /* NULL to use the existing priv->dev_ip4_config */
6723         if (!ip4_config_merge_and_apply (self, NULL, TRUE, &reason)) {
6724                 _LOGD (LOGD_DEVICE | LOGD_IP4, "Activation: Stage 5 of 5 (IPv4 Commit) failed");
6725                 nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason);
6726                 return;
6727         }
6728
6729         /* Start IPv4 sharing if we need it */
6730         method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG);
6731
6732         if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_SHARED) == 0) {
6733                 if (!start_sharing (self, priv->ip4_config)) {
6734                         _LOGW (LOGD_SHARING, "Activation: Stage 5 of 5 (IPv4 Commit) start sharing failed.");
6735                         nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_SHARED_START_FAILED);
6736                         return;
6737                 }
6738         }
6739
6740         /* If IPv4 wasn't the first to complete, and DHCP was used, then ensure
6741          * dispatcher scripts get the DHCP lease information.
6742          */
6743         if (   priv->dhcp4_client
6744             && nm_device_activate_ip4_state_in_conf (self)
6745             && (nm_device_get_state (self) > NM_DEVICE_STATE_IP_CONFIG)) {
6746                 /* Notify dispatcher scripts of new DHCP4 config */
6747                 nm_dispatcher_call (DISPATCHER_ACTION_DHCP4_CHANGE,
6748                                     nm_device_get_settings_connection (self),
6749                                     nm_device_get_applied_connection (self),
6750                                     self,
6751                                     NULL,
6752                                     NULL,
6753                                     NULL);
6754         }
6755
6756         arp_announce (self);
6757
6758         nm_device_remove_pending_action (self, PENDING_ACTION_DHCP4, FALSE);
6759
6760         /* Enter the IP_CHECK state if this is the first method to complete */
6761         priv->ip4_state = IP_DONE;
6762         check_ip_done (self);
6763 }
6764
6765 static void
6766 queued_ip4_config_change_clear (NMDevice *self)
6767 {
6768         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
6769
6770         if (priv->queued_ip4_config_id) {
6771                 _LOGD (LOGD_DEVICE, "clearing queued IP4 config change");
6772                 g_source_remove (priv->queued_ip4_config_id);
6773                 priv->queued_ip4_config_id = 0;
6774         }
6775 }
6776
6777 static void
6778 queued_ip6_config_change_clear (NMDevice *self)
6779 {
6780         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
6781
6782         if (priv->queued_ip6_config_id) {
6783                 _LOGD (LOGD_DEVICE, "clearing queued IP6 config change");
6784                 g_source_remove (priv->queued_ip6_config_id);
6785                 priv->queued_ip6_config_id = 0;
6786         }
6787 }
6788
6789 void
6790 nm_device_activate_schedule_ip4_config_result (NMDevice *self, NMIP4Config *config)
6791 {
6792         NMDevicePrivate *priv;
6793
6794         g_return_if_fail (NM_IS_DEVICE (self));
6795         priv = NM_DEVICE_GET_PRIVATE (self);
6796
6797         g_clear_object (&priv->dev_ip4_config);
6798         if (config)
6799                 priv->dev_ip4_config = g_object_ref (config);
6800
6801         queued_ip4_config_change_clear (self);
6802         activation_source_schedule (self, activate_stage5_ip4_config_commit, AF_INET);
6803 }
6804
6805 gboolean
6806 nm_device_activate_ip4_state_in_conf (NMDevice *self)
6807 {
6808         g_return_val_if_fail (self != NULL, FALSE);
6809         return NM_DEVICE_GET_PRIVATE (self)->ip4_state == IP_CONF;
6810 }
6811
6812 gboolean
6813 nm_device_activate_ip4_state_in_wait (NMDevice *self)
6814 {
6815         g_return_val_if_fail (self != NULL, FALSE);
6816         return NM_DEVICE_GET_PRIVATE (self)->ip4_state == IP_WAIT;
6817 }
6818
6819 static void
6820 activate_stage5_ip6_config_commit (NMDevice *self)
6821 {
6822         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
6823         NMActRequest *req;
6824         NMConnection *connection;
6825         NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE;
6826         int ip_ifindex;
6827
6828         req = nm_device_get_act_request (self);
6829         g_assert (req);
6830         connection = nm_act_request_get_applied_connection (req);
6831         g_assert (connection);
6832
6833         /* Interface must be IFF_UP before IP config can be applied */
6834         ip_ifindex = nm_device_get_ip_ifindex (self);
6835         if (!nm_platform_link_is_up (NM_PLATFORM_GET, ip_ifindex) && !nm_device_uses_assumed_connection (self)) {
6836                 nm_platform_link_set_up (NM_PLATFORM_GET, ip_ifindex, NULL);
6837                 if (!nm_platform_link_is_up (NM_PLATFORM_GET, ip_ifindex))
6838                         _LOGW (LOGD_DEVICE, "interface %s not up for IP configuration", nm_device_get_ip_iface (self));
6839         }
6840
6841         if (ip6_config_merge_and_apply (self, TRUE, &reason)) {
6842                 if (   priv->dhcp6_mode != NM_RDISC_DHCP_LEVEL_NONE
6843                     && priv->ip6_state == IP_CONF) {
6844                         if (priv->dhcp6_ip6_config) {
6845                                 /* If IPv6 wasn't the first IP to complete, and DHCP was used,
6846                                  * then ensure dispatcher scripts get the DHCP lease information.
6847                                  */
6848                                 nm_dispatcher_call (DISPATCHER_ACTION_DHCP6_CHANGE,
6849                                                     nm_device_get_settings_connection (self),
6850                                                     nm_device_get_applied_connection (self),
6851                                                     self,
6852                                                     NULL,
6853                                                     NULL,
6854                                                     NULL);
6855                         } else {
6856                                 /* still waiting for first dhcp6 lease. */
6857                                 return;
6858                         }
6859                 }
6860
6861                 nm_device_remove_pending_action (self, PENDING_ACTION_DHCP6, FALSE);
6862                 nm_device_remove_pending_action (self, PENDING_ACTION_AUTOCONF6, FALSE);
6863
6864                 /* Enter the IP_CHECK state if this is the first method to complete */
6865                 priv->ip6_state = IP_DONE;
6866                 check_ip_done (self);
6867         } else {
6868                 _LOGW (LOGD_DEVICE | LOGD_IP6, "Activation: Stage 5 of 5 (IPv6 Commit) failed");
6869                 nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason);
6870         }
6871 }
6872
6873 void
6874 nm_device_activate_schedule_ip6_config_result (NMDevice *self)
6875 {
6876         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
6877
6878         g_return_if_fail (NM_IS_DEVICE (self));
6879
6880         /* If IP had previously failed, move it back to IP_CONF since we
6881          * clearly now have configuration.
6882          */
6883         if (priv->ip6_state == IP_FAIL)
6884                 priv->ip6_state = IP_CONF;
6885
6886         activation_source_schedule (self, activate_stage5_ip6_config_commit, AF_INET6);
6887 }
6888
6889 gboolean
6890 nm_device_activate_ip6_state_in_conf (NMDevice *self)
6891 {
6892         g_return_val_if_fail (self != NULL, FALSE);
6893         return NM_DEVICE_GET_PRIVATE (self)->ip6_state == IP_CONF;
6894 }
6895
6896 gboolean
6897 nm_device_activate_ip6_state_in_wait (NMDevice *self)
6898 {
6899         g_return_val_if_fail (self != NULL, FALSE);
6900         return NM_DEVICE_GET_PRIVATE (self)->ip6_state == IP_WAIT;
6901 }
6902
6903 static void
6904 clear_act_request (NMDevice *self)
6905 {
6906         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
6907
6908         if (!priv->act_request)
6909                 return;
6910
6911         nm_active_connection_set_default (NM_ACTIVE_CONNECTION (priv->act_request), FALSE);
6912
6913         priv->master_ready_handled = FALSE;
6914         nm_clear_g_signal_handler (priv->act_request, &priv->master_ready_id);
6915
6916         g_clear_object (&priv->act_request);
6917         _notify (self, PROP_ACTIVE_CONNECTION);
6918 }
6919
6920 static void
6921 dnsmasq_cleanup (NMDevice *self)
6922 {
6923         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
6924
6925         if (!priv->dnsmasq_manager)
6926                 return;
6927
6928         nm_clear_g_signal_handler (priv->dnsmasq_manager, &priv->dnsmasq_state_id);
6929
6930         nm_dnsmasq_manager_stop (priv->dnsmasq_manager);
6931         g_object_unref (priv->dnsmasq_manager);
6932         priv->dnsmasq_manager = NULL;
6933 }
6934
6935 static void
6936 _update_ip4_address (NMDevice *self)
6937 {
6938         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
6939         guint32 addr;
6940
6941         g_return_if_fail (NM_IS_DEVICE (self));
6942
6943         if (   priv->ip4_config
6944             && ip_config_valid (priv->state)
6945             && nm_ip4_config_get_num_addresses (priv->ip4_config)) {
6946                 addr = nm_ip4_config_get_address (priv->ip4_config, 0)->address;
6947                 if (addr != priv->ip4_address) {
6948                         priv->ip4_address = addr;
6949                         _notify (self, PROP_IP4_ADDRESS);
6950                 }
6951         }
6952 }
6953
6954 gboolean
6955 nm_device_get_is_nm_owned (NMDevice *self)
6956 {
6957         return NM_DEVICE_GET_PRIVATE (self)->is_nm_owned;
6958 }
6959
6960 /*
6961  * delete_on_deactivate_link_delete
6962  *
6963  * Function will be queued with g_idle_add to call
6964  * nm_platform_link_delete for the underlying resources
6965  * of the device.
6966  */
6967 static gboolean
6968 delete_on_deactivate_link_delete (gpointer user_data)
6969 {
6970         DeleteOnDeactivateData *data = user_data;
6971         NMDevice *self = data->device;
6972
6973         _LOGD (LOGD_DEVICE, "delete_on_deactivate: cleanup and delete virtual link #%d (id=%u)",
6974                data->ifindex, data->idle_add_id);
6975
6976         if (data->device) {
6977                 NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (data->device);
6978                 gs_free_error GError *error = NULL;
6979
6980                 g_object_remove_weak_pointer (G_OBJECT (data->device), (void **) &data->device);
6981                 priv->delete_on_deactivate_data = NULL;
6982
6983                 if (!nm_device_unrealize (data->device, TRUE, &error))
6984                         _LOGD (LOGD_DEVICE, "delete_on_deactivate: unrealizing %d failed (%s)", data->ifindex, error->message);
6985         } else
6986                 nm_platform_link_delete (NM_PLATFORM_GET, data->ifindex);
6987
6988         g_free (data);
6989         return FALSE;
6990 }
6991
6992 static void
6993 delete_on_deactivate_unschedule (NMDevice *self)
6994 {
6995         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
6996
6997         if (priv->delete_on_deactivate_data) {
6998                 DeleteOnDeactivateData *data = priv->delete_on_deactivate_data;
6999
7000                 priv->delete_on_deactivate_data = NULL;
7001
7002                 g_source_remove (data->idle_add_id);
7003                 g_object_remove_weak_pointer (G_OBJECT (self), (void **) &data->device);
7004                 _LOGD (LOGD_DEVICE, "delete_on_deactivate: cancel cleanup and delete virtual link #%d (id=%u)",
7005                        data->ifindex, data->idle_add_id);
7006                 g_free (data);
7007         }
7008 }
7009
7010 static void
7011 delete_on_deactivate_check_and_schedule (NMDevice *self, int ifindex)
7012 {
7013         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
7014         DeleteOnDeactivateData *data;
7015
7016         if (ifindex <= 0)
7017                 return;
7018         if (!priv->is_nm_owned)
7019                 return;
7020         if (priv->queued_act_request)
7021                 return;
7022         if (!nm_device_is_software (self) || !nm_device_is_real (self))
7023                 return;
7024         if (nm_device_get_state (self) == NM_DEVICE_STATE_UNMANAGED)
7025                 return;
7026         if (nm_device_get_state (self) == NM_DEVICE_STATE_UNAVAILABLE)
7027                 return;
7028         delete_on_deactivate_unschedule (self); /* always cancel and reschedule */
7029
7030         data = g_new (DeleteOnDeactivateData, 1);
7031         g_object_add_weak_pointer (G_OBJECT (self), (void **) &data->device);
7032         data->device = self;
7033         data->ifindex = ifindex;
7034         data->idle_add_id = g_idle_add (delete_on_deactivate_link_delete, data);
7035         priv->delete_on_deactivate_data = data;
7036
7037         _LOGD (LOGD_DEVICE, "delete_on_deactivate: schedule cleanup and delete virtual link #%d (id=%u)",
7038                ifindex, data->idle_add_id);
7039 }
7040
7041 static void
7042 _cleanup_ip4_pre (NMDevice *self, CleanupType cleanup_type)
7043 {
7044         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
7045
7046         priv->ip4_state =  IP_NONE;
7047         queued_ip4_config_change_clear (self);
7048
7049         dhcp4_cleanup (self, cleanup_type, FALSE);
7050         arp_cleanup (self);
7051         dnsmasq_cleanup (self);
7052         ipv4ll_cleanup (self);
7053 }
7054
7055 static void
7056 _cleanup_ip6_pre (NMDevice *self, CleanupType cleanup_type)
7057 {
7058         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
7059
7060         priv->ip6_state = IP_NONE;
7061         queued_ip6_config_change_clear (self);
7062
7063         dhcp6_cleanup (self, cleanup_type, FALSE);
7064         linklocal6_cleanup (self);
7065         addrconf6_cleanup (self);
7066 }
7067
7068 static gboolean
7069 _hash_check_invalid_keys_impl (GHashTable *hash, const char *setting_name, GError **error, const char **argv)
7070 {
7071         guint found_keys = 0;
7072         guint i;
7073
7074         nm_assert (argv && argv[0]);
7075
7076 #if NM_MORE_ASSERTS > 10
7077         /* Assert that the keys are unique. */
7078         {
7079                 gs_unref_hashtable GHashTable *check_dups = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, NULL);
7080
7081                 for (i = 0; argv[i]; i++) {
7082                         if (!g_hash_table_add (check_dups, (char *) argv[i]))
7083                                 nm_assert (FALSE);
7084                 }
7085                 nm_assert (g_hash_table_size (check_dups) > 0);
7086         }
7087 #endif
7088
7089         if (!hash || g_hash_table_size (hash) == 0)
7090                 return TRUE;
7091
7092         for (i = 0; argv[i]; i++) {
7093                 if (g_hash_table_contains (hash, argv[i]))
7094                         found_keys++;
7095         }
7096
7097         if (found_keys != g_hash_table_size (hash)) {
7098                 GHashTableIter iter;
7099                 const char *k = NULL;
7100                 const char *first_invalid_key = NULL;
7101
7102                 if (!error)
7103                         return FALSE;
7104
7105                 g_hash_table_iter_init (&iter, hash);
7106                 while (g_hash_table_iter_next (&iter, (gpointer *) &k, NULL)) {
7107                         for (i = 0; argv[i]; i++) {
7108                                 if (!strcmp (argv[i], k)) {
7109                                         first_invalid_key = k;
7110                                         break;
7111                                 }
7112                         }
7113                         if (first_invalid_key)
7114                                 break;
7115                 }
7116                 g_set_error (error,
7117                              NM_DEVICE_ERROR,
7118                              NM_DEVICE_ERROR_INCOMPATIBLE_CONNECTION,
7119                              "Can't reapply changes to '%s%s%s' setting",
7120                              setting_name ? : "",
7121                              setting_name ? "." : "",
7122                              first_invalid_key ? : "<UNKNOWN>");
7123                 g_return_val_if_fail (first_invalid_key, FALSE);
7124                 return FALSE;
7125         }
7126
7127         return TRUE;
7128 }
7129 #define _hash_check_invalid_keys(hash, setting_name, error, ...) _hash_check_invalid_keys_impl (hash, setting_name, error, ((const char *[]) { __VA_ARGS__, NULL }))
7130
7131 void
7132 nm_device_reactivate_ip4_config (NMDevice *self,
7133                                  NMSettingIPConfig *s_ip4_old,
7134                                  NMSettingIPConfig *s_ip4_new)
7135 {
7136         NMDevicePrivate *priv;
7137
7138         g_return_if_fail (NM_IS_DEVICE (self));
7139         priv = NM_DEVICE_GET_PRIVATE (self);
7140
7141         if (priv->ip4_state != IP_NONE) {
7142                 g_clear_object (&priv->con_ip4_config);
7143                 priv->con_ip4_config = nm_ip4_config_new (nm_device_get_ip_ifindex (self));
7144                 nm_ip4_config_merge_setting (priv->con_ip4_config,
7145                                              s_ip4_new,
7146                                              nm_device_get_ip4_route_metric (self));
7147
7148                 if (strcmp (nm_setting_ip_config_get_method (s_ip4_new),
7149                             nm_setting_ip_config_get_method (s_ip4_old))) {
7150                         _cleanup_ip4_pre (self, CLEANUP_TYPE_DECONFIGURE);
7151                         priv->ip4_state = IP_WAIT;
7152                         if (!nm_device_activate_stage3_ip4_start (self))
7153                                 _LOGW (LOGD_IP4, "Failed to apply IPv4 configuration");
7154                 } else {
7155                         if (!ip4_config_merge_and_apply (self, NULL, TRUE, NULL))
7156                                 _LOGW (LOGD_IP4, "Failed to reapply IPv4 configuration");
7157                 }
7158         }
7159 }
7160
7161 void
7162 nm_device_reactivate_ip6_config (NMDevice *self,
7163                                  NMSettingIPConfig *s_ip6_old,
7164                                  NMSettingIPConfig *s_ip6_new)
7165 {
7166         NMDevicePrivate *priv;
7167
7168         g_return_if_fail (NM_IS_DEVICE (self));
7169         priv = NM_DEVICE_GET_PRIVATE (self);
7170
7171         if (priv->ip6_state != IP_NONE) {
7172                 g_clear_object (&priv->con_ip6_config);
7173                 priv->con_ip6_config = nm_ip6_config_new (nm_device_get_ip_ifindex (self));
7174                 nm_ip6_config_merge_setting (priv->con_ip6_config,
7175                                              s_ip6_new,
7176                                              nm_device_get_ip6_route_metric (self));
7177
7178                 if (strcmp (nm_setting_ip_config_get_method (s_ip6_new),
7179                             nm_setting_ip_config_get_method (s_ip6_old))) {
7180                         _cleanup_ip6_pre (self, CLEANUP_TYPE_DECONFIGURE);
7181                         priv->ip6_state = IP_WAIT;
7182                         if (!nm_device_activate_stage3_ip6_start (self))
7183                                 _LOGW (LOGD_IP6, "Failed to apply IPv6 configuration");
7184                 } else {
7185                         if (!ip6_config_merge_and_apply (self, TRUE, NULL))
7186                                 _LOGW (LOGD_IP4, "Failed to reapply IPv6 configuration");
7187                 }
7188         }
7189 }
7190
7191
7192 /* reapply_connection:
7193  * @connection: the new connection settings to be applied or %NULL to reapply
7194  *   the current settings connection
7195  * @version_id: either zero, or the current version id for the applied
7196  *   connection.
7197  * @error: the error if %FALSE is returned
7198  *
7199  * Change configuration of an already configured device if possible.
7200  * Updates the device's applied connection upon success.
7201  *
7202  * Return: %FALSE if the new configuration can not be reapplied.
7203  */
7204 static gboolean
7205 reapply_connection (NMDevice *self,
7206                     NMConnection *connection,
7207                     guint64 version_id,
7208                     GError **error)
7209 {
7210         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
7211         NMConnection *applied = nm_device_get_applied_connection (self);
7212         gs_unref_object NMConnection *applied_clone = NULL;
7213         gs_unref_hashtable GHashTable *diffs = NULL;
7214         NMConnection *con_old, *con_new;
7215         NMSettingIPConfig *s_ip4_old, *s_ip4_new;
7216         NMSettingIPConfig *s_ip6_old, *s_ip6_new;
7217
7218         if (priv->state != NM_DEVICE_STATE_ACTIVATED) {
7219                 g_set_error_literal (error,
7220                                      NM_DEVICE_ERROR,
7221                                      NM_DEVICE_ERROR_NOT_ACTIVE,
7222                                      "Device is not activated");
7223                 return FALSE;
7224         }
7225
7226         nm_connection_diff (connection,
7227                             applied,
7228                             NM_SETTING_COMPARE_FLAG_IGNORE_TIMESTAMP |
7229                             NM_SETTING_COMPARE_FLAG_IGNORE_SECRETS,
7230                             &diffs);
7231
7232         /**************************************************************************
7233          * check for unsupported changes and reject to reapply
7234          *************************************************************************/
7235         if (!_hash_check_invalid_keys (diffs, NULL, error,
7236                                        NM_SETTING_IP4_CONFIG_SETTING_NAME,
7237                                        NM_SETTING_IP6_CONFIG_SETTING_NAME,
7238                                        NM_SETTING_CONNECTION_SETTING_NAME))
7239                 return FALSE;
7240
7241         if (!_hash_check_invalid_keys (diffs ? g_hash_table_lookup (diffs, NM_SETTING_CONNECTION_SETTING_NAME) : NULL,
7242                                        NM_SETTING_CONNECTION_SETTING_NAME,
7243                                        error,
7244                                        NM_SETTING_CONNECTION_ZONE,
7245                                        NM_SETTING_CONNECTION_METERED))
7246                 return FALSE;
7247
7248         if (   version_id != 0
7249             && version_id != nm_active_connection_version_id_get ((NMActiveConnection *) priv->act_request)) {
7250                 g_set_error_literal (error,
7251                                      NM_DEVICE_ERROR,
7252                                      NM_DEVICE_ERROR_VERSION_ID_MISMATCH,
7253                                      "Reapply failed because device changed in the meantime and the version-id mismatches");
7254                 return FALSE;
7255         }
7256
7257         /**************************************************************************
7258          * Update applied connection
7259          *************************************************************************/
7260
7261         if (diffs)
7262                 nm_active_connection_version_id_bump ((NMActiveConnection *) priv->act_request);
7263
7264         _LOGD (LOGD_DEVICE, "reapply (version-id %llu%s)",
7265                (long long unsigned) nm_active_connection_version_id_get (((NMActiveConnection *) priv->act_request)),
7266                diffs ? "" : " (unmodified)");
7267
7268         if (diffs) {
7269                 con_old = applied_clone  = nm_simple_connection_new_clone (applied);
7270                 con_new = applied;
7271                 nm_connection_replace_settings_from_connection (applied, connection);
7272         } else
7273                 con_old = con_new = applied;
7274
7275         s_ip4_new = nm_connection_get_setting_ip4_config (con_new);
7276         s_ip4_old = nm_connection_get_setting_ip4_config (con_old);
7277         s_ip6_new = nm_connection_get_setting_ip6_config (con_new);
7278         s_ip6_old = nm_connection_get_setting_ip6_config (con_old);
7279
7280         /**************************************************************************
7281          * Reapply changes
7282          *************************************************************************/
7283
7284         nm_device_update_firewall_zone (self);
7285         nm_device_update_metered (self);
7286
7287         nm_device_reactivate_ip4_config (self, s_ip4_old, s_ip4_new);
7288         nm_device_reactivate_ip6_config (self, s_ip6_old, s_ip6_new);
7289
7290         return TRUE;
7291 }
7292
7293 typedef struct {
7294         NMConnection *connection;
7295         guint64 version_id;
7296 } ReapplyData;
7297
7298 static void
7299 reapply_cb (NMDevice *self,
7300             GDBusMethodInvocation *context,
7301             NMAuthSubject *subject,
7302             GError *error,
7303             gpointer user_data)
7304 {
7305         ReapplyData *reapply_data = user_data;
7306         guint64 version_id = 0;
7307         gs_unref_object NMConnection *connection = NULL;
7308         GError *local = NULL;
7309
7310         if (reapply_data) {
7311                 connection = reapply_data->connection;
7312                 version_id = reapply_data->version_id;
7313                 g_slice_free (ReapplyData, reapply_data);
7314         }
7315
7316         if (error) {
7317                 nm_audit_log_device_op (NM_AUDIT_OP_DEVICE_REAPPLY, self, FALSE, subject, error->message);
7318                 g_dbus_method_invocation_return_gerror (context, error);
7319                 return;
7320         }
7321
7322         if (!reapply_connection (self,
7323                                  connection ? : (NMConnection *) nm_device_get_settings_connection (self),
7324                                  version_id,
7325                                  &local)) {
7326                 nm_audit_log_device_op (NM_AUDIT_OP_DEVICE_REAPPLY, self, FALSE, subject, local->message);
7327                 g_dbus_method_invocation_take_error (context, local);
7328                 local = NULL;
7329         } else {
7330                 nm_audit_log_device_op (NM_AUDIT_OP_DEVICE_REAPPLY, self, TRUE, subject, NULL);
7331                 g_dbus_method_invocation_return_value (context, NULL);
7332         }
7333 }
7334
7335 static void
7336 impl_device_reapply (NMDevice *self,
7337                      GDBusMethodInvocation *context,
7338                      GVariant *settings,
7339                      guint64 version_id,
7340                      guint32 flags)
7341 {
7342         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
7343         NMSettingsConnection *settings_connection;
7344         NMConnection *connection = NULL;
7345         GError *error = NULL;
7346         ReapplyData *reapply_data;
7347
7348         /* No flags supported as of now. */
7349         if (flags != 0) {
7350                 error = g_error_new_literal (NM_DEVICE_ERROR,
7351                                              NM_DEVICE_ERROR_FAILED,
7352                                              "Invalid flags specified");
7353                 nm_audit_log_device_op (NM_AUDIT_OP_DEVICE_REAPPLY, self, FALSE, context, error->message);
7354                 g_dbus_method_invocation_take_error (context, error);
7355                 return;
7356         }
7357
7358         if (priv->state != NM_DEVICE_STATE_ACTIVATED) {
7359                 error = g_error_new_literal (NM_DEVICE_ERROR,
7360                                              NM_DEVICE_ERROR_NOT_ACTIVE,
7361                                              "Device is not activated");
7362                 nm_audit_log_device_op (NM_AUDIT_OP_DEVICE_REAPPLY, self, FALSE, context, error->message);
7363                 g_dbus_method_invocation_take_error (context, error);
7364                 return;
7365         }
7366
7367         settings_connection = nm_device_get_settings_connection (self);
7368         g_return_if_fail (settings_connection);
7369
7370         if (settings && g_variant_n_children (settings)) {
7371                 /* New settings specified inline. */
7372                 connection = nm_simple_connection_new_from_dbus (settings, &error);
7373                 if (!connection) {
7374                         g_prefix_error (&error, "The settings specified are invalid: ");
7375                         nm_audit_log_device_op (NM_AUDIT_OP_DEVICE_REAPPLY, self, FALSE, context, error->message);
7376                         g_dbus_method_invocation_take_error (context, error);
7377                         return;
7378                 }
7379                 nm_connection_clear_secrets (connection);
7380         }
7381
7382         if (connection || version_id) {
7383                 reapply_data = g_slice_new (ReapplyData);
7384                 reapply_data->connection = connection;
7385                 reapply_data->version_id = version_id;
7386         } else
7387                 reapply_data = NULL;
7388
7389         /* Ask the manager to authenticate this request for us */
7390         g_signal_emit (self, signals[AUTH_REQUEST], 0,
7391                        context,
7392                        nm_device_get_applied_connection (self),
7393                        NM_AUTH_PERMISSION_NETWORK_CONTROL,
7394                        TRUE,
7395                        reapply_cb,
7396                        reapply_data);
7397 }
7398
7399 /*****************************************************************************/
7400
7401 static void
7402 get_applied_connection_cb (NMDevice *self,
7403                            GDBusMethodInvocation *context,
7404                            NMAuthSubject *subject,
7405                            GError *error,
7406                            gpointer user_data /* possibly dangling pointer */)
7407 {
7408         NMDevicePrivate *priv;
7409         NMConnection *applied_connection;
7410         GVariant *settings;
7411
7412         g_return_if_fail (NM_IS_DEVICE (self));
7413
7414         if (error) {
7415                 g_dbus_method_invocation_return_gerror (context, error);
7416                 return;
7417         }
7418
7419         priv = NM_DEVICE_GET_PRIVATE (self);
7420
7421         applied_connection = nm_device_get_applied_connection (self);
7422
7423         if (!applied_connection) {
7424                 error = g_error_new_literal (NM_DEVICE_ERROR,
7425                                              NM_DEVICE_ERROR_NOT_ACTIVE,
7426                                              "Device is not activated");
7427                 g_dbus_method_invocation_take_error (context, error);
7428                 return;
7429         }
7430
7431         if (applied_connection != user_data) {
7432                 /* The applied connection changed due to a race. Reauthenticate. */
7433                 g_signal_emit (self, signals[AUTH_REQUEST], 0,
7434                                context,
7435                                applied_connection,
7436                                NM_AUTH_PERMISSION_NETWORK_CONTROL,
7437                                TRUE,
7438                                get_applied_connection_cb,
7439                                applied_connection /* no need take a ref. We will not dereference this pointer. */);
7440                 return;
7441         }
7442
7443         settings = nm_connection_to_dbus (applied_connection, NM_CONNECTION_SERIALIZE_NO_SECRETS);
7444         if (!settings)
7445                 settings = g_variant_new_array (G_VARIANT_TYPE ("{sa{sv}}"), NULL, 0);
7446
7447         g_dbus_method_invocation_return_value (context,
7448                                                g_variant_new ("(@a{sa{sv}}t)",
7449                                                               settings,
7450                                                               nm_active_connection_version_id_get ((NMActiveConnection *) priv->act_request)));
7451 }
7452
7453 static void
7454 impl_device_get_applied_connection (NMDevice *self,
7455                                     GDBusMethodInvocation *context,
7456                                     guint32 flags)
7457 {
7458         NMConnection *applied_connection;
7459         GError *error = NULL;
7460
7461         g_return_if_fail (NM_IS_DEVICE (self));
7462
7463         /* No flags supported as of now. */
7464         if (flags != 0) {
7465                 error = g_error_new_literal (NM_DEVICE_ERROR,
7466                                              NM_DEVICE_ERROR_FAILED,
7467                                              "Invalid flags specified");
7468                 g_dbus_method_invocation_take_error (context, error);
7469                 return;
7470         }
7471
7472         applied_connection = nm_device_get_applied_connection (self);
7473         if (!applied_connection) {
7474                 error = g_error_new_literal (NM_DEVICE_ERROR,
7475                                              NM_DEVICE_ERROR_NOT_ACTIVE,
7476                                              "Device is not activated");
7477                 g_dbus_method_invocation_take_error (context, error);
7478                 return;
7479         }
7480
7481         /* Ask the manager to authenticate this request for us */
7482         g_signal_emit (self, signals[AUTH_REQUEST], 0,
7483                        context,
7484                        applied_connection,
7485                        NM_AUTH_PERMISSION_NETWORK_CONTROL,
7486                        TRUE,
7487                        get_applied_connection_cb,
7488                        applied_connection /* no need take a ref. We will not dereference this pointer. */);
7489 }
7490
7491 /*****************************************************************************/
7492
7493 static void
7494 disconnect_cb (NMDevice *self,
7495                GDBusMethodInvocation *context,
7496                NMAuthSubject *subject,
7497                GError *error,
7498                gpointer user_data)
7499 {
7500         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
7501         GError *local = NULL;
7502
7503         if (error) {
7504                 g_dbus_method_invocation_return_gerror (context, error);
7505                 nm_audit_log_device_op (NM_AUDIT_OP_DEVICE_DISCONNECT, self, FALSE, subject, error->message);
7506                 return;
7507         }
7508
7509         /* Authorized */
7510         if (priv->state <= NM_DEVICE_STATE_DISCONNECTED) {
7511                 local = g_error_new_literal (NM_DEVICE_ERROR,
7512                                              NM_DEVICE_ERROR_NOT_ACTIVE,
7513                                              "Device is not active");
7514                 nm_audit_log_device_op (NM_AUDIT_OP_DEVICE_DISCONNECT, self, FALSE, subject, local->message);
7515                 g_dbus_method_invocation_take_error (context, local);
7516         } else {
7517                 nm_device_set_autoconnect (self, FALSE);
7518
7519                 nm_device_state_changed (self,
7520                                          NM_DEVICE_STATE_DEACTIVATING,
7521                                          NM_DEVICE_STATE_REASON_USER_REQUESTED);
7522                 g_dbus_method_invocation_return_value (context, NULL);
7523                 nm_audit_log_device_op (NM_AUDIT_OP_DEVICE_DISCONNECT, self, TRUE, subject, NULL);
7524         }
7525 }
7526
7527 static void
7528 _clear_queued_act_request (NMDevicePrivate *priv)
7529 {
7530         if (priv->queued_act_request) {
7531                 nm_active_connection_set_state ((NMActiveConnection *) priv->queued_act_request, NM_ACTIVE_CONNECTION_STATE_DEACTIVATED);
7532                 g_clear_object (&priv->queued_act_request);
7533         }
7534 }
7535
7536 static void
7537 impl_device_disconnect (NMDevice *self, GDBusMethodInvocation *context)
7538 {
7539         NMConnection *connection;
7540         GError *error = NULL;
7541
7542         if (NM_DEVICE_GET_PRIVATE (self)->act_request == NULL) {
7543                 error = g_error_new_literal (NM_DEVICE_ERROR,
7544                                              NM_DEVICE_ERROR_NOT_ACTIVE,
7545                                              "This device is not active");
7546                 g_dbus_method_invocation_take_error (context, error);
7547                 return;
7548         }
7549
7550         connection = nm_device_get_applied_connection (self);
7551         g_assert (connection);
7552
7553         /* Ask the manager to authenticate this request for us */
7554         g_signal_emit (self, signals[AUTH_REQUEST], 0,
7555                        context,
7556                        connection,
7557                        NM_AUTH_PERMISSION_NETWORK_CONTROL,
7558                        TRUE,
7559                        disconnect_cb,
7560                        NULL);
7561 }
7562
7563 static void
7564 delete_cb (NMDevice *self,
7565            GDBusMethodInvocation *context,
7566            NMAuthSubject *subject,
7567            GError *error,
7568            gpointer user_data)
7569 {
7570         GError *local = NULL;
7571
7572         if (error) {
7573                 g_dbus_method_invocation_return_gerror (context, error);
7574                 nm_audit_log_device_op (NM_AUDIT_OP_DEVICE_DELETE, self, FALSE, subject, error->message);
7575                 return;
7576         }
7577
7578         /* Authorized */
7579         nm_audit_log_device_op (NM_AUDIT_OP_DEVICE_DELETE, self, TRUE, subject, NULL);
7580         if (nm_device_unrealize (self, TRUE, &local))
7581                 g_dbus_method_invocation_return_value (context, NULL);
7582         else
7583                 g_dbus_method_invocation_take_error (context, local);
7584 }
7585
7586 static void
7587 impl_device_delete (NMDevice *self, GDBusMethodInvocation *context)
7588 {
7589         GError *error = NULL;
7590
7591         if (!nm_device_is_software (self) || !nm_device_is_real (self)) {
7592                 error = g_error_new_literal (NM_DEVICE_ERROR,
7593                                              NM_DEVICE_ERROR_NOT_SOFTWARE,
7594                                              "This device is not a software device or is not realized");
7595                 g_dbus_method_invocation_take_error (context, error);
7596                 return;
7597         }
7598
7599         /* Ask the manager to authenticate this request for us */
7600         g_signal_emit (self, signals[AUTH_REQUEST], 0,
7601                        context,
7602                        NULL,
7603                        NM_AUTH_PERMISSION_NETWORK_CONTROL,
7604                        TRUE,
7605                        delete_cb,
7606                        NULL);
7607 }
7608
7609 static gboolean
7610 _device_activate (NMDevice *self, NMActRequest *req)
7611 {
7612         NMDevicePrivate *priv;
7613         NMConnection *connection;
7614
7615         g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
7616         g_return_val_if_fail (NM_IS_ACT_REQUEST (req), FALSE);
7617         g_return_val_if_fail (nm_device_get_managed (self, FALSE), FALSE);
7618
7619         /* Ensure the activation request is still valid; the master may have
7620          * already failed in which case activation of this device should not proceed.
7621          */
7622         if (nm_active_connection_get_state (NM_ACTIVE_CONNECTION (req)) >= NM_ACTIVE_CONNECTION_STATE_DEACTIVATING)
7623                 return FALSE;
7624
7625         priv = NM_DEVICE_GET_PRIVATE (self);
7626
7627         connection = nm_act_request_get_applied_connection (req);
7628         g_assert (connection);
7629
7630         _LOGI (LOGD_DEVICE, "Activation: starting connection '%s' (%s)",
7631                nm_connection_get_id (connection),
7632                nm_connection_get_uuid (connection));
7633
7634         delete_on_deactivate_unschedule (self);
7635
7636         /* note: don't notify D-Bus of the new AC here, but do it later when
7637          * changing state to PREPARE so that the two properties change together.
7638          */
7639         priv->act_request = g_object_ref (req);
7640
7641         nm_device_activate_schedule_stage1_device_prepare (self);
7642         return TRUE;
7643 }
7644
7645 static void
7646 _carrier_wait_check_queued_act_request (NMDevice *self)
7647 {
7648         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
7649         NMActRequest *queued_req;
7650
7651         if (   !priv->queued_act_request
7652             || !priv->queued_act_request_is_waiting_for_carrier)
7653                 return;
7654
7655         priv->queued_act_request_is_waiting_for_carrier = FALSE;
7656         if (!priv->carrier) {
7657                 _LOGD (LOGD_DEVICE, "Cancel queued activation request as we have no carrier after timeout");
7658                 _clear_queued_act_request (priv);
7659         } else {
7660                 _LOGD (LOGD_DEVICE, "Activate queued activation request as we now have carrier");
7661                 queued_req = priv->queued_act_request;
7662                 priv->queued_act_request = NULL;
7663                 _device_activate (self, queued_req);
7664                 g_object_unref (queued_req);
7665         }
7666 }
7667
7668 static gboolean
7669 _carrier_wait_check_act_request_must_queue (NMDevice *self, NMActRequest *req)
7670 {
7671         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
7672         NMConnection *connection;
7673
7674         /* If we have carrier or if we are not waiting for it, the activation
7675          * request is not blocked waiting for carrier. */
7676         if (priv->carrier)
7677                 return FALSE;
7678         if (priv->carrier_wait_id == 0)
7679                 return FALSE;
7680
7681         connection = nm_act_request_get_applied_connection (req);
7682         if (!connection_requires_carrier (connection))
7683                 return FALSE;
7684
7685         if (!nm_device_check_connection_available (self, connection, NM_DEVICE_CHECK_CON_AVAILABLE_ALL, NULL)) {
7686                 /* We passed all @flags we have, and no @specific_object.
7687                  * This equals maximal availability, if a connection is not available
7688                  * in this case, it is not waiting for carrier.
7689                  *
7690                  * Actually, why are we even trying to activate it? Strange, but whatever
7691                  * the reason, don't wait for carrier.
7692                  */
7693                 return FALSE;
7694         }
7695
7696         if (nm_device_check_connection_available (self, connection, NM_DEVICE_CHECK_CON_AVAILABLE_ALL & ~_NM_DEVICE_CHECK_CON_AVAILABLE_FOR_USER_REQUEST_WAITING_CARRIER, NULL)) {
7697                 /* The connection was available with flags ALL, and it is still available
7698                  * if we pretend not to wait for carrier. That means that the
7699                  * connection is available now, and does not wait for carrier.
7700                  *
7701                  * Since the flags increase the availability of a connection, when checking
7702                  * ALL&~WAITING_CARRIER, it means that we certainly would wait for carrier. */
7703                 return FALSE;
7704         }
7705
7706         /* The activation request must wait for carrier. */
7707         return TRUE;
7708 }
7709
7710 void
7711 nm_device_steal_connection (NMDevice *self, NMSettingsConnection *connection)
7712 {
7713         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
7714
7715         _LOGW (LOGD_DEVICE, "disconnecting connection '%s' for new activation request.",
7716                nm_settings_connection_get_id (connection));
7717
7718         if (   priv->queued_act_request
7719             && connection == nm_active_connection_get_settings_connection (NM_ACTIVE_CONNECTION (priv->queued_act_request)))
7720                 _clear_queued_act_request (priv);
7721
7722         if (   priv->act_request
7723             && connection == nm_active_connection_get_settings_connection (NM_ACTIVE_CONNECTION (priv->act_request))
7724             && priv->state < NM_DEVICE_STATE_DEACTIVATING)
7725                 nm_device_state_changed (self,
7726                                          NM_DEVICE_STATE_DEACTIVATING,
7727                                          NM_DEVICE_STATE_REASON_NEW_ACTIVATION);
7728 }
7729
7730 void
7731 nm_device_queue_activation (NMDevice *self, NMActRequest *req)
7732 {
7733         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
7734         gboolean must_queue;
7735
7736         must_queue = _carrier_wait_check_act_request_must_queue (self, req);
7737
7738         if (!priv->act_request && !must_queue) {
7739                 /* Just activate immediately */
7740                 if (!_device_activate (self, req))
7741                         g_assert_not_reached ();
7742                 return;
7743         }
7744
7745         /* supercede any already-queued request */
7746         _clear_queued_act_request (priv);
7747         priv->queued_act_request = g_object_ref (req);
7748         priv->queued_act_request_is_waiting_for_carrier = must_queue;
7749
7750         _LOGD (LOGD_DEVICE, "queue activation request waiting for %s", must_queue ? "carrier" : "currently active connection to disconnect");
7751
7752         /* Deactivate existing activation request first */
7753         if (priv->act_request) {
7754                 _LOGI (LOGD_DEVICE, "disconnecting for new activation request.");
7755                 nm_device_state_changed (self,
7756                                          NM_DEVICE_STATE_DEACTIVATING,
7757                                          NM_DEVICE_STATE_REASON_NEW_ACTIVATION);
7758         }
7759 }
7760
7761 /*
7762  * nm_device_is_activating
7763  *
7764  * Return whether or not the device is currently activating itself.
7765  *
7766  */
7767 gboolean
7768 nm_device_is_activating (NMDevice *self)
7769 {
7770         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
7771         NMDeviceState state;
7772
7773         g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
7774
7775         state = nm_device_get_state (self);
7776         if (state >= NM_DEVICE_STATE_PREPARE && state <= NM_DEVICE_STATE_SECONDARIES)
7777                 return TRUE;
7778
7779         /* There's a small race between the time when stage 1 is scheduled
7780          * and when the device actually sets STATE_PREPARE when the activation
7781          * handler is actually run.  If there's an activation handler scheduled
7782          * we're activating anyway.
7783          */
7784         return priv->act_handle4.id ? TRUE : FALSE;
7785 }
7786
7787 /* IP Configuration stuff */
7788
7789 NMDhcp4Config *
7790 nm_device_get_dhcp4_config (NMDevice *self)
7791 {
7792         g_return_val_if_fail (NM_IS_DEVICE (self), NULL);
7793
7794         return NM_DEVICE_GET_PRIVATE (self)->dhcp4_config;
7795 }
7796
7797 NMIP4Config *
7798 nm_device_get_ip4_config (NMDevice *self)
7799 {
7800         g_return_val_if_fail (NM_IS_DEVICE (self), NULL);
7801
7802         return NM_DEVICE_GET_PRIVATE (self)->ip4_config;
7803 }
7804
7805
7806 static gboolean
7807 nm_device_set_ip4_config (NMDevice *self,
7808                           NMIP4Config *new_config,
7809                           guint32 default_route_metric,
7810                           gboolean commit,
7811                           gboolean routes_full_sync,
7812                           NMDeviceStateReason *reason)
7813 {
7814         NMDevicePrivate *priv;
7815         NMIP4Config *old_config = NULL;
7816         gboolean has_changes = FALSE;
7817         gboolean success = TRUE;
7818         NMDeviceStateReason reason_local = NM_DEVICE_STATE_REASON_NONE;
7819         int ip_ifindex, config_ifindex;
7820
7821         g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
7822
7823         priv = NM_DEVICE_GET_PRIVATE (self);
7824         ip_ifindex = nm_device_get_ip_ifindex (self);
7825
7826         if (new_config) {
7827                 config_ifindex = nm_ip4_config_get_ifindex (new_config);
7828                 if (config_ifindex > 0)
7829                         g_return_val_if_fail (ip_ifindex == config_ifindex, FALSE);
7830         }
7831
7832         old_config = priv->ip4_config;
7833
7834         /* Always commit to nm-platform to update lifetimes */
7835         if (commit && new_config) {
7836                 gboolean assumed = nm_device_uses_assumed_connection (self);
7837
7838                 nm_device_set_mtu (self, nm_ip4_config_get_mtu (new_config));
7839
7840                 /* For assumed devices we must not touch the kernel-routes, such as the device-route.
7841                  * FIXME: this is wrong in case where "assumed" means "take-over-seamlessly". In this
7842                  * case, we should manage the device route, for example on new DHCP lease. */
7843                 success = nm_ip4_config_commit (new_config, ip_ifindex,
7844                                                 routes_full_sync,
7845                                                 assumed ? (gint64) -1 : (gint64) default_route_metric);
7846                 if (!success)
7847                         reason_local = NM_DEVICE_STATE_REASON_CONFIG_FAILED;
7848         }
7849
7850         if (new_config) {
7851                 if (old_config) {
7852                         /* has_changes is set only on relevant changes, because when the configuration changes,
7853                          * this causes a re-read and reset. This should only happen for relevant changes */
7854                         nm_ip4_config_replace (old_config, new_config, &has_changes);
7855                         if (has_changes) {
7856                                 _LOGD (LOGD_IP4, "update IP4Config instance (%s)",
7857                                        nm_exported_object_get_path (NM_EXPORTED_OBJECT (old_config)));
7858                         }
7859                 } else {
7860                         has_changes = TRUE;
7861                         priv->ip4_config = g_object_ref (new_config);
7862
7863                         if (success && !nm_exported_object_is_exported (NM_EXPORTED_OBJECT (new_config)))
7864                                 nm_exported_object_export (NM_EXPORTED_OBJECT (new_config));
7865
7866                         _LOGD (LOGD_IP4, "set IP4Config instance (%s)",
7867                                nm_exported_object_get_path (NM_EXPORTED_OBJECT (new_config)));
7868                 }
7869         } else if (old_config) {
7870                 has_changes = TRUE;
7871                 priv->ip4_config = NULL;
7872                 _LOGD (LOGD_IP4, "clear IP4Config instance (%s)",
7873                        nm_exported_object_get_path (NM_EXPORTED_OBJECT (old_config)));
7874                 /* Device config is invalid if combined config is invalid */
7875                 g_clear_object (&priv->dev_ip4_config);
7876         }
7877
7878         nm_default_route_manager_ip4_update_default_route (nm_default_route_manager_get (), self);
7879
7880         if (has_changes) {
7881                 _update_ip4_address (self);
7882
7883                 if (old_config != priv->ip4_config)
7884                         _notify (self, PROP_IP4_CONFIG);
7885                 g_signal_emit (self, signals[IP4_CONFIG_CHANGED], 0, priv->ip4_config, old_config);
7886
7887                 if (old_config != priv->ip4_config)
7888                         nm_exported_object_clear_and_unexport (&old_config);
7889
7890                 if (nm_device_uses_generated_assumed_connection (self)) {
7891                         NMConnection *connection = nm_device_get_applied_connection (self);
7892                         NMConnection *settings_connection = NM_CONNECTION (nm_device_get_settings_connection (self));
7893                         NMSetting *s_ip4;
7894
7895                         g_object_freeze_notify (G_OBJECT (connection));
7896                         g_object_freeze_notify (G_OBJECT (settings_connection));
7897
7898                         nm_connection_remove_setting (settings_connection, NM_TYPE_SETTING_IP4_CONFIG);
7899                         s_ip4 = nm_ip4_config_create_setting (priv->ip4_config);
7900                         nm_connection_add_setting (settings_connection, s_ip4);
7901
7902                         nm_connection_remove_setting (connection, NM_TYPE_SETTING_IP4_CONFIG);
7903                         s_ip4 = nm_ip4_config_create_setting (priv->ip4_config);
7904                         nm_connection_add_setting (connection, s_ip4);
7905
7906                         g_object_thaw_notify (G_OBJECT (settings_connection));
7907                         g_object_thaw_notify (G_OBJECT (connection));
7908                 }
7909
7910                 nm_device_queue_recheck_assume (self);
7911         }
7912
7913         if (reason)
7914                 *reason = reason_local;
7915
7916         return success;
7917 }
7918
7919 static gboolean
7920 _replace_vpn_config_in_list (GSList **plist, GObject *old, GObject *new)
7921 {
7922         GSList *old_link;
7923
7924         /* Below, assert that @new is not yet tracked, but still behave
7925          * correctly in any case. Don't complain for missing @old since
7926          * it could have been removed when the parent device became
7927          * unmanaged. */
7928
7929         if (   old
7930             && (old_link = g_slist_find (*plist, old))) {
7931                 if (old != new) {
7932                         if (new)
7933                                 old_link->data = g_object_ref (new);
7934                         else
7935                                 *plist = g_slist_delete_link (*plist, old_link);
7936                         g_object_unref (old);
7937                 }
7938                 return TRUE;
7939         }
7940
7941         if (new) {
7942                 if (!g_slist_find (*plist, new))
7943                         *plist = g_slist_append (*plist, g_object_ref (new));
7944                 else
7945                         g_return_val_if_reached (TRUE);
7946                 return TRUE;
7947         }
7948
7949         return FALSE;
7950 }
7951
7952 void
7953 nm_device_replace_vpn4_config (NMDevice *self, NMIP4Config *old, NMIP4Config *config)
7954 {
7955         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
7956
7957         if (!_replace_vpn_config_in_list (&priv->vpn4_configs, (GObject *) old, (GObject *) config))
7958                 return;
7959
7960         /* NULL to use existing configs */
7961         if (!ip4_config_merge_and_apply (self, NULL, TRUE, NULL))
7962                 _LOGW (LOGD_IP4, "failed to set VPN routes for device");
7963 }
7964
7965 void
7966 nm_device_set_wwan_ip4_config (NMDevice *self, NMIP4Config *config)
7967 {
7968         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
7969
7970         if (priv->wwan_ip4_config == config)
7971                 return;
7972
7973         g_clear_object (&priv->wwan_ip4_config);
7974         if (config)
7975                 priv->wwan_ip4_config = g_object_ref (config);
7976
7977         /* NULL to use existing configs */
7978         if (!ip4_config_merge_and_apply (self, NULL, TRUE, NULL))
7979                 _LOGW (LOGD_IP4, "failed to set WWAN IPv4 configuration");
7980 }
7981
7982 static gboolean
7983 nm_device_set_ip6_config (NMDevice *self,
7984                           NMIP6Config *new_config,
7985                           gboolean commit,
7986                           gboolean routes_full_sync,
7987                           NMDeviceStateReason *reason)
7988 {
7989         NMDevicePrivate *priv;
7990         NMIP6Config *old_config = NULL;
7991         gboolean has_changes = FALSE;
7992         gboolean success = TRUE;
7993         NMDeviceStateReason reason_local = NM_DEVICE_STATE_REASON_NONE;
7994         int ip_ifindex, config_ifindex;
7995
7996         g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
7997
7998         priv = NM_DEVICE_GET_PRIVATE (self);
7999         ip_ifindex = nm_device_get_ip_ifindex (self);
8000
8001         if (new_config) {
8002                 config_ifindex = nm_ip6_config_get_ifindex (new_config);
8003                 if (config_ifindex > 0)
8004                         g_return_val_if_fail (ip_ifindex == config_ifindex, FALSE);
8005         }
8006
8007         old_config = priv->ip6_config;
8008
8009         /* Always commit to nm-platform to update lifetimes */
8010         if (commit && new_config) {
8011                 nm_device_ipv6_set_mtu (self, priv->ip6_mtu);
8012                 success = nm_ip6_config_commit (new_config,
8013                                                 ip_ifindex,
8014                                                 routes_full_sync);
8015                 if (!success)
8016                         reason_local = NM_DEVICE_STATE_REASON_CONFIG_FAILED;
8017         }
8018
8019         if (new_config) {
8020                 if (old_config) {
8021                         /* has_changes is set only on relevant changes, because when the configuration changes,
8022                          * this causes a re-read and reset. This should only happen for relevant changes */
8023                         nm_ip6_config_replace (old_config, new_config, &has_changes);
8024                         if (has_changes) {
8025                                 _LOGD (LOGD_IP6, "update IP6Config instance (%s)",
8026                                        nm_exported_object_get_path (NM_EXPORTED_OBJECT (old_config)));
8027                         }
8028                 } else {
8029                         has_changes = TRUE;
8030                         priv->ip6_config = g_object_ref (new_config);
8031
8032                         if (success && !nm_exported_object_is_exported (NM_EXPORTED_OBJECT (new_config)))
8033                                 nm_exported_object_export (NM_EXPORTED_OBJECT (new_config));
8034
8035                         _LOGD (LOGD_IP6, "set IP6Config instance (%s)",
8036                                nm_exported_object_get_path (NM_EXPORTED_OBJECT (new_config)));
8037                 }
8038         } else if (old_config) {
8039                 has_changes = TRUE;
8040                 priv->ip6_config = NULL;
8041                 _LOGD (LOGD_IP6, "clear IP6Config instance (%s)",
8042                        nm_exported_object_get_path (NM_EXPORTED_OBJECT (old_config)));
8043         }
8044
8045         nm_default_route_manager_ip6_update_default_route (nm_default_route_manager_get (), self);
8046
8047         if (has_changes) {
8048                 if (old_config != priv->ip6_config)
8049                         _notify (self, PROP_IP6_CONFIG);
8050                 g_signal_emit (self, signals[IP6_CONFIG_CHANGED], 0, priv->ip6_config, old_config);
8051
8052                 if (old_config != priv->ip6_config)
8053                         nm_exported_object_clear_and_unexport (&old_config);
8054
8055                 if (nm_device_uses_generated_assumed_connection (self)) {
8056                         NMConnection *connection = nm_device_get_applied_connection (self);
8057                         NMConnection *settings_connection = NM_CONNECTION (nm_device_get_settings_connection (self));
8058                         NMSetting *s_ip6;
8059
8060                         g_object_freeze_notify (G_OBJECT (connection));
8061                         g_object_freeze_notify (G_OBJECT (settings_connection));
8062
8063                         nm_connection_remove_setting (settings_connection, NM_TYPE_SETTING_IP6_CONFIG);
8064                         s_ip6 = nm_ip6_config_create_setting (priv->ip6_config);
8065                         nm_connection_add_setting (settings_connection, s_ip6);
8066
8067                         nm_connection_remove_setting (connection, NM_TYPE_SETTING_IP6_CONFIG);
8068                         s_ip6 = nm_ip6_config_create_setting (priv->ip6_config);
8069                         nm_connection_add_setting (connection, s_ip6);
8070
8071                         g_object_thaw_notify (G_OBJECT (settings_connection));
8072                         g_object_thaw_notify (G_OBJECT (connection));
8073                 }
8074
8075                 nm_device_queue_recheck_assume (self);
8076         }
8077
8078         if (reason)
8079                 *reason = reason_local;
8080
8081         return success;
8082 }
8083
8084 void
8085 nm_device_replace_vpn6_config (NMDevice *self, NMIP6Config *old, NMIP6Config *config)
8086 {
8087         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
8088
8089         if (!_replace_vpn_config_in_list (&priv->vpn6_configs, (GObject *) old, (GObject *) config))
8090                 return;
8091
8092         /* NULL to use existing configs */
8093         if (!ip6_config_merge_and_apply (self, TRUE, NULL))
8094                 _LOGW (LOGD_IP6, "failed to set VPN routes for device");
8095 }
8096
8097 void
8098 nm_device_set_wwan_ip6_config (NMDevice *self, NMIP6Config *config)
8099 {
8100         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
8101
8102         if (priv->wwan_ip6_config == config)
8103                 return;
8104
8105         g_clear_object (&priv->wwan_ip6_config);
8106         if (config)
8107                 priv->wwan_ip6_config = g_object_ref (config);
8108
8109         /* NULL to use existing configs */
8110         if (!ip6_config_merge_and_apply (self, TRUE, NULL))
8111                 _LOGW (LOGD_IP6, "failed to set WWAN IPv6 configuration");
8112 }
8113
8114 NMDhcp6Config *
8115 nm_device_get_dhcp6_config (NMDevice *self)
8116 {
8117         g_return_val_if_fail (NM_IS_DEVICE (self), NULL);
8118
8119         return NM_DEVICE_GET_PRIVATE (self)->dhcp6_config;
8120 }
8121
8122 NMIP6Config *
8123 nm_device_get_ip6_config (NMDevice *self)
8124 {
8125         g_return_val_if_fail (NM_IS_DEVICE (self), NULL);
8126
8127         return NM_DEVICE_GET_PRIVATE (self)->ip6_config;
8128 }
8129
8130 /****************************************************************/
8131
8132 static void
8133 dispatcher_cleanup (NMDevice *self)
8134 {
8135         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
8136
8137         if (priv->dispatcher.call_id) {
8138                 nm_dispatcher_call_cancel (priv->dispatcher.call_id);
8139                 priv->dispatcher.call_id = 0;
8140                 priv->dispatcher.post_state = NM_DEVICE_STATE_UNKNOWN;
8141                 priv->dispatcher.post_state_reason = NM_DEVICE_STATE_REASON_NONE;
8142         }
8143 }
8144
8145 static void
8146 dispatcher_complete_proceed_state (guint call_id, gpointer user_data)
8147 {
8148         NMDevice *self = NM_DEVICE (user_data);
8149         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
8150
8151         g_return_if_fail (call_id == priv->dispatcher.call_id);
8152
8153         priv->dispatcher.call_id = 0;
8154         nm_device_queue_state (self, priv->dispatcher.post_state,
8155                                priv->dispatcher.post_state_reason);
8156         priv->dispatcher.post_state = NM_DEVICE_STATE_UNKNOWN;
8157         priv->dispatcher.post_state_reason = NM_DEVICE_STATE_REASON_NONE;
8158 }
8159
8160 /****************************************************************/
8161
8162 static void
8163 ip_check_pre_up (NMDevice *self)
8164 {
8165         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
8166
8167         if (priv->dispatcher.call_id != 0) {
8168                 g_warn_if_reached ();
8169                 dispatcher_cleanup (self);
8170         }
8171
8172         priv->dispatcher.post_state = NM_DEVICE_STATE_SECONDARIES;
8173         priv->dispatcher.post_state_reason = NM_DEVICE_STATE_REASON_NONE;
8174         if (!nm_dispatcher_call (DISPATCHER_ACTION_PRE_UP,
8175                                  nm_device_get_settings_connection (self),
8176                                  nm_device_get_applied_connection (self),
8177                                  self,
8178                                  dispatcher_complete_proceed_state,
8179                                  self,
8180                                  &priv->dispatcher.call_id)) {
8181                 /* Just proceed on errors */
8182                 dispatcher_complete_proceed_state (0, self);
8183         }
8184 }
8185
8186 static void
8187 ip_check_gw_ping_cleanup (NMDevice *self)
8188 {
8189         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
8190
8191         nm_clear_g_source (&priv->gw_ping.watch);
8192         nm_clear_g_source (&priv->gw_ping.timeout);
8193
8194         if (priv->gw_ping.pid) {
8195                 nm_utils_kill_child_async (priv->gw_ping.pid, SIGTERM, priv->gw_ping.log_domain, "ping", 1000, NULL, NULL);
8196                 priv->gw_ping.pid = 0;
8197         }
8198
8199         g_clear_pointer (&priv->gw_ping.binary, g_free);
8200         g_clear_pointer (&priv->gw_ping.address, g_free);
8201 }
8202
8203 static gboolean
8204 spawn_ping (NMDevice *self)
8205 {
8206         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
8207         gs_free char *str_timeout = NULL;
8208         gs_free char *tmp_str = NULL;
8209         const char *args[] = { priv->gw_ping.binary, "-I", nm_device_get_ip_iface (self),
8210                                "-c", "1", "-w", NULL, priv->gw_ping.address, NULL };
8211         gs_free_error GError *error = NULL;
8212         gboolean ret;
8213
8214         args[6] = str_timeout = g_strdup_printf ("%u", priv->gw_ping.deadline);
8215         tmp_str = g_strjoinv (" ", (gchar **) args);
8216         _LOGD (priv->gw_ping.log_domain, "ping: running '%s'", tmp_str);
8217
8218         ret = g_spawn_async ("/",
8219                              (gchar **) args,
8220                               NULL,
8221                               G_SPAWN_DO_NOT_REAP_CHILD,
8222                               NULL,
8223                               NULL,
8224                               &priv->gw_ping.pid,
8225                               &error);
8226
8227         if (!ret) {
8228                 _LOGW (priv->gw_ping.log_domain, "ping: could not spawn %s: %s",
8229                        priv->gw_ping.binary, error->message);
8230         }
8231
8232         return ret;
8233 }
8234
8235 static gboolean
8236 respawn_ping_cb (gpointer user_data)
8237 {
8238         NMDevice *self = NM_DEVICE (user_data);
8239         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
8240
8241         priv->gw_ping.watch = 0;
8242
8243         if (spawn_ping (self)) {
8244                 priv->gw_ping.watch = g_child_watch_add (priv->gw_ping.pid,
8245                                                          ip_check_ping_watch_cb, self);
8246         } else {
8247                 ip_check_gw_ping_cleanup (self);
8248                 ip_check_pre_up (self);
8249         }
8250
8251         return FALSE;
8252 }
8253
8254 static void
8255 ip_check_ping_watch_cb (GPid pid, gint status, gpointer user_data)
8256 {
8257         NMDevice *self = NM_DEVICE (user_data);
8258         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
8259         NMLogDomain log_domain = priv->gw_ping.log_domain;
8260         gboolean success = FALSE;
8261
8262         if (!priv->gw_ping.watch)
8263                 return;
8264         priv->gw_ping.watch = 0;
8265         priv->gw_ping.pid = 0;
8266
8267         if (WIFEXITED (status)) {
8268                 if (WEXITSTATUS (status) == 0) {
8269                         _LOGD (log_domain, "ping: gateway ping succeeded");
8270                         success = TRUE;
8271                 } else {
8272                         _LOGW (log_domain, "ping: gateway ping failed with error code %d",
8273                                WEXITSTATUS (status));
8274                 }
8275         } else
8276                 _LOGW (log_domain, "ping: stopped unexpectedly with status %d", status);
8277
8278         if (success) {
8279                 /* We've got connectivity, proceed to pre_up */
8280                 ip_check_gw_ping_cleanup (self);
8281                 ip_check_pre_up (self);
8282         } else {
8283                 /* If ping exited with an error it may have returned early,
8284                  * wait 1 second and restart it */
8285                 priv->gw_ping.watch = g_timeout_add_seconds (1, respawn_ping_cb, self);
8286         }
8287 }
8288
8289 static gboolean
8290 ip_check_ping_timeout_cb (gpointer user_data)
8291 {
8292         NMDevice *self = NM_DEVICE (user_data);
8293         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
8294
8295         priv->gw_ping.timeout = 0;
8296
8297         _LOGW (priv->gw_ping.log_domain, "ping: gateway ping timed out");
8298
8299         ip_check_gw_ping_cleanup (self);
8300         ip_check_pre_up (self);
8301         return FALSE;
8302 }
8303
8304 static gboolean
8305 start_ping (NMDevice *self,
8306             NMLogDomain log_domain,
8307             const char *binary,
8308             const char *address,
8309             guint timeout)
8310 {
8311         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
8312
8313         g_return_val_if_fail (priv->gw_ping.watch == 0, FALSE);
8314         g_return_val_if_fail (priv->gw_ping.timeout == 0, FALSE);
8315
8316         priv->gw_ping.log_domain = log_domain;
8317         priv->gw_ping.address = g_strdup (address);
8318         priv->gw_ping.binary = g_strdup (binary);
8319         priv->gw_ping.deadline = timeout + 10;  /* the proper termination is enforced by a timer */
8320
8321         if (spawn_ping (self)) {
8322                 priv->gw_ping.watch = g_child_watch_add (priv->gw_ping.pid, ip_check_ping_watch_cb, self);
8323                 priv->gw_ping.timeout = g_timeout_add_seconds (timeout, ip_check_ping_timeout_cb, self);
8324                 return TRUE;
8325         }
8326
8327         ip_check_gw_ping_cleanup (self);
8328         return FALSE;
8329 }
8330
8331 static void
8332 nm_device_start_ip_check (NMDevice *self)
8333 {
8334         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
8335         NMConnection *connection;
8336         NMSettingConnection *s_con;
8337         guint timeout = 0;
8338         const char *ping_binary = NULL;
8339         char buf[INET6_ADDRSTRLEN] = { 0 };
8340         NMLogDomain log_domain = LOGD_IP4;
8341
8342         /* Shouldn't be any active ping here, since IP_CHECK happens after the
8343          * first IP method completes.  Any subsequently completing IP method doesn't
8344          * get checked.
8345          */
8346         g_assert (!priv->gw_ping.watch);
8347         g_assert (!priv->gw_ping.timeout);
8348         g_assert (!priv->gw_ping.pid);
8349         g_assert (priv->ip4_state == IP_DONE || priv->ip6_state == IP_DONE);
8350
8351         connection = nm_device_get_applied_connection (self);
8352         g_assert (connection);
8353
8354         s_con = nm_connection_get_setting_connection (connection);
8355         g_assert (s_con);
8356         timeout = nm_setting_connection_get_gateway_ping_timeout (s_con);
8357
8358         if (timeout) {
8359                 if (priv->ip4_config && priv->ip4_state == IP_DONE) {
8360                         guint gw = 0;
8361
8362                         ping_binary = nm_utils_find_helper ("ping", "/usr/bin/ping", NULL);
8363                         log_domain = LOGD_IP4;
8364
8365                         gw = nm_ip4_config_get_gateway (priv->ip4_config);
8366                         if (gw && !inet_ntop (AF_INET, &gw, buf, sizeof (buf)))
8367                                 buf[0] = '\0';
8368                 } else if (priv->ip6_config && priv->ip6_state == IP_DONE) {
8369                         const struct in6_addr *gw = NULL;
8370
8371                         ping_binary = nm_utils_find_helper ("ping6", "/usr/bin/ping6", NULL);
8372                         log_domain = LOGD_IP6;
8373
8374                         gw = nm_ip6_config_get_gateway (priv->ip6_config);
8375                         if (gw && !inet_ntop (AF_INET6, gw, buf, sizeof (buf)))
8376                                 buf[0] = '\0';
8377                 }
8378         }
8379
8380         if (buf[0])
8381                 start_ping (self, log_domain, ping_binary, buf, timeout);
8382
8383         /* If no ping was started, just advance to pre_up */
8384         if (!priv->gw_ping.pid)
8385                 ip_check_pre_up (self);
8386 }
8387
8388 /****************************************************************/
8389
8390 static gboolean
8391 carrier_wait_timeout (gpointer user_data)
8392 {
8393         NMDevice *self = NM_DEVICE (user_data);
8394
8395         NM_DEVICE_GET_PRIVATE (self)->carrier_wait_id = 0;
8396         nm_device_remove_pending_action (self, "carrier wait", TRUE);
8397
8398         _carrier_wait_check_queued_act_request (self);
8399
8400         return G_SOURCE_REMOVE;
8401 }
8402
8403 static gboolean
8404 nm_device_is_up (NMDevice *self)
8405 {
8406         g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
8407
8408         if (NM_DEVICE_GET_CLASS (self)->is_up)
8409                 return NM_DEVICE_GET_CLASS (self)->is_up (self);
8410
8411         return TRUE;
8412 }
8413
8414 static gboolean
8415 is_up (NMDevice *self)
8416 {
8417         int ifindex = nm_device_get_ip_ifindex (self);
8418
8419         return ifindex > 0 ? nm_platform_link_is_up (NM_PLATFORM_GET, ifindex) : TRUE;
8420 }
8421
8422 gboolean
8423 nm_device_bring_up (NMDevice *self, gboolean block, gboolean *no_firmware)
8424 {
8425         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
8426         gboolean device_is_up = FALSE;
8427
8428         g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
8429
8430         _LOGD (LOGD_HW, "bringing up device");
8431
8432         if (NM_DEVICE_GET_CLASS (self)->bring_up) {
8433                 if (!NM_DEVICE_GET_CLASS (self)->bring_up (self, no_firmware))
8434                         return FALSE;
8435         }
8436
8437         device_is_up = nm_device_is_up (self);
8438         if (block && !device_is_up) {
8439                 int ifindex = nm_device_get_ip_ifindex (self);
8440                 gint64 wait_until = nm_utils_get_monotonic_timestamp_us () + 10000 /* microseconds */;
8441
8442                 do {
8443                         g_usleep (200);
8444                         if (!nm_platform_link_refresh (NM_PLATFORM_GET, ifindex))
8445                                 return FALSE;
8446                         device_is_up = nm_device_is_up (self);
8447                 } while (!device_is_up && nm_utils_get_monotonic_timestamp_us () < wait_until);
8448         }
8449
8450         if (!device_is_up) {
8451                 if (block)
8452                         _LOGW (LOGD_HW, "device not up after timeout!");
8453                 else
8454                         _LOGD (LOGD_HW, "device not up immediately");
8455                 return FALSE;
8456         }
8457
8458         /* Devices that support carrier detect must be IFF_UP to report carrier
8459          * changes; so after setting the device IFF_UP we must suppress startup
8460          * complete (via a pending action) until either the carrier turns on, or
8461          * a timeout is reached.
8462          */
8463         if (nm_device_has_capability (self, NM_DEVICE_CAP_CARRIER_DETECT)) {
8464                 if (!nm_clear_g_source (&priv->carrier_wait_id))
8465                         nm_device_add_pending_action (self, "carrier wait", TRUE);
8466                 priv->carrier_wait_id = g_timeout_add_seconds (5, carrier_wait_timeout, self);
8467         }
8468
8469         /* Can only get HW address of some devices when they are up */
8470         nm_device_update_hw_address (self);
8471
8472         _update_ip4_address (self);
8473         return TRUE;
8474 }
8475
8476 static gboolean
8477 bring_up (NMDevice *self, gboolean *no_firmware)
8478 {
8479         int ifindex = nm_device_get_ip_ifindex (self);
8480         gboolean result;
8481
8482         if (ifindex <= 0) {
8483                 if (no_firmware)
8484                         *no_firmware = FALSE;
8485                 return TRUE;
8486         }
8487
8488         result = nm_platform_link_set_up (NM_PLATFORM_GET, ifindex, no_firmware);
8489
8490         /* Store carrier immediately. */
8491         if (result && nm_device_has_capability (self, NM_DEVICE_CAP_CARRIER_DETECT))
8492                 check_carrier (self);
8493
8494         return result;
8495 }
8496
8497 void
8498 nm_device_take_down (NMDevice *self, gboolean block)
8499 {
8500         gboolean device_is_up;
8501
8502         g_return_if_fail (NM_IS_DEVICE (self));
8503
8504         _LOGD (LOGD_HW, "taking down device");
8505
8506         if (NM_DEVICE_GET_CLASS (self)->take_down) {
8507                 if (!NM_DEVICE_GET_CLASS (self)->take_down (self))
8508                         return;
8509         }
8510
8511         device_is_up = nm_device_is_up (self);
8512         if (block && device_is_up) {
8513                 int ifindex = nm_device_get_ip_ifindex (self);
8514                 gint64 wait_until = nm_utils_get_monotonic_timestamp_us () + 10000 /* microseconds */;
8515
8516                 do {
8517                         g_usleep (200);
8518                         if (!nm_platform_link_refresh (NM_PLATFORM_GET, ifindex))
8519                                 return;
8520                         device_is_up = nm_device_is_up (self);
8521                 } while (device_is_up && nm_utils_get_monotonic_timestamp_us () < wait_until);
8522         }
8523
8524         if (device_is_up) {
8525                 if (block)
8526                         _LOGW (LOGD_HW, "device not down after timeout!");
8527                 else
8528                         _LOGD (LOGD_HW, "device not down immediately");
8529         }
8530 }
8531
8532 static gboolean
8533 take_down (NMDevice *self)
8534 {
8535         int ifindex = nm_device_get_ip_ifindex (self);
8536
8537         if (ifindex > 0)
8538                 return nm_platform_link_set_down (NM_PLATFORM_GET, ifindex);
8539
8540         /* devices without ifindex are always up. */
8541         _LOGD (LOGD_HW, "cannot take down device without ifindex");
8542         return FALSE;
8543 }
8544
8545 void
8546 nm_device_set_firmware_missing (NMDevice *self, gboolean new_missing)
8547 {
8548         NMDevicePrivate *priv;
8549
8550         g_return_if_fail (NM_IS_DEVICE (self));
8551
8552         priv = NM_DEVICE_GET_PRIVATE (self);
8553         if (priv->firmware_missing != new_missing) {
8554                 priv->firmware_missing = new_missing;
8555                 _notify (self, PROP_FIRMWARE_MISSING);
8556         }
8557 }
8558
8559 gboolean
8560 nm_device_get_firmware_missing (NMDevice *self)
8561 {
8562         return NM_DEVICE_GET_PRIVATE (self)->firmware_missing;
8563 }
8564
8565 void
8566 nm_device_set_nm_plugin_missing (NMDevice *self, gboolean new_missing)
8567 {
8568         NMDevicePrivate *priv;
8569
8570         g_return_if_fail (NM_IS_DEVICE (self));
8571
8572         priv = NM_DEVICE_GET_PRIVATE (self);
8573         if (priv->nm_plugin_missing != new_missing) {
8574                 priv->nm_plugin_missing = new_missing;
8575                 _notify (self, PROP_NM_PLUGIN_MISSING);
8576         }
8577 }
8578
8579 gboolean
8580 nm_device_get_nm_plugin_missing (NMDevice *self)
8581 {
8582         return NM_DEVICE_GET_PRIVATE (self)->nm_plugin_missing;
8583 }
8584
8585 static NMIP4Config *
8586 find_ip4_lease_config (NMDevice *self,
8587                        NMConnection *connection,
8588                        NMIP4Config *ext_ip4_config)
8589 {
8590         const char *ip_iface = nm_device_get_ip_iface (self);
8591         int ip_ifindex = nm_device_get_ip_ifindex (self);
8592         GSList *leases, *liter;
8593         NMIP4Config *found = NULL;
8594
8595         g_return_val_if_fail (NM_IS_IP4_CONFIG (ext_ip4_config), NULL);
8596         g_return_val_if_fail (NM_IS_CONNECTION (connection), NULL);
8597
8598         leases = nm_dhcp_manager_get_lease_ip_configs (nm_dhcp_manager_get (),
8599                                                        ip_iface,
8600                                                        ip_ifindex,
8601                                                        nm_connection_get_uuid (connection),
8602                                                        FALSE,
8603                                                        nm_device_get_ip4_route_metric (self));
8604         for (liter = leases; liter && !found; liter = liter->next) {
8605                 NMIP4Config *lease_config = liter->data;
8606                 const NMPlatformIP4Address *address = nm_ip4_config_get_address (lease_config, 0);
8607                 guint32 gateway = nm_ip4_config_get_gateway (lease_config);
8608
8609                 g_assert (address);
8610                 if (!nm_ip4_config_address_exists (ext_ip4_config, address))
8611                         continue;
8612                 if (gateway != nm_ip4_config_get_gateway (ext_ip4_config))
8613                         continue;
8614                 found = g_object_ref (lease_config);
8615         }
8616
8617         g_slist_free_full (leases, g_object_unref);
8618         return found;
8619 }
8620
8621 static void
8622 capture_lease_config (NMDevice *self,
8623                       NMIP4Config *ext_ip4_config,
8624                       NMIP4Config **out_ip4_config,
8625                       NMIP6Config *ext_ip6_config,
8626                       NMIP6Config **out_ip6_config)
8627 {
8628         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
8629         const GSList *connections, *citer;
8630         guint i;
8631         gboolean dhcp_used = FALSE;
8632
8633         /* Ensure at least one address on the device has a non-infinite lifetime,
8634          * otherwise DHCP cannot possibly be active on the device right now.
8635          */
8636         if (ext_ip4_config && out_ip4_config) {
8637                 for (i = 0; i < nm_ip4_config_get_num_addresses (ext_ip4_config); i++) {
8638                         const NMPlatformIP4Address *addr = nm_ip4_config_get_address (ext_ip4_config, i);
8639
8640                         if (addr->lifetime != NM_PLATFORM_LIFETIME_PERMANENT) {
8641                                 dhcp_used = TRUE;
8642                                 break;
8643                         }
8644                 }
8645         } else if (ext_ip6_config && out_ip6_config) {
8646                 for (i = 0; i < nm_ip6_config_get_num_addresses (ext_ip6_config); i++) {
8647                         const NMPlatformIP6Address *addr = nm_ip6_config_get_address (ext_ip6_config, i);
8648
8649                         if (addr->lifetime != NM_PLATFORM_LIFETIME_PERMANENT) {
8650                                 dhcp_used = TRUE;
8651                                 break;
8652                         }
8653                 }
8654         } else {
8655                 g_return_if_fail (   (ext_ip6_config && out_ip6_config)
8656                                   || (ext_ip4_config && out_ip4_config));
8657         }
8658
8659         if (!dhcp_used)
8660                 return;
8661
8662         connections = nm_connection_provider_get_connections (priv->con_provider);
8663         for (citer = connections; citer; citer = citer->next) {
8664                 NMConnection *candidate = citer->data;
8665                 const char *method;
8666
8667                 if (!nm_device_check_connection_compatible (self, candidate))
8668                         continue;
8669
8670                 /* IPv4 leases */
8671                 method = nm_utils_get_ip_config_method (candidate, NM_TYPE_SETTING_IP4_CONFIG);
8672                 if (out_ip4_config && strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO) == 0) {
8673                         *out_ip4_config = find_ip4_lease_config (self, candidate, ext_ip4_config);
8674                         if (*out_ip4_config)
8675                                 return;
8676                 }
8677
8678                 /* IPv6 leases */
8679                 method = nm_utils_get_ip_config_method (candidate, NM_TYPE_SETTING_IP6_CONFIG);
8680                 if (out_ip6_config && strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_AUTO) == 0) {
8681                         /* FIXME: implement find_ip6_lease_config() */
8682                 }
8683         }
8684 }
8685
8686 static void
8687 _ip4_config_intersect (gpointer value, gpointer user_data)
8688 {
8689         NMIP4Config *dst = (NMIP4Config *) value;
8690         NMIP4Config *src = (NMIP4Config *) user_data;
8691
8692         nm_ip4_config_intersect (dst, src);
8693 }
8694
8695 static void
8696 _ip4_config_subtract (gpointer value, gpointer user_data)
8697 {
8698         NMIP4Config *dst = (NMIP4Config *) user_data;
8699         NMIP4Config *src = (NMIP4Config *) value;
8700
8701         nm_ip4_config_subtract (dst, src);
8702 }
8703
8704 static void
8705 update_ip4_config (NMDevice *self, gboolean initial)
8706 {
8707         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
8708         int ifindex;
8709         gboolean capture_resolv_conf;
8710         NMDnsManagerResolvConfMode resolv_conf_mode;
8711
8712         ifindex = nm_device_get_ip_ifindex (self);
8713         if (!ifindex)
8714                 return;
8715
8716         resolv_conf_mode = nm_dns_manager_get_resolv_conf_mode (nm_dns_manager_get ());
8717         capture_resolv_conf = initial && (resolv_conf_mode == NM_DNS_MANAGER_RESOLV_CONF_EXPLICIT);
8718
8719         /* IPv4 */
8720         g_clear_object (&priv->ext_ip4_config);
8721         priv->ext_ip4_config = nm_ip4_config_capture (ifindex, capture_resolv_conf);
8722         if (priv->ext_ip4_config) {
8723                 if (initial) {
8724                         g_clear_object (&priv->dev_ip4_config);
8725                         capture_lease_config (self, priv->ext_ip4_config, &priv->dev_ip4_config, NULL, NULL);
8726                 }
8727
8728                 /* FIXME: ext_ip4_config does not contain routes with source==RTPROT_KERNEL.
8729                  * Hence, we will wrongly remove device-routes with metric=0 if they were added by
8730                  * the user on purpose. This should be fixed by also tracking and exposing
8731                  * kernel routes. */
8732
8733                 /* This function was called upon external changes. Remove the configuration
8734                  * (addresses,routes) that is no longer present externally from the internal
8735                  * config. This way, we don't re-add addresses that were manually removed
8736                  * by the user. */
8737                 if (priv->con_ip4_config)
8738                         nm_ip4_config_intersect (priv->con_ip4_config, priv->ext_ip4_config);
8739                 if (priv->dev_ip4_config)
8740                         nm_ip4_config_intersect (priv->dev_ip4_config, priv->ext_ip4_config);
8741
8742                 g_slist_foreach (priv->vpn4_configs, _ip4_config_intersect, priv->ext_ip4_config);
8743
8744                 if (priv->wwan_ip4_config)
8745                         nm_ip4_config_intersect (priv->wwan_ip4_config, priv->ext_ip4_config);
8746
8747                 /* Remove parts from ext_ip4_config to only contain the information that
8748                  * was configured externally -- we already have the same configuration from
8749                  * internal origins. */
8750                 if (priv->con_ip4_config)
8751                         nm_ip4_config_subtract (priv->ext_ip4_config, priv->con_ip4_config);
8752                 if (priv->dev_ip4_config)
8753                         nm_ip4_config_subtract (priv->ext_ip4_config, priv->dev_ip4_config);
8754
8755                 g_slist_foreach (priv->vpn4_configs, _ip4_config_subtract, priv->ext_ip4_config);
8756
8757                 if (priv->wwan_ip4_config)
8758                         nm_ip4_config_subtract (priv->ext_ip4_config, priv->wwan_ip4_config);
8759
8760                 ip4_config_merge_and_apply (self, NULL, FALSE, NULL);
8761         }
8762 }
8763
8764 static void
8765 _ip6_config_intersect (gpointer value, gpointer user_data)
8766 {
8767         NMIP6Config *dst = (NMIP6Config *) value;
8768         NMIP6Config *src = (NMIP6Config *) user_data;
8769
8770         nm_ip6_config_intersect (dst, src);
8771 }
8772
8773 static void
8774 _ip6_config_subtract (gpointer value, gpointer user_data)
8775 {
8776         NMIP6Config *dst = (NMIP6Config *) user_data;
8777         NMIP6Config *src = (NMIP6Config *) value;
8778
8779         nm_ip6_config_subtract (dst, src);
8780 }
8781
8782 static void
8783 update_ip6_config (NMDevice *self, gboolean initial)
8784 {
8785         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
8786         int ifindex;
8787         gboolean capture_resolv_conf;
8788         NMDnsManagerResolvConfMode resolv_conf_mode;
8789
8790         ifindex = nm_device_get_ip_ifindex (self);
8791         if (!ifindex)
8792                 return;
8793
8794         resolv_conf_mode = nm_dns_manager_get_resolv_conf_mode (nm_dns_manager_get ());
8795         capture_resolv_conf = initial && (resolv_conf_mode == NM_DNS_MANAGER_RESOLV_CONF_EXPLICIT);
8796
8797         /* IPv6 */
8798         g_clear_object (&priv->ext_ip6_config);
8799         g_clear_object (&priv->ext_ip6_config_captured);
8800         priv->ext_ip6_config_captured = nm_ip6_config_capture (ifindex, capture_resolv_conf, NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN);
8801         if (priv->ext_ip6_config_captured) {
8802
8803                 priv->ext_ip6_config = nm_ip6_config_new_cloned (priv->ext_ip6_config_captured);
8804
8805                 /* This function was called upon external changes. Remove the configuration
8806                  * (addresses,routes) that is no longer present externally from the internal
8807                  * config. This way, we don't re-add addresses that were manually removed
8808                  * by the user. */
8809                 if (priv->con_ip6_config)
8810                         nm_ip6_config_intersect (priv->con_ip6_config, priv->ext_ip6_config);
8811                 if (priv->ac_ip6_config)
8812                         nm_ip6_config_intersect (priv->ac_ip6_config, priv->ext_ip6_config);
8813                 if (priv->dhcp6_ip6_config)
8814                         nm_ip6_config_intersect (priv->dhcp6_ip6_config, priv->ext_ip6_config);
8815                 if (priv->wwan_ip6_config)
8816                         nm_ip6_config_intersect (priv->wwan_ip6_config, priv->ext_ip6_config);
8817                 g_slist_foreach (priv->vpn6_configs, _ip6_config_intersect, priv->ext_ip6_config);
8818
8819                 /* Remove parts from ext_ip6_config to only contain the information that
8820                  * was configured externally -- we already have the same configuration from
8821                  * internal origins. */
8822                 if (priv->con_ip6_config)
8823                         nm_ip6_config_subtract (priv->ext_ip6_config, priv->con_ip6_config);
8824                 if (priv->ac_ip6_config)
8825                         nm_ip6_config_subtract (priv->ext_ip6_config, priv->ac_ip6_config);
8826                 if (priv->dhcp6_ip6_config)
8827                         nm_ip6_config_subtract (priv->ext_ip6_config, priv->dhcp6_ip6_config);
8828                 if (priv->wwan_ip6_config)
8829                         nm_ip6_config_subtract (priv->ext_ip6_config, priv->wwan_ip6_config);
8830                 g_slist_foreach (priv->vpn6_configs, _ip6_config_subtract, priv->ext_ip6_config);
8831
8832                 ip6_config_merge_and_apply (self, FALSE, NULL);
8833         }
8834
8835         if (   priv->linklocal6_timeout_id
8836             && priv->ext_ip6_config_captured
8837             && nm_ip6_config_get_address_first_nontentative (priv->ext_ip6_config_captured, TRUE)) {
8838                 /* linklocal6 is ready now, do the state transition... we are also
8839                  * invoked as g_idle_add, so no problems with reentrance doing it now.
8840                  */
8841                 linklocal6_complete (self);
8842         }
8843 }
8844
8845 void
8846 nm_device_capture_initial_config (NMDevice *self)
8847 {
8848         update_ip4_config (self, TRUE);
8849         update_ip6_config (self, TRUE);
8850 }
8851
8852 static gboolean
8853 queued_ip4_config_change (gpointer user_data)
8854 {
8855         NMDevice *self = NM_DEVICE (user_data);
8856         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
8857
8858         /* Wait for any queued state changes */
8859         if (priv->queued_state.id)
8860                 return TRUE;
8861
8862         priv->queued_ip4_config_id = 0;
8863         g_object_ref (self);
8864         update_ip4_config (self, FALSE);
8865         g_object_unref (self);
8866
8867         return FALSE;
8868 }
8869
8870 static gboolean
8871 queued_ip6_config_change (gpointer user_data)
8872 {
8873         NMDevice *self = NM_DEVICE (user_data);
8874         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
8875         GSList *iter;
8876         gboolean need_ipv6ll = FALSE;
8877
8878         /* Wait for any queued state changes */
8879         if (priv->queued_state.id)
8880                 return TRUE;
8881
8882         priv->queued_ip6_config_id = 0;
8883         g_object_ref (self);
8884         update_ip6_config (self, FALSE);
8885
8886         if (   nm_platform_link_get (NM_PLATFORM_GET, priv->ifindex)
8887             && priv->state < NM_DEVICE_STATE_DEACTIVATING) {
8888                 /* Handle DAD falures */
8889                 for (iter = priv->dad6_failed_addrs; iter; iter = g_slist_next (iter)) {
8890                         NMPlatformIP6Address *addr = iter->data;
8891
8892                         if (addr->source >= NM_IP_CONFIG_SOURCE_USER)
8893                                 continue;
8894
8895                         _LOGI (LOGD_IP6, "ipv6: duplicate address check failed for the %s address",
8896                                nm_platform_ip6_address_to_string (addr, NULL, 0));
8897
8898                         if (IN6_IS_ADDR_LINKLOCAL (&addr->address))
8899                                 need_ipv6ll = TRUE;
8900                         else if (priv->rdisc)
8901                                 nm_rdisc_dad_failed (priv->rdisc, &addr->address);
8902                 }
8903
8904                 /* If no IPv6 link-local address exists but other addresses do then we
8905                  * must add the LL address to remain conformant with RFC 3513 chapter 2.1
8906                  * ("Addressing Model"): "All interfaces are required to have at least
8907                  * one link-local unicast address".
8908                  */
8909                 if (priv->ip6_config && nm_ip6_config_get_num_addresses (priv->ip6_config))
8910                         need_ipv6ll = TRUE;
8911
8912                 if (need_ipv6ll)
8913                         check_and_add_ipv6ll_addr (self);
8914         }
8915
8916         g_slist_free_full (priv->dad6_failed_addrs, g_free);
8917         priv->dad6_failed_addrs = NULL;
8918
8919         g_object_unref (self);
8920
8921         return FALSE;
8922 }
8923
8924 static void
8925 device_ipx_changed (NMPlatform *platform,
8926                     NMPObjectType obj_type,
8927                     int ifindex,
8928                     gpointer platform_object,
8929                     NMPlatformSignalChangeType change_type,
8930                     NMDevice *self)
8931 {
8932         NMDevicePrivate *priv;
8933         NMPlatformIP6Address *addr;
8934
8935         if (nm_device_get_ip_ifindex (self) != ifindex)
8936                 return;
8937
8938         priv = NM_DEVICE_GET_PRIVATE (self);
8939
8940         switch (obj_type) {
8941         case NMP_OBJECT_TYPE_IP4_ADDRESS:
8942         case NMP_OBJECT_TYPE_IP4_ROUTE:
8943                 if (!priv->queued_ip4_config_id) {
8944                         priv->queued_ip4_config_id = g_idle_add (queued_ip4_config_change, self);
8945                         _LOGD (LOGD_DEVICE, "queued IP4 config change");
8946                 }
8947                 break;
8948         case NMP_OBJECT_TYPE_IP6_ADDRESS:
8949                 addr = platform_object;
8950
8951                 if (   priv->state > NM_DEVICE_STATE_DISCONNECTED
8952                     && priv->state < NM_DEVICE_STATE_DEACTIVATING
8953                     && (   (change_type == NM_PLATFORM_SIGNAL_CHANGED && addr->n_ifa_flags & IFA_F_DADFAILED)
8954                         || (change_type == NM_PLATFORM_SIGNAL_REMOVED && addr->n_ifa_flags & IFA_F_TENTATIVE))) {
8955                         priv->dad6_failed_addrs = g_slist_append (priv->dad6_failed_addrs,
8956                                                                   g_memdup (addr, sizeof (NMPlatformIP6Address)));
8957                 }
8958                 /* fallthrough */
8959         case NMP_OBJECT_TYPE_IP6_ROUTE:
8960                 if (!priv->queued_ip6_config_id) {
8961                         priv->queued_ip6_config_id = g_idle_add (queued_ip6_config_change, self);
8962                         _LOGD (LOGD_DEVICE, "queued IP6 config change");
8963                 }
8964                 break;
8965         default:
8966                 g_return_if_reached ();
8967         }
8968 }
8969
8970 /*****************************************************************************/
8971
8972 NM_UTILS_FLAGS2STR_DEFINE (nm_unmanaged_flags2str, NMUnmanagedFlags,
8973         NM_UTILS_FLAGS2STR (NM_UNMANAGED_SLEEPING, "sleeping"),
8974         NM_UTILS_FLAGS2STR (NM_UNMANAGED_QUITTING, "quitting"),
8975         NM_UTILS_FLAGS2STR (NM_UNMANAGED_PARENT, "parent"),
8976         NM_UTILS_FLAGS2STR (NM_UNMANAGED_LOOPBACK, "loopback"),
8977         NM_UTILS_FLAGS2STR (NM_UNMANAGED_PLATFORM_INIT, "platform-init"),
8978         NM_UTILS_FLAGS2STR (NM_UNMANAGED_USER_EXPLICIT, "user-explicit"),
8979         NM_UTILS_FLAGS2STR (NM_UNMANAGED_BY_DEFAULT, "by-default"),
8980         NM_UTILS_FLAGS2STR (NM_UNMANAGED_USER_SETTINGS, "user-settings"),
8981         NM_UTILS_FLAGS2STR (NM_UNMANAGED_USER_UDEV, "user-udev"),
8982         NM_UTILS_FLAGS2STR (NM_UNMANAGED_EXTERNAL_DOWN, "external-down"),
8983         NM_UTILS_FLAGS2STR (NM_UNMANAGED_IS_SLAVE, "is-slave"),
8984 );
8985
8986 static const char *
8987 _unmanaged_flags2str (NMUnmanagedFlags flags, NMUnmanagedFlags mask, char *buf, gsize len)
8988 {
8989         char buf2[512];
8990         char *b;
8991         char *tmp, *tmp2;
8992         gsize l;
8993
8994         nm_utils_to_string_buffer_init (&buf, &len);
8995         if (!len)
8996                 return buf;
8997
8998         b = buf;
8999
9000         mask |= flags;
9001
9002         nm_unmanaged_flags2str (flags, b, len);
9003         l = strlen (b);
9004         b += l;
9005         len -= l;
9006
9007         nm_unmanaged_flags2str (mask & ~flags, buf2, sizeof (buf2));
9008         if (buf2[0]) {
9009                 gboolean add_separator = l > 0;
9010
9011                 tmp = buf2;
9012                 while (TRUE) {
9013                         if (add_separator)
9014                                 nm_utils_strbuf_append_c (&b, &len, ',');
9015                         add_separator = TRUE;
9016
9017                         tmp2 = strchr (tmp, ',');
9018                         if (tmp2)
9019                                 tmp2[0] = '\0';
9020
9021                         nm_utils_strbuf_append_c (&b, &len, '!');
9022                         nm_utils_strbuf_append_str (&b, &len, tmp);
9023                         if (!tmp2)
9024                                 break;
9025
9026                         tmp = &tmp2[1];
9027                 }
9028         }
9029
9030         return buf;
9031 }
9032
9033 static gboolean
9034 _get_managed_by_flags(NMUnmanagedFlags flags, NMUnmanagedFlags mask, gboolean for_user_request)
9035 {
9036         /* Evaluate the managed state based on the unmanaged flags.
9037          *
9038          * Some flags are authoritative, meaning they always cause
9039          * the device to be unmanaged (e.g. @NM_UNMANAGED_PLATFORM_INIT).
9040          *
9041          * OTOH, some flags can be overwritten. For example NM_UNMANAGED_USER_SETTINGS
9042          * is ignored once NM_UNMANAGED_USER_EXPLICIT is set. The idea is that
9043          * the flag from the configuration has no effect once the user explicitly
9044          * touches the unmanaged flags. */
9045
9046         if (for_user_request) {
9047
9048                 /* @for_user_request can make the result only ~more~ managed.
9049                  * If the flags already indicate a managed state for a non-user-request,
9050                  * then it is also managed for an explict user-request.
9051                  *
9052                  * Effectively, this check is redundant, as the code below already
9053                  * already ensures that. Still, express this invariant explictly here. */
9054                 if (_get_managed_by_flags (flags, mask, FALSE))
9055                         return TRUE;
9056
9057                 /* A for-user-request, is effectively the same as pretending
9058                  * that user-dbus flag is cleared. */
9059                 mask |= NM_UNMANAGED_USER_EXPLICIT;
9060                 flags &= ~NM_UNMANAGED_USER_EXPLICIT;
9061         }
9062
9063         if (   NM_FLAGS_ANY (mask, NM_UNMANAGED_USER_SETTINGS)
9064             && !NM_FLAGS_ANY (flags, NM_UNMANAGED_USER_SETTINGS)) {
9065                 /* NM_UNMANAGED_USER_SETTINGS can only explicitly unmanage a device. It cannot
9066                  * *manage* it. Having NM_UNMANAGED_USER_SETTINGS explicitly not set, is the
9067                  * same as having it not set at all. */
9068                 mask &= ~NM_UNMANAGED_USER_SETTINGS;
9069         }
9070
9071         if (NM_FLAGS_ANY (mask, NM_UNMANAGED_USER_UDEV)) {
9072                 /* configuration from udev or nm-config overwrites the by-default flag
9073                  * which is based on the device type. */
9074                 flags &= ~NM_UNMANAGED_BY_DEFAULT;
9075         }
9076
9077         if (   NM_FLAGS_HAS (mask, NM_UNMANAGED_IS_SLAVE)
9078             && !NM_FLAGS_HAS (flags, NM_UNMANAGED_IS_SLAVE)) {
9079                 /* for an enslaved device, by-default doesn't matter */
9080                 flags &= ~NM_UNMANAGED_BY_DEFAULT;
9081         }
9082
9083         if (NM_FLAGS_HAS (mask, NM_UNMANAGED_USER_EXPLICIT)) {
9084                 /* if the device is managed by user-decision, certain other flags
9085                  * are ignored. */
9086
9087                 flags &= ~(  NM_UNMANAGED_BY_DEFAULT
9088                            | NM_UNMANAGED_USER_UDEV
9089                            | NM_UNMANAGED_EXTERNAL_DOWN);
9090         }
9091
9092         return flags == NM_UNMANAGED_NONE;
9093 }
9094
9095 /**
9096  * nm_device_get_managed:
9097  * @self: the #NMDevice
9098  * @for_user_request: whether to check the flags for an explict user-request
9099  *
9100  * Whether the device is unmanaged according to the unmanaged flags.
9101  *
9102  * Returns: %TRUE if the device is unmanaged because of the flags.
9103  */
9104 gboolean
9105 nm_device_get_managed (NMDevice *self, gboolean for_user_request)
9106 {
9107         NMDevicePrivate *priv;
9108
9109         g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
9110
9111         if (!nm_device_is_real (self)) {
9112                 /* a unrealized device is always considered unmanaged. */
9113                 return FALSE;
9114         }
9115
9116         priv = NM_DEVICE_GET_PRIVATE (self);
9117
9118         return _get_managed_by_flags (priv->unmanaged_flags, priv->unmanaged_mask, for_user_request);
9119 }
9120
9121 /**
9122  * nm_device_get_unmanaged_flags:
9123  * @self: the #NMDevice
9124  * @flag: the unmanaged flags to check.
9125  *
9126  * Return the unmanaged flags of the device.
9127  *
9128  * Returns: the flags of the device ( & @flag)
9129  */
9130 NMUnmanagedFlags
9131 nm_device_get_unmanaged_flags (NMDevice *self, NMUnmanagedFlags flag)
9132 {
9133         g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
9134         g_return_val_if_fail (flag != NM_UNMANAGED_NONE, FALSE);
9135
9136         return NM_DEVICE_GET_PRIVATE (self)->unmanaged_flags & flag;
9137 }
9138
9139 /**
9140  * _set_unmanaged_flags:
9141  * @self: the #NMDevice instance
9142  * @flags: which #NMUnmanagedFlags to set.
9143  * @set_op: whether to set/clear/forget the flags. You can also pass
9144  *   boolean values %TRUE and %FALSE, which mean %NM_UNMAN_FLAG_OP_SET_UNMANAGED
9145  *   and %NM_UNMAN_FLAG_OP_SET_MANAGED, respectively.
9146  * @allow_state_transition: if %FALSE, setting flags never triggers a device
9147  *   state change. If %TRUE, the device can change state, if it is real and
9148  *   switches from managed to unmanaged (or vice versa).
9149  * @reason: the device state reason passed to nm_device_state_changed() if
9150  *   the device becomes managed/unmanaged. This is only relevant if the
9151  *   device switches state and if @allow_state_transition is %TRUE.
9152  *
9153  * Set the unmanaged flags of the device.
9154  **/
9155 static void
9156 _set_unmanaged_flags (NMDevice *self,
9157                       NMUnmanagedFlags flags,
9158                       NMUnmanFlagOp set_op,
9159                       gboolean allow_state_transition,
9160                       NMDeviceStateReason reason)
9161 {
9162         NMDevicePrivate *priv;
9163         gboolean was_managed, transition_state;
9164         NMUnmanagedFlags old_flags, old_mask;
9165         const char *operation = NULL;
9166         char str1[512];
9167         char str2[512];
9168
9169         g_return_if_fail (NM_IS_DEVICE (self));
9170         g_return_if_fail (flags);
9171
9172         priv = NM_DEVICE_GET_PRIVATE (self);
9173
9174         if (!priv->real)
9175                 allow_state_transition = FALSE;
9176         was_managed = allow_state_transition && nm_device_get_managed (self, FALSE);
9177
9178         old_flags = priv->unmanaged_flags;
9179         old_mask = priv->unmanaged_mask;
9180
9181         switch (set_op) {
9182         case NM_UNMAN_FLAG_OP_FORGET:
9183                 priv->unmanaged_mask &= ~flags;
9184                 priv->unmanaged_flags &= ~flags;
9185                 operation = "forget";
9186                 break;
9187         case NM_UNMAN_FLAG_OP_SET_UNMANAGED:
9188                 priv->unmanaged_mask |= flags;
9189                 priv->unmanaged_flags |= flags;
9190                 operation = "set-unmanaged";
9191                 break;
9192         case NM_UNMAN_FLAG_OP_SET_MANAGED:
9193                 priv->unmanaged_mask |= flags;
9194                 priv->unmanaged_flags &= ~flags;
9195                 operation = "set-managed";
9196                 break;
9197         default:
9198                 g_return_if_reached ();
9199         }
9200
9201         if (   old_flags == priv->unmanaged_flags
9202             && old_mask == priv->unmanaged_mask)
9203                 return;
9204
9205         transition_state =    allow_state_transition
9206                            && was_managed != nm_device_get_managed (self, FALSE)
9207                            && (   was_managed
9208                                || (   !was_managed
9209                                    && nm_device_get_state (self) == NM_DEVICE_STATE_UNMANAGED));
9210
9211 #define _FMTX "[%s%s0x%0x/0x%x/%s"
9212 #define _FMT(flags, mask, str) \
9213         _unmanaged_flags2str ((flags), (mask), str, sizeof (str)), \
9214         ((flags) | (mask)) ? "=" : "", \
9215         (flags), \
9216         (mask), \
9217         (_get_managed_by_flags (flags, mask, FALSE) \
9218              ? "managed" \
9219              : (_get_managed_by_flags (flags, mask, TRUE) \
9220                     ? "manageable" \
9221                     : "unmanaged"))
9222         _LOGD (LOGD_DEVICE, "unmanaged: flags set to "_FMTX"%s, %s [%s=0x%0x]%s%s%s)",
9223                _FMT (priv->unmanaged_flags, priv->unmanaged_mask, str1),
9224                priv->real ? "" : "/unrealized",
9225                operation,
9226                nm_unmanaged_flags2str (flags, str2, sizeof (str2)),
9227                flags,
9228                NM_PRINT_FMT_QUOTED (allow_state_transition,
9229                                     ", reason ",
9230                                     reason_to_string (reason),
9231                                     transition_state ? ", transition-state" : "",
9232                                     ""));
9233 #undef _FMT
9234
9235         if (transition_state) {
9236                 if (was_managed)
9237                         nm_device_state_changed (self, NM_DEVICE_STATE_UNMANAGED, reason);
9238                 else
9239                         nm_device_state_changed (self, NM_DEVICE_STATE_UNAVAILABLE, reason);
9240         }
9241 }
9242
9243 /**
9244  * @self: the #NMDevice instance
9245  * @flags: which #NMUnmanagedFlags to set.
9246  * @set_op: whether to set/clear/forget the flags. You can also pass
9247  *   boolean values %TRUE and %FALSE, which mean %NM_UNMAN_FLAG_OP_SET_UNMANAGED
9248  *   and %NM_UNMAN_FLAG_OP_SET_MANAGED, respectively.
9249  *
9250  * Set the unmanaged flags of the device (does not trigger a state change).
9251  **/
9252 void
9253 nm_device_set_unmanaged_flags (NMDevice *self,
9254                                NMUnmanagedFlags flags,
9255                                NMUnmanFlagOp set_op)
9256 {
9257         _set_unmanaged_flags (self, flags, set_op, FALSE, NM_DEVICE_STATE_REASON_NONE);
9258 }
9259
9260 /**
9261  * nm_device_set_unmanaged_by_flags:
9262  * @self: the #NMDevice instance
9263  * @flags: which #NMUnmanagedFlags to set.
9264  * @set_op: whether to set/clear/forget the flags. You can also pass
9265  *   boolean values %TRUE and %FALSE, which mean %NM_UNMAN_FLAG_OP_SET_UNMANAGED
9266  *   and %NM_UNMAN_FLAG_OP_SET_MANAGED, respectively.
9267  * @reason: the device state reason passed to nm_device_state_changed() if
9268  *   the device becomes managed/unmanaged.
9269  *
9270  * Set the unmanaged flags of the device and possibly trigger a state change.
9271  **/
9272 void
9273 nm_device_set_unmanaged_by_flags (NMDevice *self,
9274                                   NMUnmanagedFlags flags,
9275                                   NMUnmanFlagOp set_op,
9276                                   NMDeviceStateReason reason)
9277 {
9278         _set_unmanaged_flags (self, flags, set_op, TRUE, reason);
9279 }
9280
9281 void
9282 nm_device_set_unmanaged_by_user_config (NMDevice *self, const GSList *unmanaged_specs)
9283 {
9284         NMDevicePrivate *priv;
9285         gboolean unmanaged;
9286
9287         g_return_if_fail (NM_IS_DEVICE (self));
9288
9289         priv = NM_DEVICE_GET_PRIVATE (self);
9290
9291         unmanaged = nm_device_spec_match_list (self, unmanaged_specs);
9292
9293         nm_device_set_unmanaged_by_flags (self,
9294                                           NM_UNMANAGED_USER_SETTINGS,
9295                                           unmanaged,
9296                                           unmanaged
9297                                               ? NM_DEVICE_STATE_REASON_NOW_UNMANAGED
9298                                               : NM_DEVICE_STATE_REASON_NOW_MANAGED);
9299 }
9300
9301 void
9302 nm_device_set_unmanaged_by_user_udev (NMDevice *self)
9303 {
9304         int ifindex;
9305         gboolean platform_unmanaged = FALSE;
9306
9307         ifindex = self->priv->ifindex;
9308
9309         if (   ifindex <= 0
9310             || !nm_platform_link_get_unmanaged (NM_PLATFORM_GET, ifindex, &platform_unmanaged))
9311                 return;
9312
9313         nm_device_set_unmanaged_by_flags (self,
9314                                           NM_UNMANAGED_USER_UDEV,
9315                                           platform_unmanaged,
9316                                           NM_DEVICE_STATE_REASON_USER_REQUESTED);
9317 }
9318
9319 void
9320 nm_device_set_unmanaged_by_quitting (NMDevice *self)
9321 {
9322         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
9323         gboolean need_deactivate = nm_device_is_activating (self) ||
9324                                    priv->state == NM_DEVICE_STATE_ACTIVATED;
9325
9326         /* It's OK to block here because we're quitting */
9327         if (need_deactivate)
9328                 _set_state_full (self, NM_DEVICE_STATE_DEACTIVATING, NM_DEVICE_STATE_REASON_NOW_UNMANAGED, TRUE);
9329
9330         nm_device_set_unmanaged_by_flags (self,
9331                                           NM_UNMANAGED_QUITTING,
9332                                           TRUE,
9333                                           need_deactivate ? NM_DEVICE_STATE_REASON_REMOVED
9334                                                           : NM_DEVICE_STATE_REASON_NOW_UNMANAGED);
9335 }
9336
9337 /*****************************************************************************/
9338
9339 void
9340 nm_device_set_dhcp_timeout (NMDevice *self, guint32 timeout)
9341 {
9342         g_return_if_fail (NM_IS_DEVICE (self));
9343
9344         NM_DEVICE_GET_PRIVATE (self)->dhcp_timeout = timeout;
9345 }
9346
9347 void
9348 nm_device_set_dhcp_anycast_address (NMDevice *self, const char *addr)
9349 {
9350         NMDevicePrivate *priv;
9351
9352         g_return_if_fail (NM_IS_DEVICE (self));
9353         g_return_if_fail (!addr || nm_utils_hwaddr_valid (addr, ETH_ALEN));
9354
9355         priv = NM_DEVICE_GET_PRIVATE (self);
9356
9357         g_free (priv->dhcp_anycast_address);
9358         priv->dhcp_anycast_address = g_strdup (addr);
9359 }
9360
9361 void
9362 nm_device_reapply_settings_immediately (NMDevice *self)
9363 {
9364         NMConnection *applied_connection;
9365         NMSettingsConnection *settings_connection;
9366         NMDeviceState state;
9367         NMSettingConnection *s_con_settings;
9368         NMSettingConnection *s_con_applied;
9369         const char *zone;
9370         NMMetered metered;
9371         guint64 version_id;
9372
9373         g_return_if_fail (NM_IS_DEVICE (self));
9374
9375         state = nm_device_get_state (self);
9376         if (   state <= NM_DEVICE_STATE_DISCONNECTED
9377             || state > NM_DEVICE_STATE_ACTIVATED)
9378                 return;
9379
9380         applied_connection = nm_device_get_applied_connection (self);
9381         settings_connection = nm_device_get_settings_connection (self);
9382
9383         if (!nm_settings_connection_has_unmodified_applied_connection (settings_connection,
9384                                                                        applied_connection,
9385                                                                        NM_SETTING_COMPARE_FLAG_IGNORE_REAPPLY_IMMEDIATELY))
9386                 return;
9387
9388         s_con_settings = nm_connection_get_setting_connection ((NMConnection *) settings_connection);
9389         s_con_applied = nm_connection_get_setting_connection (applied_connection);
9390
9391         if (g_strcmp0 ((zone = nm_setting_connection_get_zone (s_con_settings)),
9392                        nm_setting_connection_get_zone (s_con_applied)) != 0) {
9393
9394                 version_id = nm_active_connection_version_id_bump ((NMActiveConnection *) self->priv->act_request);
9395                 _LOGD (LOGD_DEVICE, "reapply setting: zone = %s%s%s (version-id %llu)", NM_PRINT_FMT_QUOTE_STRING (zone), (long long unsigned) version_id);
9396
9397                 g_object_set (G_OBJECT (s_con_applied),
9398                               NM_SETTING_CONNECTION_ZONE, zone,
9399                               NULL);
9400
9401                 nm_device_update_firewall_zone (self);
9402         }
9403
9404         if ((metered = nm_setting_connection_get_metered (s_con_settings)) != nm_setting_connection_get_metered (s_con_applied)) {
9405
9406                 version_id = nm_active_connection_version_id_bump ((NMActiveConnection *) self->priv->act_request);
9407                 _LOGD (LOGD_DEVICE, "reapply setting: metered = %d (version-id %llu)", (int) metered, (long long unsigned) version_id);
9408
9409                 g_object_set (G_OBJECT (s_con_applied),
9410                               NM_SETTING_CONNECTION_METERED, metered,
9411                               NULL);
9412
9413                 nm_device_update_metered (self);
9414         }
9415 }
9416
9417 void
9418 nm_device_update_firewall_zone (NMDevice *self)
9419 {
9420         NMConnection *applied_connection;
9421         NMSettingConnection *s_con;
9422
9423         g_return_if_fail (NM_IS_DEVICE (self));
9424
9425         applied_connection = nm_device_get_applied_connection (self);
9426         if (!applied_connection)
9427                 return;
9428
9429         s_con = nm_connection_get_setting_connection (applied_connection);
9430         if (    nm_device_get_state (self) == NM_DEVICE_STATE_ACTIVATED
9431             && !nm_device_uses_assumed_connection (self)) {
9432                 nm_firewall_manager_add_or_change_zone (nm_firewall_manager_get (),
9433                                                         nm_device_get_ip_iface (self),
9434                                                         nm_setting_connection_get_zone (s_con),
9435                                                         FALSE, /* change zone */
9436                                                         NULL,
9437                                                         NULL);
9438         }
9439 }
9440
9441 void
9442 nm_device_update_metered (NMDevice *self)
9443 {
9444 #define NM_METERED_INVALID ((NMMetered) -1)
9445         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
9446         NMSettingConnection *setting;
9447         NMMetered conn_value, value = NM_METERED_INVALID;
9448         NMConnection *connection = NULL;
9449         NMDeviceState state;
9450
9451         g_return_if_fail (NM_IS_DEVICE (self));
9452
9453         state = nm_device_get_state (self);
9454         if (   state <= NM_DEVICE_STATE_DISCONNECTED
9455             || state > NM_DEVICE_STATE_ACTIVATED)
9456                 value = NM_METERED_UNKNOWN;
9457
9458         if (value == NM_METERED_INVALID) {
9459                 connection = nm_device_get_applied_connection (self);
9460                 if (connection) {
9461                         setting = nm_connection_get_setting_connection (connection);
9462                         if (setting) {
9463                                 conn_value = nm_setting_connection_get_metered (setting);
9464                                 if (conn_value != NM_METERED_UNKNOWN)
9465                                         value = conn_value;
9466                         }
9467                 }
9468         }
9469
9470         /* Try to guess a value using the metered flag in IP configuration */
9471         if (value == NM_METERED_INVALID) {
9472                 if (   priv->ip4_config
9473                     && priv->ip4_state == IP_DONE
9474                     && nm_ip4_config_get_metered (priv->ip4_config))
9475                         value = NM_METERED_GUESS_YES;
9476         }
9477
9478         /* Otherwise look at connection type */
9479         if (value == NM_METERED_INVALID) {
9480                 if (   nm_connection_is_type (connection, NM_SETTING_GSM_SETTING_NAME)
9481                     || nm_connection_is_type (connection, NM_SETTING_CDMA_SETTING_NAME))
9482                         value = NM_METERED_GUESS_YES;
9483                 else
9484                         value = NM_METERED_GUESS_NO;
9485         }
9486
9487         if (value != priv->metered) {
9488                 _LOGD (LOGD_DEVICE, "set metered value %d", value);
9489                 priv->metered = value;
9490                 _notify (self, PROP_METERED);
9491         }
9492 }
9493
9494 static gboolean
9495 _nm_device_check_connection_available (NMDevice *self,
9496                                        NMConnection *connection,
9497                                        NMDeviceCheckConAvailableFlags flags,
9498                                        const char *specific_object)
9499 {
9500         NMDeviceState state;
9501
9502         /* an unrealized software device is always available, hardware devices never. */
9503         if (!nm_device_is_real (self)) {
9504                 if (nm_device_is_software (self))
9505                         return nm_device_check_connection_compatible (self, connection);
9506                 return FALSE;
9507         }
9508
9509         state = nm_device_get_state (self);
9510         if (state < NM_DEVICE_STATE_UNMANAGED)
9511                 return FALSE;
9512         if (   state < NM_DEVICE_STATE_UNAVAILABLE
9513             && (   (   !NM_FLAGS_ANY (flags, NM_DEVICE_CHECK_CON_AVAILABLE_FOR_USER_REQUEST)
9514                     && !nm_device_get_managed (self, FALSE))
9515                 || (    NM_FLAGS_ANY (flags, NM_DEVICE_CHECK_CON_AVAILABLE_FOR_USER_REQUEST)
9516                     && !nm_device_get_managed (self, TRUE))))
9517                 return FALSE;
9518         if (   state < NM_DEVICE_STATE_DISCONNECTED
9519             && !nm_device_is_software (self)
9520             && (   (   !NM_FLAGS_ANY (flags, NM_DEVICE_CHECK_CON_AVAILABLE_FOR_USER_REQUEST)
9521                     && !nm_device_is_available (self, NM_DEVICE_CHECK_DEV_AVAILABLE_NONE))
9522                 || (    NM_FLAGS_ANY (flags, NM_DEVICE_CHECK_CON_AVAILABLE_FOR_USER_REQUEST)
9523                     && !nm_device_is_available (self, NM_DEVICE_CHECK_DEV_AVAILABLE_FOR_USER_REQUEST))))
9524                 return FALSE;
9525
9526         if (!nm_device_check_connection_compatible (self, connection))
9527                 return FALSE;
9528
9529         return NM_DEVICE_GET_CLASS (self)->check_connection_available (self, connection, flags, specific_object);
9530 }
9531
9532 /**
9533  * nm_device_check_connection_available():
9534  * @self: the #NMDevice
9535  * @connection: the #NMConnection to check for availability
9536  * @flags: flags to affect the decision making of whether a connection
9537  *   is available. Adding a flag can only make a connection more available,
9538  *   not less.
9539  * @specific_object: a device type dependent argument to further
9540  *   filter the result. Passing a non %NULL specific object can only reduce
9541  *   the availability of a connection.
9542  *
9543  * Check if @connection is available to be activated on @self.
9544  *
9545  * Returns: %TRUE if @connection can be activated on @self
9546  */
9547 gboolean
9548 nm_device_check_connection_available (NMDevice *self,
9549                                       NMConnection *connection,
9550                                       NMDeviceCheckConAvailableFlags flags,
9551                                       const char *specific_object)
9552 {
9553         gboolean available;
9554
9555         available = _nm_device_check_connection_available (self, connection, flags, specific_object);
9556
9557 #if NM_MORE_ASSERTS >= 2
9558         {
9559                 /* The meaning of the flags is so that *adding* a flag relaxes a condition, thus making
9560                  * the device *more* available. Assert against that requirement by testing all the flags. */
9561                 NMDeviceCheckConAvailableFlags i, j, k;
9562                 gboolean available_all[NM_DEVICE_CHECK_CON_AVAILABLE_ALL + 1] = { FALSE };
9563
9564                 for (i = 0; i <= NM_DEVICE_CHECK_CON_AVAILABLE_ALL; i++)
9565                         available_all[i] = _nm_device_check_connection_available (self, connection, i, specific_object);
9566
9567                 for (i = 0; i <= NM_DEVICE_CHECK_CON_AVAILABLE_ALL; i++) {
9568                         for (j = 1; j <= NM_DEVICE_CHECK_CON_AVAILABLE_ALL; j <<= 1) {
9569                                 if (NM_FLAGS_HAS (i, j)) {
9570                                         k = i & ~j;
9571                                         nm_assert (   available_all[i] == available_all[k]
9572                                                    || available_all[i]);
9573                                 }
9574                         }
9575                 }
9576         }
9577 #endif
9578
9579         return available;
9580 }
9581
9582 static void
9583 available_connections_notify (NMDevice *self)
9584 {
9585         _notify (self, PROP_AVAILABLE_CONNECTIONS);
9586 }
9587
9588 static gboolean
9589 available_connections_del_all (NMDevice *self)
9590 {
9591         if (g_hash_table_size (self->priv->available_connections) == 0)
9592                 return FALSE;
9593         g_hash_table_remove_all (self->priv->available_connections);
9594         return TRUE;
9595 }
9596
9597 static gboolean
9598 available_connections_add (NMDevice *self, NMConnection *connection)
9599 {
9600         return nm_g_hash_table_add (self->priv->available_connections, g_object_ref (connection));
9601 }
9602
9603 static gboolean
9604 available_connections_del (NMDevice *self, NMConnection *connection)
9605 {
9606         return g_hash_table_remove (self->priv->available_connections, connection);
9607 }
9608
9609 static gboolean
9610 check_connection_available (NMDevice *self,
9611                             NMConnection *connection,
9612                             NMDeviceCheckConAvailableFlags flags,
9613                             const char *specific_object)
9614 {
9615         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE(self);
9616
9617         /* Connections which require a network connection are not available when
9618          * the device has no carrier, even with ignore-carrer=TRUE.
9619          */
9620         if (   priv->carrier
9621             || !connection_requires_carrier (connection))
9622                 return TRUE;
9623
9624         if (   NM_FLAGS_HAS (flags, _NM_DEVICE_CHECK_CON_AVAILABLE_FOR_USER_REQUEST_WAITING_CARRIER)
9625             && priv->carrier_wait_id != 0) {
9626                 /* The device has no carrier though the connection requires it.
9627                  *
9628                  * If we are still waiting for carrier, the connection is available
9629                  * for an explicit user-request. */
9630                 return TRUE;
9631         }
9632
9633         return FALSE;
9634 }
9635
9636 void
9637 nm_device_recheck_available_connections (NMDevice *self)
9638 {
9639         NMDevicePrivate *priv;
9640         const GSList *connections, *iter;
9641         gboolean changed = FALSE;
9642         GHashTableIter h_iter;
9643         NMConnection *connection;
9644
9645         g_return_if_fail (NM_IS_DEVICE (self));
9646
9647         priv = NM_DEVICE_GET_PRIVATE(self);
9648
9649         if (priv->con_provider) {
9650                 gs_unref_hashtable GHashTable *prune_list = NULL;
9651
9652                 if (g_hash_table_size (priv->available_connections) > 0) {
9653                         prune_list = g_hash_table_new (g_direct_hash, g_direct_equal);
9654                         g_hash_table_iter_init (&h_iter, priv->available_connections);
9655                         while (g_hash_table_iter_next (&h_iter, (gpointer *) &connection, NULL))
9656                                 g_hash_table_add (prune_list, connection);
9657                 }
9658
9659                 connections = nm_connection_provider_get_connections (priv->con_provider);
9660                 for (iter = connections; iter; iter = g_slist_next (iter)) {
9661                         connection = NM_CONNECTION (iter->data);
9662
9663                         if (nm_device_check_connection_available (self,
9664                                                                   connection,
9665                                                                   NM_DEVICE_CHECK_CON_AVAILABLE_NONE,
9666                                                                   NULL)) {
9667                                 if (available_connections_add (self, connection))
9668                                         changed = TRUE;
9669                                 if (prune_list)
9670                                         g_hash_table_remove (prune_list, connection);
9671                         }
9672                 }
9673
9674                 if (prune_list) {
9675                         g_hash_table_iter_init (&h_iter, prune_list);
9676                         while (g_hash_table_iter_next (&h_iter, (gpointer *) &connection, NULL)) {
9677                                 if (available_connections_del (self, connection))
9678                                         changed = TRUE;
9679                         }
9680                 }
9681         } else {
9682                 if (available_connections_del_all (self))
9683                         changed = TRUE;
9684         }
9685
9686         if (changed)
9687                 available_connections_notify (self);
9688         available_connections_check_delete_unrealized (self);
9689 }
9690
9691 /**
9692  * nm_device_get_best_connection:
9693  * @self: the #NMDevice
9694  * @specific_object: a specific object path if any
9695  * @error: reason why no connection was returned
9696  *
9697  * Returns a connection that's most suitable for user-initiated activation
9698  * of a device, optionally with a given specific object.
9699  *
9700  * Returns: the #NMSettingsConnection or %NULL (setting an @error)
9701  */
9702 NMSettingsConnection *
9703 nm_device_get_best_connection (NMDevice *self,
9704                                const char *specific_object,
9705                                GError **error)
9706 {
9707         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
9708         NMSettingsConnection *connection = NULL;
9709         NMSettingsConnection *candidate;
9710         guint64 best_timestamp = 0;
9711         GHashTableIter iter;
9712
9713         g_hash_table_iter_init (&iter, priv->available_connections);
9714         while (g_hash_table_iter_next (&iter, (gpointer) &candidate, NULL)) {
9715                 guint64 candidate_timestamp = 0;
9716
9717                 /* If a specific object is given, only include connections that are
9718                  * compatible with it.
9719                  */
9720                 if (    specific_object /* << Optimization: we know that the connection is available without @specific_object.  */
9721                     && !nm_device_check_connection_available (self,
9722                                                               NM_CONNECTION (candidate),
9723                                                               _NM_DEVICE_CHECK_CON_AVAILABLE_FOR_USER_REQUEST,
9724                                                               specific_object))
9725                         continue;
9726
9727                 nm_settings_connection_get_timestamp (candidate, &candidate_timestamp);
9728                 if (!connection || (candidate_timestamp > best_timestamp)) {
9729                         connection = candidate;
9730                         best_timestamp = candidate_timestamp;
9731                 }
9732         }
9733
9734         if (!connection) {
9735                 g_set_error (error, NM_MANAGER_ERROR, NM_MANAGER_ERROR_UNKNOWN_CONNECTION,
9736                              "The device '%s' has no connections available for activation.",
9737                               nm_device_get_iface (self));
9738         }
9739
9740         return connection;
9741 }
9742
9743 static void
9744 cp_connection_added_or_updated (NMConnectionProvider *cp, NMConnection *connection, gpointer user_data)
9745 {
9746         gboolean changed;
9747         NMDevice *self = user_data;
9748
9749         g_return_if_fail (NM_IS_DEVICE (self));
9750         g_return_if_fail (NM_IS_SETTINGS_CONNECTION (connection));
9751
9752         if (nm_device_check_connection_available (self,
9753                                                   connection,
9754                                                   _NM_DEVICE_CHECK_CON_AVAILABLE_FOR_USER_REQUEST,
9755                                                   NULL))
9756                 changed = available_connections_add (self, connection);
9757         else
9758                 changed = available_connections_del (self, connection);
9759
9760         if (changed) {
9761                 available_connections_notify (self);
9762                 available_connections_check_delete_unrealized (self);
9763         }
9764 }
9765
9766 static void
9767 cp_connection_removed (NMConnectionProvider *cp, NMConnection *connection, gpointer user_data)
9768 {
9769         NMDevice *self = user_data;
9770
9771         g_return_if_fail (NM_IS_DEVICE (self));
9772
9773         if (available_connections_del (self, connection)) {
9774                 available_connections_notify (self);
9775                 available_connections_check_delete_unrealized (self);
9776         }
9777 }
9778
9779 gboolean
9780 nm_device_supports_vlans (NMDevice *self)
9781 {
9782         return nm_platform_link_supports_vlans (NM_PLATFORM_GET, nm_device_get_ifindex (self));
9783 }
9784
9785 /**
9786  * nm_device_add_pending_action():
9787  * @self: the #NMDevice to add the pending action to
9788  * @action: a static string that identifies the action
9789  * @assert_not_yet_pending: if %TRUE, assert that the @action is currently not yet pending.
9790  * Otherwise, ignore duplicate scheduling of the same action silently.
9791  *
9792  * Adds a pending action to the device.
9793  *
9794  * Returns: %TRUE if the action was added (and not already added before). %FALSE
9795  * if the same action is already scheduled. In the latter case, the action was not scheduled
9796  * a second time.
9797  */
9798 gboolean
9799 nm_device_add_pending_action (NMDevice *self, const char *action, gboolean assert_not_yet_pending)
9800 {
9801         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
9802         GSList *iter;
9803         guint count = 0;
9804
9805         g_return_val_if_fail (action, FALSE);
9806
9807         /* Check if the action is already pending. Cannot add duplicate actions */
9808         for (iter = priv->pending_actions; iter; iter = iter->next) {
9809                 if (!strcmp (action, iter->data)) {
9810                         if (assert_not_yet_pending) {
9811                                 _LOGW (LOGD_DEVICE, "add_pending_action (%d): '%s' already pending",
9812                                        count + g_slist_length (iter), action);
9813                                 g_return_val_if_reached (FALSE);
9814                         } else {
9815                                 _LOGD (LOGD_DEVICE, "add_pending_action (%d): '%s' already pending (expected)",
9816                                        count + g_slist_length (iter), action);
9817                         }
9818                         return FALSE;
9819                 }
9820                 count++;
9821         }
9822
9823         priv->pending_actions = g_slist_append (priv->pending_actions, g_strdup (action));
9824         count++;
9825
9826         _LOGD (LOGD_DEVICE, "add_pending_action (%d): '%s'", count, action);
9827
9828         if (count == 1)
9829                 _notify (self, PROP_HAS_PENDING_ACTION);
9830
9831         return TRUE;
9832 }
9833
9834 /**
9835  * nm_device_remove_pending_action():
9836  * @self: the #NMDevice to remove the pending action from
9837  * @action: a static string that identifies the action
9838  * @assert_is_pending: if %TRUE, assert that the @action is pending.
9839  * If %FALSE, don't do anything if the current action is not pending and
9840  * return %FALSE.
9841  *
9842  * Removes a pending action previously added by nm_device_add_pending_action().
9843  *
9844  * Returns: whether the @action was pending and is now removed.
9845  */
9846 gboolean
9847 nm_device_remove_pending_action (NMDevice *self, const char *action, gboolean assert_is_pending)
9848 {
9849         NMDevicePrivate *priv;
9850         GSList *iter, *next;
9851         guint count = 0;
9852
9853         g_return_val_if_fail (self, FALSE);
9854         g_return_val_if_fail (action, FALSE);
9855
9856         priv = NM_DEVICE_GET_PRIVATE (self);
9857
9858         for (iter = priv->pending_actions; iter; iter = next) {
9859                 next = iter->next;
9860                 if (!strcmp (action, iter->data)) {
9861                         _LOGD (LOGD_DEVICE, "remove_pending_action (%d): '%s'",
9862                                count + g_slist_length (iter->next), /* length excluding 'iter' */
9863                                action);
9864                         g_free (iter->data);
9865                         priv->pending_actions = g_slist_delete_link (priv->pending_actions, iter);
9866                         if (priv->pending_actions == NULL)
9867                                 _notify (self, PROP_HAS_PENDING_ACTION);
9868                         return TRUE;
9869                 }
9870                 count++;
9871         }
9872
9873         if (assert_is_pending) {
9874                 _LOGW (LOGD_DEVICE, "remove_pending_action (%d): '%s' not pending", count, action);
9875                 g_return_val_if_reached (FALSE);
9876         } else
9877                 _LOGD (LOGD_DEVICE, "remove_pending_action (%d): '%s' not pending (expected)", count, action);
9878
9879         return FALSE;
9880 }
9881
9882 gboolean
9883 nm_device_has_pending_action (NMDevice *self)
9884 {
9885         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
9886
9887         return !!priv->pending_actions;
9888 }
9889
9890 /***********************************************************/
9891
9892 static void
9893 _cancel_activation (NMDevice *self)
9894 {
9895         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
9896
9897         /* Clean up when device was deactivated during call to firewall */
9898         if (priv->fw_call) {
9899                 nm_firewall_manager_cancel_call (priv->fw_call);
9900                 g_warn_if_fail (!priv->fw_call);
9901                 priv->fw_call = NULL;
9902         }
9903         priv->fw_ready = FALSE;
9904
9905         ip_check_gw_ping_cleanup (self);
9906
9907         /* Break the activation chain */
9908         activation_source_clear (self, AF_INET);
9909         activation_source_clear (self, AF_INET6);
9910 }
9911
9912 static void
9913 _cleanup_generic_pre (NMDevice *self, CleanupType cleanup_type)
9914 {
9915         NMConnection *connection;
9916
9917         _cancel_activation (self);
9918
9919         connection = nm_device_get_applied_connection (self);
9920         if (   cleanup_type == CLEANUP_TYPE_DECONFIGURE
9921             && connection
9922             && !nm_device_uses_assumed_connection (self)) {
9923                 nm_firewall_manager_remove_from_zone (nm_firewall_manager_get (),
9924                                                       nm_device_get_ip_iface (self),
9925                                                       NULL,
9926                                                       NULL,
9927                                                       NULL);
9928         }
9929
9930         /* Clear any queued transitions */
9931         nm_device_queued_state_clear (self);
9932
9933         _cleanup_ip4_pre (self, cleanup_type);
9934         _cleanup_ip6_pre (self, cleanup_type);
9935 }
9936
9937 static void
9938 _cleanup_generic_post (NMDevice *self, CleanupType cleanup_type)
9939 {
9940         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
9941         NMDeviceStateReason ignored = NM_DEVICE_STATE_REASON_NONE;
9942
9943         priv->default_route.v4_has = FALSE;
9944         priv->default_route.v6_has = FALSE;
9945
9946         if (cleanup_type == CLEANUP_TYPE_DECONFIGURE) {
9947                 priv->default_route.v4_is_assumed = FALSE;
9948                 priv->default_route.v6_is_assumed = FALSE;
9949                 nm_default_route_manager_ip4_update_default_route (nm_default_route_manager_get (), self);
9950                 nm_default_route_manager_ip6_update_default_route (nm_default_route_manager_get (), self);
9951         }
9952
9953         priv->default_route.v4_is_assumed = TRUE;
9954         priv->default_route.v6_is_assumed = TRUE;
9955         nm_default_route_manager_ip4_update_default_route (nm_default_route_manager_get (), self);
9956         nm_default_route_manager_ip6_update_default_route (nm_default_route_manager_get (), self);
9957
9958         priv->v4_commit_first_time = TRUE;
9959         priv->v6_commit_first_time = TRUE;
9960
9961         priv->linklocal6_dad_counter = 0;
9962
9963         /* Clean up IP configs; this does not actually deconfigure the
9964          * interface; the caller must flush routes and addresses explicitly.
9965          */
9966         nm_device_set_ip4_config (self, NULL, 0, TRUE, TRUE, &ignored);
9967         nm_device_set_ip6_config (self, NULL, TRUE, TRUE, &ignored);
9968         g_clear_object (&priv->con_ip4_config);
9969         g_clear_object (&priv->dev_ip4_config);
9970         g_clear_object (&priv->ext_ip4_config);
9971         g_clear_object (&priv->wwan_ip4_config);
9972         g_clear_object (&priv->ip4_config);
9973         g_clear_object (&priv->con_ip6_config);
9974         g_clear_object (&priv->ac_ip6_config);
9975         g_clear_object (&priv->ext_ip6_config);
9976         g_clear_object (&priv->ext_ip6_config_captured);
9977         g_clear_object (&priv->wwan_ip6_config);
9978         g_clear_object (&priv->ip6_config);
9979
9980         g_slist_free_full (priv->vpn4_configs, g_object_unref);
9981         priv->vpn4_configs = NULL;
9982         g_slist_free_full (priv->vpn6_configs, g_object_unref);
9983         priv->vpn6_configs = NULL;
9984
9985         clear_act_request (self);
9986
9987         /* Clear legacy IPv4 address property */
9988         if (priv->ip4_address) {
9989                 priv->ip4_address = 0;
9990                 _notify (self, PROP_IP4_ADDRESS);
9991         }
9992
9993         if (cleanup_type == CLEANUP_TYPE_DECONFIGURE) {
9994                 /* Check if the device was deactivated, and if so, delete_link.
9995                  * Don't call delete_link synchronously because we are currently
9996                  * handling a state change -- which is not reentrant. */
9997                 delete_on_deactivate_check_and_schedule (self, nm_device_get_ip_ifindex (self));
9998         }
9999
10000         /* ip_iface should be cleared after flushing all routes and addreses, since
10001          * those are identified by ip_iface, not by iface (which might be a tty
10002          * or ATM device).
10003          */
10004         nm_device_set_ip_iface (self, NULL);
10005 }
10006
10007 /*
10008  * nm_device_cleanup
10009  *
10010  * Remove a device's routing table entries and IP addresses.
10011  *
10012  */
10013 static void
10014 nm_device_cleanup (NMDevice *self, NMDeviceStateReason reason, CleanupType cleanup_type)
10015 {
10016         NMDevicePrivate *priv;
10017         int ifindex;
10018
10019         g_return_if_fail (NM_IS_DEVICE (self));
10020
10021         if (reason == NM_DEVICE_STATE_REASON_NOW_MANAGED)
10022                 _LOGD (LOGD_DEVICE, "preparing device");
10023         else
10024                 _LOGD (LOGD_DEVICE, "deactivating device (reason '%s') [%d]", reason_to_string (reason), reason);
10025
10026         /* Save whether or not we tried IPv6 for later */
10027         priv = NM_DEVICE_GET_PRIVATE (self);
10028
10029         _cleanup_generic_pre (self, cleanup_type);
10030
10031         /* Turn off kernel IPv6 */
10032         if (cleanup_type == CLEANUP_TYPE_DECONFIGURE) {
10033                 set_disable_ipv6 (self, "1");
10034                 nm_device_ipv6_sysctl_set (self, "accept_ra", "0");
10035                 nm_device_ipv6_sysctl_set (self, "use_tempaddr", "0");
10036         }
10037
10038         /* Call device type-specific deactivation */
10039         if (NM_DEVICE_GET_CLASS (self)->deactivate)
10040                 NM_DEVICE_GET_CLASS (self)->deactivate (self);
10041
10042         /* master: release slaves */
10043         nm_device_master_release_slaves (self);
10044
10045         /* slave: mark no longer enslaved */
10046         if (   priv->master
10047             && nm_platform_link_get_master (NM_PLATFORM_GET, priv->ifindex) <= 0)
10048                 nm_device_master_release_one_slave (priv->master, self, FALSE, NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED);
10049
10050         /* Take out any entries in the routing table and any IP address the device had. */
10051         ifindex = nm_device_get_ip_ifindex (self);
10052         if (ifindex > 0) {
10053                 nm_route_manager_route_flush (nm_route_manager_get (), ifindex);
10054                 nm_platform_address_flush (NM_PLATFORM_GET, ifindex);
10055         }
10056
10057         if (priv->lldp_listener)
10058                 nm_lldp_listener_stop (priv->lldp_listener);
10059
10060         nm_device_update_metered (self);
10061         _cleanup_generic_post (self, cleanup_type);
10062 }
10063
10064 static char *
10065 bin2hexstr (const char *bytes, gsize len)
10066 {
10067         GString *str;
10068         int i;
10069
10070         g_return_val_if_fail (bytes != NULL, NULL);
10071         g_return_val_if_fail (len > 0, NULL);
10072
10073         str = g_string_sized_new (len * 2 + 1);
10074         for (i = 0; i < len; i++) {
10075                 if (str->len)
10076                         g_string_append_c (str, ':');
10077                 g_string_append_printf (str, "%02x", (guint8) bytes[i]);
10078         }
10079         return g_string_free (str, FALSE);
10080 }
10081
10082 static char *
10083 find_dhcp4_address (NMDevice *self)
10084 {
10085         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
10086         guint i, n;
10087
10088         if (!priv->ip4_config)
10089                 return NULL;
10090
10091         n = nm_ip4_config_get_num_addresses (priv->ip4_config);
10092         for (i = 0; i < n; i++) {
10093                 const NMPlatformIP4Address *a = nm_ip4_config_get_address (priv->ip4_config, i);
10094
10095                 if (a->source == NM_IP_CONFIG_SOURCE_DHCP)
10096                         return g_strdup (nm_utils_inet4_ntop (a->address, NULL));
10097         }
10098         return NULL;
10099 }
10100
10101 void
10102 nm_device_spawn_iface_helper (NMDevice *self)
10103 {
10104         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
10105         gboolean configured = FALSE;
10106         NMConnection *connection;
10107         GError *error = NULL;
10108         const char *method;
10109         GPtrArray *argv;
10110         gs_free char *dhcp4_address = NULL;
10111         char *logging_backend;
10112
10113         if (priv->state != NM_DEVICE_STATE_ACTIVATED)
10114                 return;
10115         if (!nm_device_can_assume_connections (self))
10116                 return;
10117
10118         connection = nm_device_get_applied_connection (self);
10119         g_assert (connection);
10120
10121         argv = g_ptr_array_sized_new (10);
10122         g_ptr_array_set_free_func (argv, g_free);
10123
10124         g_ptr_array_add (argv, g_strdup (LIBEXECDIR "/nm-iface-helper"));
10125         g_ptr_array_add (argv, g_strdup ("--ifname"));
10126         g_ptr_array_add (argv, g_strdup (nm_device_get_ip_iface (self)));
10127         g_ptr_array_add (argv, g_strdup ("--uuid"));
10128         g_ptr_array_add (argv, g_strdup (nm_connection_get_uuid (connection)));
10129
10130         logging_backend = nm_config_get_is_debug (nm_config_get ())
10131                           ? g_strdup ("debug")
10132                           : nm_config_data_get_value (NM_CONFIG_GET_DATA_ORIG,
10133                                                       NM_CONFIG_KEYFILE_GROUP_LOGGING,
10134                                                       NM_CONFIG_KEYFILE_KEY_LOGGING_BACKEND,
10135                                                       NM_CONFIG_GET_VALUE_STRIP | NM_CONFIG_GET_VALUE_NO_EMPTY);
10136         if (logging_backend) {
10137                 g_ptr_array_add (argv, g_strdup ("--logging-backend"));
10138                 g_ptr_array_add (argv, logging_backend);
10139         }
10140
10141         dhcp4_address = find_dhcp4_address (self);
10142
10143         method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG);
10144         if (g_strcmp0 (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO) == 0) {
10145                 NMSettingIPConfig *s_ip4;
10146                 char *hex_client_id;
10147
10148                 s_ip4 = nm_connection_get_setting_ip4_config (connection);
10149                 g_assert (s_ip4);
10150
10151                 g_ptr_array_add (argv, g_strdup ("--priority4"));
10152                 g_ptr_array_add (argv, g_strdup_printf ("%u", nm_device_get_ip4_route_metric (self)));
10153
10154                 g_ptr_array_add (argv, g_strdup ("--dhcp4"));
10155                 g_ptr_array_add (argv, g_strdup (dhcp4_address));
10156                 if (nm_setting_ip_config_get_may_fail (s_ip4) == FALSE)
10157                         g_ptr_array_add (argv, g_strdup ("--dhcp4-required"));
10158
10159                 if (priv->dhcp4_client) {
10160                         const char *hostname, *fqdn;
10161                         GBytes *client_id;
10162
10163                         client_id = nm_dhcp_client_get_client_id (priv->dhcp4_client);
10164                         if (client_id) {
10165                                 g_ptr_array_add (argv, g_strdup ("--dhcp4-clientid"));
10166                                 hex_client_id = bin2hexstr (g_bytes_get_data (client_id, NULL),
10167                                                             g_bytes_get_size (client_id));
10168                                 g_ptr_array_add (argv, hex_client_id);
10169                         }
10170
10171                         hostname = nm_dhcp_client_get_hostname (priv->dhcp4_client);
10172                         if (hostname) {
10173                                 g_ptr_array_add (argv, g_strdup ("--dhcp4-hostname"));
10174                                 g_ptr_array_add (argv, g_strdup (hostname));
10175                         }
10176
10177                         fqdn = nm_dhcp_client_get_fqdn (priv->dhcp4_client);
10178                         if (fqdn) {
10179                                 g_ptr_array_add (argv, g_strdup ("--dhcp4-fqdn"));
10180                                 g_ptr_array_add (argv, g_strdup (fqdn));
10181                         }
10182                 }
10183
10184                 configured = TRUE;
10185         }
10186
10187         method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG);
10188         if (g_strcmp0 (method, NM_SETTING_IP6_CONFIG_METHOD_AUTO) == 0) {
10189                 NMSettingIPConfig *s_ip6;
10190                 char *hex_iid;
10191                 NMUtilsIPv6IfaceId iid = NM_UTILS_IPV6_IFACE_ID_INIT;
10192
10193                 s_ip6 = nm_connection_get_setting_ip6_config (connection);
10194                 g_assert (s_ip6);
10195
10196                 g_ptr_array_add (argv, g_strdup ("--priority6"));
10197                 g_ptr_array_add (argv, g_strdup_printf ("%u", nm_device_get_ip6_route_metric (self)));
10198
10199                 g_ptr_array_add (argv, g_strdup ("--slaac"));
10200
10201                 if (nm_setting_ip_config_get_may_fail (s_ip6) == FALSE)
10202                         g_ptr_array_add (argv, g_strdup ("--slaac-required"));
10203
10204                 g_ptr_array_add (argv, g_strdup ("--slaac-tempaddr"));
10205                 g_ptr_array_add (argv, g_strdup_printf ("%d", priv->rdisc_use_tempaddr));
10206
10207                 if (nm_device_get_ip_iface_identifier (self, &iid)) {
10208                         g_ptr_array_add (argv, g_strdup ("--iid"));
10209                         hex_iid = bin2hexstr ((const char *) iid.id_u8, sizeof (NMUtilsIPv6IfaceId));
10210                         g_ptr_array_add (argv, hex_iid);
10211                 }
10212
10213                 g_ptr_array_add (argv, g_strdup ("--addr-gen-mode"));
10214                 g_ptr_array_add (argv, g_strdup_printf ("%d", nm_setting_ip6_config_get_addr_gen_mode (NM_SETTING_IP6_CONFIG (s_ip6))));
10215
10216                 configured = TRUE;
10217         }
10218
10219         if (configured) {
10220                 GPid pid;
10221
10222                 g_ptr_array_add (argv, NULL);
10223
10224                 if (nm_logging_enabled (LOGL_DEBUG, LOGD_DEVICE)) {
10225                         char *tmp;
10226
10227                         tmp = g_strjoinv (" ", (char **) argv->pdata);
10228                         _LOGD (LOGD_DEVICE, "running '%s'", tmp);
10229                         g_free (tmp);
10230                 }
10231
10232                 if (g_spawn_async (NULL, (char **) argv->pdata, NULL,
10233                                    G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL, &pid, &error)) {
10234                         _LOGI (LOGD_DEVICE, "spawned helper PID %u", (guint) pid);
10235                 } else {
10236                         _LOGW (LOGD_DEVICE, "failed to spawn helper: %s", error->message);
10237                         g_error_free (error);
10238                 }
10239         }
10240
10241         g_ptr_array_unref (argv);
10242 }
10243
10244 /***********************************************************/
10245
10246 static gboolean
10247 ip_config_valid (NMDeviceState state)
10248 {
10249         return (state == NM_DEVICE_STATE_UNMANAGED) ||
10250                 (state >= NM_DEVICE_STATE_IP_CHECK &&
10251                  state <= NM_DEVICE_STATE_DEACTIVATING);
10252 }
10253
10254 static void
10255 notify_ip_properties (NMDevice *self)
10256 {
10257         _notify (self, PROP_IP_IFACE);
10258         _notify (self, PROP_IP4_CONFIG);
10259         _notify (self, PROP_DHCP4_CONFIG);
10260         _notify (self, PROP_IP6_CONFIG);
10261         _notify (self, PROP_DHCP6_CONFIG);
10262 }
10263
10264 static void
10265 ip6_managed_setup (NMDevice *self)
10266 {
10267         set_nm_ipv6ll (self, TRUE);
10268         set_disable_ipv6 (self, "1");
10269         nm_device_ipv6_sysctl_set (self, "accept_ra_defrtr", "0");
10270         nm_device_ipv6_sysctl_set (self, "accept_ra_pinfo", "0");
10271         nm_device_ipv6_sysctl_set (self, "accept_ra_rtr_pref", "0");
10272         nm_device_ipv6_sysctl_set (self, "use_tempaddr", "0");
10273 }
10274
10275 static void
10276 deactivate_async_ready (NMDevice *self,
10277                         GAsyncResult *res,
10278                         gpointer user_data)
10279 {
10280         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
10281         NMDeviceStateReason reason = GPOINTER_TO_UINT (user_data);
10282         GError *error = NULL;
10283
10284         NM_DEVICE_GET_CLASS (self)->deactivate_async_finish (self, res, &error);
10285
10286         /* If operation cancelled, just return */
10287         if (   g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)
10288             || (priv->deactivating_cancellable && g_cancellable_is_cancelled (priv->deactivating_cancellable))) {
10289                 _LOGW (LOGD_DEVICE, "Deactivation cancelled");
10290         }
10291         /* In every other case, transition to the DISCONNECTED state */
10292         else {
10293                 if (error) {
10294                         _LOGW (LOGD_DEVICE, "Deactivation failed: %s",
10295                                error->message);
10296                 }
10297                 nm_device_queue_state (self, NM_DEVICE_STATE_DISCONNECTED, reason);
10298         }
10299
10300         g_clear_object (&priv->deactivating_cancellable);
10301         g_clear_error (&error);
10302 }
10303
10304 static void
10305 deactivate_dispatcher_complete (guint call_id, gpointer user_data)
10306 {
10307         NMDevice *self = NM_DEVICE (user_data);
10308         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
10309         NMDeviceStateReason reason;
10310
10311         g_return_if_fail (call_id == priv->dispatcher.call_id);
10312         g_return_if_fail (priv->dispatcher.post_state == NM_DEVICE_STATE_DISCONNECTED);
10313
10314         reason = priv->dispatcher.post_state_reason;
10315
10316         priv->dispatcher.call_id = 0;
10317         priv->dispatcher.post_state = NM_DEVICE_STATE_UNKNOWN;
10318         priv->dispatcher.post_state_reason = NM_DEVICE_STATE_REASON_NONE;
10319
10320         if (priv->deactivating_cancellable) {
10321                 g_warn_if_reached ();
10322                 g_cancellable_cancel (priv->deactivating_cancellable);
10323                 g_clear_object (&priv->deactivating_cancellable);
10324         }
10325
10326         if (   NM_DEVICE_GET_CLASS (self)->deactivate_async
10327             && NM_DEVICE_GET_CLASS (self)->deactivate_async_finish) {
10328                 priv->deactivating_cancellable = g_cancellable_new ();
10329                 NM_DEVICE_GET_CLASS (self)->deactivate_async (self,
10330                                                               priv->deactivating_cancellable,
10331                                                               (GAsyncReadyCallback) deactivate_async_ready,
10332                                                               GUINT_TO_POINTER (reason));
10333         } else
10334                 nm_device_queue_state (self, NM_DEVICE_STATE_DISCONNECTED, reason);
10335 }
10336
10337 static void
10338 _set_state_full (NMDevice *self,
10339                  NMDeviceState state,
10340                  NMDeviceStateReason reason,
10341                  gboolean quitting)
10342 {
10343         NMDevicePrivate *priv;
10344         NMDeviceState old_state;
10345         NMActRequest *req;
10346         gboolean no_firmware = FALSE;
10347         NMSettingsConnection *connection;
10348         NMConnection *applied_connection;
10349
10350         g_return_if_fail (NM_IS_DEVICE (self));
10351
10352         priv = NM_DEVICE_GET_PRIVATE (self);
10353
10354         /* Track re-entry */
10355         g_warn_if_fail (priv->in_state_changed == FALSE);
10356
10357         old_state = priv->state;
10358
10359         /* Do nothing if state isn't changing, but as a special case allow
10360          * re-setting UNAVAILABLE if the device is missing firmware so that we
10361          * can retry device initialization.
10362          */
10363         if (   (priv->state == state)
10364             && (   state != NM_DEVICE_STATE_UNAVAILABLE
10365                 || !priv->firmware_missing)) {
10366                 _LOGD (LOGD_DEVICE, "state change: %s -> %s (reason '%s') [%d %d %d]%s",
10367                        state_to_string (old_state),
10368                        state_to_string (state),
10369                        reason_to_string (reason),
10370                        old_state,
10371                        state,
10372                        reason,
10373                        priv->firmware_missing ? " (missing firmware)" : "");
10374                 return;
10375         }
10376
10377         _LOGI (LOGD_DEVICE, "state change: %s -> %s (reason '%s') [%d %d %d]",
10378                state_to_string (old_state),
10379                state_to_string (state),
10380                reason_to_string (reason),
10381                old_state,
10382                state,
10383                reason);
10384
10385         priv->in_state_changed = TRUE;
10386
10387         priv->state = state;
10388         priv->state_reason = reason;
10389
10390         /* Clear any queued transitions */
10391         nm_device_queued_state_clear (self);
10392
10393         dispatcher_cleanup (self);
10394         if (priv->deactivating_cancellable)
10395                 g_cancellable_cancel (priv->deactivating_cancellable);
10396
10397         /* Cache the activation request for the dispatcher */
10398         req = priv->act_request ? g_object_ref (priv->act_request) : NULL;
10399
10400         if (state <= NM_DEVICE_STATE_UNAVAILABLE) {
10401                 if (available_connections_del_all (self))
10402                         available_connections_notify (self);
10403                 _clear_queued_act_request (priv);
10404         }
10405
10406         /* Update the available connections list when a device first becomes available */
10407         if (state >= NM_DEVICE_STATE_DISCONNECTED && old_state < NM_DEVICE_STATE_DISCONNECTED)
10408                 nm_device_recheck_available_connections (self);
10409
10410         /* Handle the new state here; but anything that could trigger
10411          * another state change should be done below.
10412          */
10413         switch (state) {
10414         case NM_DEVICE_STATE_UNMANAGED:
10415                 nm_device_set_firmware_missing (self, FALSE);
10416                 if (old_state > NM_DEVICE_STATE_UNMANAGED) {
10417                         if (reason == NM_DEVICE_STATE_REASON_REMOVED) {
10418                                 nm_device_cleanup (self, reason, CLEANUP_TYPE_REMOVED);
10419                         } else {
10420                                 /* Clean up if the device is now unmanaged but was activated */
10421                                 if (nm_device_get_act_request (self))
10422                                         nm_device_cleanup (self, reason, CLEANUP_TYPE_DECONFIGURE);
10423                                 nm_device_take_down (self, TRUE);
10424                                 set_nm_ipv6ll (self, FALSE);
10425                                 restore_ip6_properties (self);
10426                         }
10427                 }
10428                 break;
10429         case NM_DEVICE_STATE_UNAVAILABLE:
10430                 if (old_state == NM_DEVICE_STATE_UNMANAGED) {
10431                         save_ip6_properties (self);
10432                         if (reason != NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED)
10433                                 ip6_managed_setup (self);
10434                 }
10435
10436                 if (reason != NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED) {
10437                         if (old_state == NM_DEVICE_STATE_UNMANAGED || priv->firmware_missing) {
10438                                 if (!nm_device_bring_up (self, TRUE, &no_firmware) && no_firmware)
10439                                         _LOGW (LOGD_HW, "firmware may be missing.");
10440                                 nm_device_set_firmware_missing (self, no_firmware ? TRUE : FALSE);
10441                         }
10442
10443                         /* Ensure the device gets deactivated in response to stuff like
10444                          * carrier changes or rfkill.  But don't deactivate devices that are
10445                          * about to assume a connection since that defeats the purpose of
10446                          * assuming the device's existing connection.
10447                          *
10448                          * Note that we "deactivate" the device even when coming from
10449                          * UNMANAGED, to ensure that it's in a clean state.
10450                          */
10451                         nm_device_cleanup (self, reason, CLEANUP_TYPE_DECONFIGURE);
10452                 }
10453                 break;
10454         case NM_DEVICE_STATE_DISCONNECTED:
10455                 if (old_state > NM_DEVICE_STATE_DISCONNECTED) {
10456                         /* Ensure devices that previously assumed a connection now have
10457                          * userspace IPv6LL enabled.
10458                          */
10459                         set_nm_ipv6ll (self, TRUE);
10460
10461                         nm_device_cleanup (self, reason, CLEANUP_TYPE_DECONFIGURE);
10462                 } else if (old_state < NM_DEVICE_STATE_DISCONNECTED) {
10463                         if (reason != NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED) {
10464                                 /* Ensure IPv6 is set up as it may not have been done when
10465                                  * entering the UNAVAILABLE state depending on the reason.
10466                                  */
10467                                 ip6_managed_setup (self);
10468                         }
10469                 }
10470                 break;
10471         case NM_DEVICE_STATE_NEED_AUTH:
10472                 if (old_state > NM_DEVICE_STATE_NEED_AUTH) {
10473                         /* Clean up any half-done IP operations if the device's layer2
10474                          * finds out it needs authentication during IP config.
10475                          */
10476                         _cleanup_ip4_pre (self, CLEANUP_TYPE_DECONFIGURE);
10477                         _cleanup_ip6_pre (self, CLEANUP_TYPE_DECONFIGURE);
10478                 }
10479                 break;
10480         default:
10481                 break;
10482         }
10483
10484         /* Reset autoconnect flag when the device is activating or connected. */
10485         if (   state >= NM_DEVICE_STATE_PREPARE
10486             && state <= NM_DEVICE_STATE_ACTIVATED)
10487                 nm_device_set_autoconnect (self, TRUE);
10488
10489         _notify (self, PROP_STATE);
10490         _notify (self, PROP_STATE_REASON);
10491         g_signal_emit_by_name (self, NM_DEVICE_STATE_CHANGED, state, old_state, reason);
10492
10493         /* Post-process the event after internal notification */
10494
10495         switch (state) {
10496         case NM_DEVICE_STATE_UNAVAILABLE:
10497                 /* If the device can activate now (ie, it's got a carrier, the supplicant
10498                  * is active, or whatever) schedule a delayed transition to DISCONNECTED
10499                  * to get things rolling.  The device can't transition immediately because
10500                  * we can't change states again from the state handler for a variety of
10501                  * reasons.
10502                  */
10503                 if (nm_device_is_available (self, NM_DEVICE_CHECK_DEV_AVAILABLE_NONE)) {
10504                         nm_device_queue_recheck_available (self,
10505                                                            NM_DEVICE_STATE_REASON_NONE,
10506                                                            NM_DEVICE_STATE_REASON_NONE);
10507                 } else {
10508                         _LOGD (LOGD_DEVICE, "device not yet available for transition to DISCONNECTED");
10509                 }
10510                 break;
10511         case NM_DEVICE_STATE_DEACTIVATING:
10512                 _cancel_activation (self);
10513
10514                 if (nm_device_has_capability (self, NM_DEVICE_CAP_CARRIER_DETECT)) {
10515                         /* We cache the ignore_carrier state to not react on config-reloads while the connection
10516                          * is active. But on deactivating, reset the ignore-carrier flag to the current state. */
10517                         priv->ignore_carrier = nm_config_data_get_ignore_carrier (NM_CONFIG_GET_DATA, self);
10518                 }
10519
10520                 if (quitting) {
10521                         nm_dispatcher_call_sync (DISPATCHER_ACTION_PRE_DOWN,
10522                                                  nm_act_request_get_settings_connection (req),
10523                                                  nm_act_request_get_applied_connection (req),
10524                                                  self);
10525                 } else {
10526                         priv->dispatcher.post_state = NM_DEVICE_STATE_DISCONNECTED;
10527                         priv->dispatcher.post_state_reason = reason;
10528                         if (!nm_dispatcher_call (DISPATCHER_ACTION_PRE_DOWN,
10529                                                  nm_act_request_get_settings_connection (req),
10530                                                  nm_act_request_get_applied_connection (req),
10531                                                  self,
10532                                                  deactivate_dispatcher_complete,
10533                                                  self,
10534                                                  &priv->dispatcher.call_id)) {
10535                                 /* Just proceed on errors */
10536                                 deactivate_dispatcher_complete (0, self);
10537                         }
10538                 }
10539                 break;
10540         case NM_DEVICE_STATE_DISCONNECTED:
10541                 if (   priv->queued_act_request
10542                     && !priv->queued_act_request_is_waiting_for_carrier) {
10543                         NMActRequest *queued_req;
10544                         gboolean success;
10545
10546                         queued_req = priv->queued_act_request;
10547                         priv->queued_act_request = NULL;
10548                         success = _device_activate (self, queued_req);
10549                         g_object_unref (queued_req);
10550                         if (success)
10551                                 break;
10552                         /* fall through */
10553                 }
10554                 break;
10555         case NM_DEVICE_STATE_ACTIVATED:
10556                 _LOGI (LOGD_DEVICE, "Activation: successful, device activated.");
10557                 nm_device_update_metered (self);
10558                 nm_dispatcher_call (DISPATCHER_ACTION_UP,
10559                                     nm_act_request_get_settings_connection (req),
10560                                     nm_act_request_get_applied_connection (req),
10561                                     self, NULL, NULL, NULL);
10562                 break;
10563         case NM_DEVICE_STATE_FAILED:
10564                 /* Usually upon failure the activation chain is interrupted in
10565                  * one of the stages; but in some cases the device fails for
10566                  * external events (as a failure of master connection) while
10567                  * the activation sequence is running and so we need to ensure
10568                  * that the chain is terminated here.
10569                  */
10570                 _cancel_activation (self);
10571
10572                 if (nm_device_uses_assumed_connection (self)) {
10573                         /* Avoid tearing down assumed connection, assume it's connected */
10574                         nm_device_queue_state (self,
10575                                                NM_DEVICE_STATE_ACTIVATED,
10576                                                NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED);
10577                         break;
10578                 }
10579
10580                 connection = nm_device_get_settings_connection (self);
10581                 _LOGW (LOGD_DEVICE | LOGD_WIFI,
10582                        "Activation: failed for connection '%s'",
10583                        connection ? nm_settings_connection_get_id (connection) : "<unknown>");
10584
10585                 /* Notify any slaves of the unexpected failure */
10586                 nm_device_master_release_slaves (self);
10587
10588                 /* If the connection doesn't yet have a timestamp, set it to zero so that
10589                  * we can distinguish between connections we've tried to activate and have
10590                  * failed (zero timestamp), connections that succeeded (non-zero timestamp),
10591                  * and those we haven't tried yet (no timestamp).
10592                  */
10593                 if (connection && !nm_settings_connection_get_timestamp (connection, NULL))
10594                         nm_settings_connection_update_timestamp (connection, (guint64) 0, TRUE);
10595
10596                 /* Schedule the transition to DISCONNECTED.  The device can't transition
10597                  * immediately because we can't change states again from the state
10598                  * handler for a variety of reasons.
10599                  */
10600                 nm_device_queue_state (self, NM_DEVICE_STATE_DISCONNECTED, NM_DEVICE_STATE_REASON_NONE);
10601                 break;
10602         case NM_DEVICE_STATE_IP_CHECK:
10603                 /* Now that IP config has completed, check if the firewall
10604                  * zone must be set again for the IP interface.
10605                  */
10606                 applied_connection = nm_device_get_applied_connection (self);
10607
10608                 if (   applied_connection
10609                     && priv->ifindex != priv->ip_ifindex
10610                     && !nm_device_uses_assumed_connection (self)) {
10611                         NMSettingConnection *s_con;
10612                         const char *zone;
10613
10614                         s_con = nm_connection_get_setting_connection (applied_connection);
10615                         zone = nm_setting_connection_get_zone (s_con);
10616                         g_assert (!priv->fw_call);
10617                         priv->fw_call = nm_firewall_manager_add_or_change_zone (nm_firewall_manager_get (),
10618                                                                                 nm_device_get_ip_iface (self),
10619                                                                                 zone,
10620                                                                                 FALSE,
10621                                                                                 fw_change_zone_cb_ip_check,
10622                                                                                 self);
10623                 } else
10624                         nm_device_start_ip_check (self);
10625
10626                 /* IP-related properties are only valid when the device has IP configuration;
10627                  * now that it does, ensure their change notifications are emitted.
10628                  */
10629                 notify_ip_properties (self);
10630                 break;
10631         case NM_DEVICE_STATE_SECONDARIES:
10632                 ip_check_gw_ping_cleanup (self);
10633                 _LOGD (LOGD_DEVICE, "device entered SECONDARIES state");
10634                 break;
10635         default:
10636                 break;
10637         }
10638
10639         if (state > NM_DEVICE_STATE_DISCONNECTED)
10640                 delete_on_deactivate_unschedule (self);
10641
10642         if (   (old_state == NM_DEVICE_STATE_ACTIVATED || old_state == NM_DEVICE_STATE_DEACTIVATING)
10643             && (state != NM_DEVICE_STATE_DEACTIVATING)) {
10644                 if (quitting) {
10645                         nm_dispatcher_call_sync (DISPATCHER_ACTION_DOWN,
10646                                                  nm_act_request_get_settings_connection (req),
10647                                                  nm_act_request_get_applied_connection (req),
10648                                                  self);
10649                 } else {
10650                         nm_dispatcher_call (DISPATCHER_ACTION_DOWN,
10651                                             nm_act_request_get_settings_connection (req),
10652                                             nm_act_request_get_applied_connection (req),
10653                                             self, NULL, NULL, NULL);
10654                 }
10655         }
10656
10657         /* IP-related properties are only valid when the device has IP configuration.
10658          * If it no longer does, ensure their change notifications are emitted.
10659          */
10660         if (ip_config_valid (old_state) && !ip_config_valid (state))
10661             notify_ip_properties (self);
10662
10663         /* Dispose of the cached activation request */
10664         if (req)
10665                 g_object_unref (req);
10666
10667         priv->in_state_changed = FALSE;
10668
10669         if ((old_state > NM_DEVICE_STATE_UNMANAGED) != (state > NM_DEVICE_STATE_UNMANAGED))
10670                 _notify (self, PROP_MANAGED);
10671 }
10672
10673 void
10674 nm_device_state_changed (NMDevice *self,
10675                          NMDeviceState state,
10676                          NMDeviceStateReason reason)
10677 {
10678         _set_state_full (self, state, reason, FALSE);
10679 }
10680
10681 static gboolean
10682 queued_set_state (gpointer user_data)
10683 {
10684         NMDevice *self = NM_DEVICE (user_data);
10685         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
10686         NMDeviceState new_state;
10687         NMDeviceStateReason new_reason;
10688
10689         if (priv->queued_state.id) {
10690                 _LOGD (LOGD_DEVICE, "running queued state change to %s (id %d)",
10691                        state_to_string (priv->queued_state.state),
10692                        priv->queued_state.id);
10693
10694                 /* Clear queued state struct before triggering state change, since
10695                  * the state change may queue another state.
10696                  */
10697                 priv->queued_state.id = 0;
10698                 new_state = priv->queued_state.state;
10699                 new_reason = priv->queued_state.reason;
10700                 nm_device_queued_state_clear (self);
10701
10702                 nm_device_state_changed (self, new_state, new_reason);
10703                 nm_device_remove_pending_action (self, queued_state_to_string (new_state), TRUE);
10704         } else {
10705                 g_warn_if_fail (priv->queued_state.state == NM_DEVICE_STATE_UNKNOWN);
10706                 g_warn_if_fail (priv->queued_state.reason == NM_DEVICE_STATE_REASON_NONE);
10707         }
10708         return FALSE;
10709 }
10710
10711 void
10712 nm_device_queue_state (NMDevice *self,
10713                        NMDeviceState state,
10714                        NMDeviceStateReason reason)
10715 {
10716         NMDevicePrivate *priv;
10717
10718         g_return_if_fail (NM_IS_DEVICE (self));
10719
10720         priv = NM_DEVICE_GET_PRIVATE (self);
10721
10722         if (priv->queued_state.id && priv->queued_state.state == state)
10723                 return;
10724
10725         /* Add pending action for the new state before clearing the queued states, so
10726          * that we don't accidently pop all pending states and reach 'startup complete'  */
10727         nm_device_add_pending_action (self, queued_state_to_string (state), TRUE);
10728
10729         /* We should only ever have one delayed state transition at a time */
10730         if (priv->queued_state.id) {
10731                 _LOGW (LOGD_DEVICE, "overwriting previously queued state change to %s (%s)",
10732                        state_to_string (priv->queued_state.state),
10733                        reason_to_string (priv->queued_state.reason));
10734                 nm_device_queued_state_clear (self);
10735         }
10736
10737         priv->queued_state.state = state;
10738         priv->queued_state.reason = reason;
10739         priv->queued_state.id = g_idle_add (queued_set_state, self);
10740
10741         _LOGD (LOGD_DEVICE, "queued state change to %s due to %s (id %d)",
10742                state_to_string (state), reason_to_string (reason),
10743                priv->queued_state.id);
10744 }
10745
10746 NMDeviceState
10747 nm_device_queued_state_peek (NMDevice *self)
10748 {
10749         NMDevicePrivate *priv;
10750
10751         g_return_val_if_fail (NM_IS_DEVICE (self), NM_DEVICE_STATE_UNKNOWN);
10752
10753         priv = NM_DEVICE_GET_PRIVATE (self);
10754
10755         return priv->queued_state.id ? priv->queued_state.state : NM_DEVICE_STATE_UNKNOWN;
10756 }
10757
10758 void
10759 nm_device_queued_state_clear (NMDevice *self)
10760 {
10761         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
10762
10763         if (priv->queued_state.id) {
10764                 _LOGD (LOGD_DEVICE, "clearing queued state transition (id %d)",
10765                        priv->queued_state.id);
10766                 nm_clear_g_source (&priv->queued_state.id);
10767                 nm_device_remove_pending_action (self, queued_state_to_string (priv->queued_state.state), TRUE);
10768         }
10769         memset (&priv->queued_state, 0, sizeof (priv->queued_state));
10770 }
10771
10772 NMDeviceState
10773 nm_device_get_state (NMDevice *self)
10774 {
10775         g_return_val_if_fail (NM_IS_DEVICE (self), NM_DEVICE_STATE_UNKNOWN);
10776
10777         return NM_DEVICE_GET_PRIVATE (self)->state;
10778 }
10779
10780 /***********************************************************/
10781 /* NMConfigDevice interface related stuff */
10782
10783 const char *
10784 nm_device_get_hw_address (NMDevice *self)
10785 {
10786         NMDevicePrivate *priv;
10787
10788         g_return_val_if_fail (NM_IS_DEVICE (self), NULL);
10789         priv = NM_DEVICE_GET_PRIVATE (self);
10790
10791         return priv->hw_addr_len ? priv->hw_addr : NULL;
10792 }
10793
10794 void
10795 nm_device_update_hw_address (NMDevice *self)
10796 {
10797         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
10798         int ifindex = nm_device_get_ifindex (self);
10799         const guint8 *hwaddr;
10800         gsize hwaddrlen = 0;
10801         static const guint8 zero_hwaddr[ETH_ALEN];
10802
10803         if (ifindex <= 0)
10804                 return;
10805
10806         hwaddr = nm_platform_link_get_address (NM_PLATFORM_GET, ifindex, &hwaddrlen);
10807
10808         if (   priv->type == NM_DEVICE_TYPE_ETHERNET
10809             && nm_utils_hwaddr_matches (hwaddr, hwaddrlen, zero_hwaddr, sizeof (zero_hwaddr)))
10810                 hwaddrlen = 0;
10811
10812         if (hwaddrlen) {
10813                 priv->hw_addr_len = hwaddrlen;
10814                 if (!priv->hw_addr || !nm_utils_hwaddr_matches (priv->hw_addr, -1, hwaddr, hwaddrlen)) {
10815                         g_free (priv->hw_addr);
10816                         priv->hw_addr = nm_utils_hwaddr_ntoa (hwaddr, hwaddrlen);
10817
10818                         _LOGD (LOGD_HW | LOGD_DEVICE, "hardware address now %s", priv->hw_addr);
10819                         _notify (self, PROP_HW_ADDRESS);
10820                 }
10821         } else {
10822                 /* Invalid or no hardware address */
10823                 if (priv->hw_addr_len != 0) {
10824                         g_clear_pointer (&priv->hw_addr, g_free);
10825                         priv->hw_addr_len = 0;
10826                         _LOGD (LOGD_HW | LOGD_DEVICE,
10827                                "previous hardware address is no longer valid");
10828                         _notify (self, PROP_HW_ADDRESS);
10829                 }
10830         }
10831 }
10832
10833 void
10834 nm_device_update_initial_hw_address (NMDevice *self)
10835 {
10836         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
10837
10838         if (priv->hw_addr_len) {
10839                 priv->initial_hw_addr = g_strdup (priv->hw_addr);
10840                 _LOGD (LOGD_DEVICE | LOGD_HW, "read initial MAC address %s", priv->initial_hw_addr);
10841
10842                 if (priv->ifindex > 0) {
10843                         guint8 buf[NM_UTILS_HWADDR_LEN_MAX];
10844                         size_t len = 0;
10845
10846                         if (nm_platform_link_get_permanent_address (NM_PLATFORM_GET, priv->ifindex, buf, &len)) {
10847                                 g_warn_if_fail (len == priv->hw_addr_len);
10848                                 priv->perm_hw_addr = nm_utils_hwaddr_ntoa (buf, priv->hw_addr_len);
10849                                 _LOGD (LOGD_DEVICE | LOGD_HW, "read permanent MAC address %s",
10850                                        priv->perm_hw_addr);
10851                         } else {
10852                                 /* Fall back to current address */
10853                                 _LOGD (LOGD_HW | LOGD_ETHER, "unable to read permanent MAC address");
10854                                 priv->perm_hw_addr = g_strdup (priv->hw_addr);
10855                         }
10856                 }
10857         }
10858 }
10859
10860 gboolean
10861 nm_device_set_hw_addr (NMDevice *self, const char *addr,
10862                        const char *detail, guint64 hw_log_domain)
10863 {
10864         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
10865         gboolean success = FALSE;
10866         const char *cur_addr = nm_device_get_hw_address (self);
10867         guint8 addr_bytes[NM_UTILS_HWADDR_LEN_MAX];
10868
10869         /* Fall back to the permanent address */
10870         if (!addr)
10871                 addr = priv->perm_hw_addr;
10872         if (!addr)
10873                 return FALSE;
10874
10875         /* Do nothing if current MAC is same */
10876         if (cur_addr && nm_utils_hwaddr_matches (cur_addr, -1, addr, -1)) {
10877                 _LOGD (LOGD_DEVICE | hw_log_domain, "no MAC address change needed");
10878                 return TRUE;
10879         }
10880         if (!nm_utils_hwaddr_aton (addr, addr_bytes, priv->hw_addr_len)) {
10881                 _LOGW (LOGD_DEVICE | hw_log_domain, "invalid MAC address %s", addr);
10882                 return FALSE;
10883         }
10884
10885         /* Can't change MAC address while device is up */
10886         nm_device_take_down (self, FALSE);
10887
10888         success = nm_platform_link_set_address (NM_PLATFORM_GET, nm_device_get_ip_ifindex (self), addr_bytes, priv->hw_addr_len);
10889         if (success) {
10890                 /* MAC address succesfully changed; update the current MAC to match */
10891                 nm_device_update_hw_address (self);
10892                 cur_addr = nm_device_get_hw_address (self);
10893                 if (cur_addr && nm_utils_hwaddr_matches (cur_addr, -1, addr, -1)) {
10894                         _LOGI (LOGD_DEVICE | hw_log_domain, "%s MAC address to %s",
10895                                detail, addr);
10896                 } else {
10897                         _LOGW (LOGD_DEVICE | hw_log_domain,
10898                                "new MAC address %s not successfully set", addr);
10899                         success = FALSE;
10900                 }
10901         } else {
10902                 _LOGW (LOGD_DEVICE | hw_log_domain, "failed to %s MAC address to %s",
10903                        detail, addr);
10904         }
10905         nm_device_bring_up (self, TRUE, NULL);
10906
10907         return success;
10908 }
10909
10910 const char *
10911 nm_device_get_permanent_hw_address (NMDevice *self)
10912 {
10913         g_return_val_if_fail (NM_IS_DEVICE (self), NULL);
10914
10915         return NM_DEVICE_GET_PRIVATE (self)->perm_hw_addr;
10916 }
10917
10918 const char *
10919 nm_device_get_initial_hw_address (NMDevice *self)
10920 {
10921         g_return_val_if_fail (NM_IS_DEVICE (self), NULL);
10922
10923         return NM_DEVICE_GET_PRIVATE (self)->initial_hw_addr;
10924 }
10925
10926 /**
10927  * nm_device_spec_match_list:
10928  * @self: an #NMDevice
10929  * @specs: (element-type utf8): a list of device specs
10930  *
10931  * Checks if @self matches any of the specifications in @specs. The
10932  * currently-supported spec types are:
10933  *
10934  *     "mac:00:11:22:33:44:55" - matches a device with the given
10935  *     hardware address
10936  *
10937  *     "interface-name:foo0" - matches a device with the given
10938  *     interface name
10939  *
10940  *     "s390-subchannels:00.11.22" - matches a device with the given
10941  *     z/VM / s390 subchannels.
10942  *
10943  *     "*" - matches any device
10944  *
10945  * Returns: #TRUE if @self matches one of the specs in @specs
10946  */
10947 gboolean
10948 nm_device_spec_match_list (NMDevice *self, const GSList *specs)
10949 {
10950         g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
10951
10952         if (!specs)
10953                 return FALSE;
10954
10955         return NM_DEVICE_GET_CLASS (self)->spec_match_list (self, specs) == NM_MATCH_SPEC_MATCH;
10956 }
10957
10958 static NMMatchSpecMatchType
10959 spec_match_list (NMDevice *self, const GSList *specs)
10960 {
10961         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
10962         NMMatchSpecMatchType matched = NM_MATCH_SPEC_NO_MATCH, m;
10963         const GSList *iter;
10964
10965         for (iter = specs; iter; iter = g_slist_next (iter)) {
10966                 if (!strcmp ((const char *) iter->data, "*")) {
10967                         matched = NM_MATCH_SPEC_MATCH;
10968                         break;
10969                 }
10970         }
10971         if (priv->hw_addr_len && priv->hw_addr) {
10972                 m = nm_match_spec_hwaddr (specs, priv->hw_addr);
10973                 matched = MAX (matched, m);
10974         }
10975         if (matched != NM_MATCH_SPEC_NEG_MATCH) {
10976                 m = nm_match_spec_interface_name (specs, nm_device_get_iface (self));
10977                 matched = MAX (matched, m);
10978         }
10979         if (matched != NM_MATCH_SPEC_NEG_MATCH) {
10980                 m = nm_match_spec_device_type (specs, nm_device_get_type_description (self));
10981                 matched = MAX (matched, m);
10982         }
10983         return matched;
10984 }
10985
10986 /***********************************************************/
10987
10988 static const char *
10989 _activation_func_to_string (ActivationHandleFunc func)
10990 {
10991 #define FUNC_TO_STRING_CHECK_AND_RETURN(func, f) \
10992         G_STMT_START { \
10993                 if ((func) == (f)) \
10994                         return #f; \
10995         } G_STMT_END
10996         FUNC_TO_STRING_CHECK_AND_RETURN (func, activate_stage1_device_prepare);
10997         FUNC_TO_STRING_CHECK_AND_RETURN (func, activate_stage2_device_config);
10998         FUNC_TO_STRING_CHECK_AND_RETURN (func, activate_stage3_ip_config_start);
10999         FUNC_TO_STRING_CHECK_AND_RETURN (func, activate_stage4_ip4_config_timeout);
11000         FUNC_TO_STRING_CHECK_AND_RETURN (func, activate_stage4_ip6_config_timeout);
11001         FUNC_TO_STRING_CHECK_AND_RETURN (func, activate_stage5_ip4_config_commit);
11002         FUNC_TO_STRING_CHECK_AND_RETURN (func, activate_stage5_ip6_config_commit);
11003         g_return_val_if_reached ("unknown");
11004 }
11005
11006 /***********************************************************/
11007
11008 static void
11009 nm_device_init (NMDevice *self)
11010 {
11011         NMDevicePrivate *priv;
11012
11013         priv = G_TYPE_INSTANCE_GET_PRIVATE (self, NM_TYPE_DEVICE, NMDevicePrivate);
11014
11015         self->priv = priv;
11016
11017         priv->type = NM_DEVICE_TYPE_UNKNOWN;
11018         priv->capabilities = NM_DEVICE_CAP_NM_SUPPORTED;
11019         priv->state = NM_DEVICE_STATE_UNMANAGED;
11020         priv->state_reason = NM_DEVICE_STATE_REASON_NONE;
11021         priv->dhcp_timeout = 0;
11022         priv->rfkill_type = RFKILL_TYPE_UNKNOWN;
11023         priv->autoconnect = DEFAULT_AUTOCONNECT;
11024         priv->unmanaged_flags = NM_UNMANAGED_PLATFORM_INIT;
11025         priv->unmanaged_mask = priv->unmanaged_flags;
11026         priv->available_connections = g_hash_table_new_full (g_direct_hash, g_direct_equal, g_object_unref, NULL);
11027         priv->ip6_saved_properties = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, g_free);
11028
11029         priv->default_route.v4_is_assumed = TRUE;
11030         priv->default_route.v6_is_assumed = TRUE;
11031
11032         priv->v4_commit_first_time = TRUE;
11033         priv->v6_commit_first_time = TRUE;
11034 }
11035
11036 static GObject*
11037 constructor (GType type,
11038              guint n_construct_params,
11039              GObjectConstructParam *construct_params)
11040 {
11041         GObject *object;
11042         GObjectClass *klass;
11043         NMDevice *self;
11044         NMDevicePrivate *priv;
11045         const NMPlatformLink *pllink;
11046
11047         klass = G_OBJECT_CLASS (nm_device_parent_class);
11048         object = klass->constructor (type, n_construct_params, construct_params);
11049         if (!object)
11050                 return NULL;
11051
11052         self = NM_DEVICE (object);
11053         priv = NM_DEVICE_GET_PRIVATE (self);
11054
11055         if (priv->iface) {
11056                 pllink = nm_platform_link_get_by_ifname (NM_PLATFORM_GET, priv->iface);
11057
11058                 if (pllink && link_type_compatible (self, pllink->type, NULL, NULL)) {
11059                         priv->ifindex = pllink->ifindex;
11060                         priv->up = NM_FLAGS_HAS (pllink->n_ifi_flags, IFF_UP);
11061                 }
11062         }
11063
11064         return object;
11065 }
11066
11067 static void
11068 constructed (GObject *object)
11069 {
11070         NMDevice *self = NM_DEVICE (object);
11071         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
11072         NMPlatform *platform;
11073
11074         platform = nm_platform_get ();
11075
11076         if (NM_DEVICE_GET_CLASS (self)->get_generic_capabilities)
11077                 priv->capabilities |= NM_DEVICE_GET_CLASS (self)->get_generic_capabilities (self);
11078
11079         /* Watch for external IP config changes */
11080         g_signal_connect (platform, NM_PLATFORM_SIGNAL_IP4_ADDRESS_CHANGED, G_CALLBACK (device_ipx_changed), self);
11081         g_signal_connect (platform, NM_PLATFORM_SIGNAL_IP6_ADDRESS_CHANGED, G_CALLBACK (device_ipx_changed), self);
11082         g_signal_connect (platform, NM_PLATFORM_SIGNAL_IP4_ROUTE_CHANGED, G_CALLBACK (device_ipx_changed), self);
11083         g_signal_connect (platform, NM_PLATFORM_SIGNAL_IP6_ROUTE_CHANGED, G_CALLBACK (device_ipx_changed), self);
11084         g_signal_connect (platform, NM_PLATFORM_SIGNAL_LINK_CHANGED, G_CALLBACK (link_changed_cb), self);
11085
11086         priv->con_provider = nm_connection_provider_get ();
11087         g_assert (priv->con_provider);
11088         g_signal_connect (priv->con_provider,
11089                           NM_CP_SIGNAL_CONNECTION_ADDED,
11090                           G_CALLBACK (cp_connection_added_or_updated),
11091                           self);
11092
11093         g_signal_connect (priv->con_provider,
11094                           NM_CP_SIGNAL_CONNECTION_REMOVED,
11095                           G_CALLBACK (cp_connection_removed),
11096                           self);
11097
11098         g_signal_connect (priv->con_provider,
11099                           NM_CP_SIGNAL_CONNECTION_UPDATED,
11100                           G_CALLBACK (cp_connection_added_or_updated),
11101                           self);
11102
11103         G_OBJECT_CLASS (nm_device_parent_class)->constructed (object);
11104
11105         _LOGD (LOGD_DEVICE, "constructed (%s)", G_OBJECT_TYPE_NAME (self));
11106 }
11107
11108 static void
11109 dispose (GObject *object)
11110 {
11111         NMDevice *self = NM_DEVICE (object);
11112         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
11113         NMPlatform *platform;
11114
11115         _LOGD (LOGD_DEVICE, "disposing");
11116
11117         g_slist_free_full (priv->arping.dad_list, (GDestroyNotify) nm_arping_manager_destroy);
11118         priv->arping.dad_list = NULL;
11119
11120         arp_cleanup (self);
11121
11122         g_signal_handlers_disconnect_by_func (nm_config_get (), config_changed_update_ignore_carrier, self);
11123
11124         dispatcher_cleanup (self);
11125
11126         _cleanup_generic_pre (self, CLEANUP_TYPE_KEEP);
11127
11128         g_warn_if_fail (priv->slaves == NULL);
11129         g_assert (priv->master_ready_id == 0);
11130
11131         /* Let the kernel manage IPv6LL again */
11132         set_nm_ipv6ll (self, FALSE);
11133
11134         _cleanup_generic_post (self, CLEANUP_TYPE_KEEP);
11135
11136         g_hash_table_remove_all (priv->ip6_saved_properties);
11137
11138         nm_clear_g_source (&priv->recheck_assume_id);
11139         nm_clear_g_source (&priv->recheck_available.call_id);
11140
11141         nm_clear_g_source (&priv->check_delete_unrealized_id);
11142
11143         link_disconnect_action_cancel (self);
11144
11145         if (priv->con_provider) {
11146                 g_signal_handlers_disconnect_by_func (priv->con_provider, cp_connection_added_or_updated, self);
11147                 g_signal_handlers_disconnect_by_func (priv->con_provider, cp_connection_removed, self);
11148                 priv->con_provider = NULL;
11149         }
11150
11151         available_connections_del_all (self);
11152
11153         nm_clear_g_source (&priv->carrier_wait_id);
11154
11155         _clear_queued_act_request (priv);
11156
11157         platform = nm_platform_get ();
11158         g_signal_handlers_disconnect_by_func (platform, G_CALLBACK (device_ipx_changed), self);
11159         g_signal_handlers_disconnect_by_func (platform, G_CALLBACK (link_changed_cb), self);
11160
11161         nm_clear_g_source (&priv->device_link_changed_id);
11162         nm_clear_g_source (&priv->device_ip_link_changed_id);
11163
11164         if (priv->lldp_listener) {
11165                 g_signal_handlers_disconnect_by_func (priv->lldp_listener,
11166                                                       G_CALLBACK (lldp_neighbors_changed),
11167                                                       self);
11168                 nm_lldp_listener_stop (priv->lldp_listener);
11169                 g_clear_object (&priv->lldp_listener);
11170         }
11171
11172         G_OBJECT_CLASS (nm_device_parent_class)->dispose (object);
11173
11174         if (nm_clear_g_source (&priv->queued_state.id)) {
11175                 /* FIXME: we'd expect the queud_state to be alredy cleared and this statement
11176                  * not being necessary. Add this check here to hopefully investigate crash
11177                  * rh#1270247. */
11178                 g_return_if_reached ();
11179         }
11180 }
11181
11182 static void
11183 finalize (GObject *object)
11184 {
11185         NMDevice *self = NM_DEVICE (object);
11186         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
11187
11188         _LOGD (LOGD_DEVICE, "finalize(): %s", G_OBJECT_TYPE_NAME (self));
11189
11190         g_free (priv->hw_addr);
11191         g_free (priv->perm_hw_addr);
11192         g_free (priv->initial_hw_addr);
11193         g_slist_free_full (priv->pending_actions, g_free);
11194         g_slist_free_full (priv->dad6_failed_addrs, g_free);
11195         g_clear_pointer (&priv->physical_port_id, g_free);
11196         g_free (priv->udi);
11197         g_free (priv->iface);
11198         g_free (priv->ip_iface);
11199         g_free (priv->driver);
11200         g_free (priv->driver_version);
11201         g_free (priv->firmware_version);
11202         g_free (priv->type_desc);
11203         g_free (priv->type_description);
11204         g_free (priv->dhcp_anycast_address);
11205
11206         g_hash_table_unref (priv->ip6_saved_properties);
11207         g_hash_table_unref (priv->available_connections);
11208
11209         G_OBJECT_CLASS (nm_device_parent_class)->finalize (object);
11210 }
11211
11212 static void
11213 set_property (GObject *object, guint prop_id,
11214               const GValue *value, GParamSpec *pspec)
11215 {
11216         NMDevice *self = NM_DEVICE (object);
11217         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
11218         const char *hw_addr, *p;
11219         guint count;
11220
11221         switch (prop_id) {
11222         case PROP_UDI:
11223                 if (g_value_get_string (value)) {
11224                         g_free (priv->udi);
11225                         priv->udi = g_value_dup_string (value);
11226                 }
11227                 break;
11228         case PROP_IFACE:
11229                 /* construct only */
11230                 g_return_if_fail (!priv->iface);
11231                 priv->iface = g_value_dup_string (value);
11232                 break;
11233         case PROP_DRIVER:
11234                 if (g_value_get_string (value)) {
11235                         g_free (priv->driver);
11236                         priv->driver = g_value_dup_string (value);
11237                 }
11238                 break;
11239         case PROP_DRIVER_VERSION:
11240                 g_free (priv->driver_version);
11241                 priv->driver_version = g_strdup (g_value_get_string (value));
11242                 break;
11243         case PROP_FIRMWARE_VERSION:
11244                 g_free (priv->firmware_version);
11245                 priv->firmware_version = g_strdup (g_value_get_string (value));
11246                 break;
11247         case PROP_MTU:
11248                 priv->mtu = g_value_get_uint (value);
11249                 break;
11250         case PROP_IP4_ADDRESS:
11251                 priv->ip4_address = g_value_get_uint (value);
11252                 break;
11253         case PROP_MANAGED: {
11254                 gboolean managed;
11255                 NMDeviceStateReason reason;
11256
11257                 managed = g_value_get_boolean (value);
11258                 if (managed)
11259                         reason = NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED;
11260                 else
11261                         reason = NM_DEVICE_STATE_REASON_REMOVED;
11262                 nm_device_set_unmanaged_by_flags (self,
11263                                                   NM_UNMANAGED_USER_EXPLICIT,
11264                                                   !managed,
11265                                                   reason);
11266                 break;
11267         }
11268         case PROP_AUTOCONNECT:
11269                 nm_device_set_autoconnect (self, g_value_get_boolean (value));
11270                 break;
11271         case PROP_FIRMWARE_MISSING:
11272                 /* construct only */
11273                 priv->firmware_missing = g_value_get_boolean (value);
11274                 break;
11275         case PROP_NM_PLUGIN_MISSING:
11276                 priv->nm_plugin_missing = g_value_get_boolean (value);
11277                 break;
11278         case PROP_DEVICE_TYPE:
11279                 g_return_if_fail (priv->type == NM_DEVICE_TYPE_UNKNOWN);
11280                 priv->type = g_value_get_uint (value);
11281                 break;
11282         case PROP_LINK_TYPE:
11283                 /* construct only */
11284                 g_return_if_fail (priv->link_type == NM_LINK_TYPE_NONE);
11285                 priv->link_type = g_value_get_uint (value);
11286                 break;
11287         case PROP_TYPE_DESC:
11288                 g_free (priv->type_desc);
11289                 priv->type_desc = g_value_dup_string (value);
11290                 break;
11291         case PROP_RFKILL_TYPE:
11292                 priv->rfkill_type = g_value_get_uint (value);
11293                 break;
11294         case PROP_IS_MASTER:
11295                 priv->is_master = g_value_get_boolean (value);
11296                 break;
11297         case PROP_HW_ADDRESS:
11298                 /* construct only */
11299                 p = hw_addr = g_value_get_string (value);
11300
11301                 /* Hardware address length is the number of ':' plus 1 */
11302                 count = 1;
11303                 while (p && *p) {
11304                         if (*p++ == ':')
11305                                 count++;
11306                 }
11307                 if (count < ETH_ALEN || count > NM_UTILS_HWADDR_LEN_MAX) {
11308                         if (hw_addr && *hw_addr) {
11309                                 _LOGW (LOGD_DEVICE, "ignoring hardware address '%s' with unexpected length %d",
11310                                        hw_addr, count);
11311                         }
11312                         break;
11313                 }
11314
11315                 priv->hw_addr_len = count;
11316                 g_free (priv->hw_addr);
11317                 if (nm_utils_hwaddr_valid (hw_addr, priv->hw_addr_len))
11318                         priv->hw_addr = g_strdup (hw_addr);
11319                 else {
11320                         _LOGW (LOGD_DEVICE, "could not parse hw-address '%s'", hw_addr);
11321                         priv->hw_addr = NULL;
11322                 }
11323                 break;
11324         default:
11325                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
11326                 break;
11327         }
11328 }
11329
11330 static void
11331 get_property (GObject *object, guint prop_id,
11332               GValue *value, GParamSpec *pspec)
11333 {
11334         NMDevice *self = NM_DEVICE (object);
11335         NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
11336         GPtrArray *array;
11337         GHashTableIter iter;
11338         NMConnection *connection;
11339         GVariantBuilder array_builder;
11340
11341         switch (prop_id) {
11342         case PROP_UDI:
11343                 g_value_set_string (value, priv->udi);
11344                 break;
11345         case PROP_IFACE:
11346                 g_value_set_string (value, priv->iface);
11347                 break;
11348         case PROP_IP_IFACE:
11349                 if (ip_config_valid (priv->state))
11350                         g_value_set_string (value, nm_device_get_ip_iface (self));
11351                 else
11352                         g_value_set_string (value, NULL);
11353                 break;
11354         case PROP_IFINDEX:
11355                 g_value_set_int (value, priv->ifindex);
11356                 break;
11357         case PROP_DRIVER:
11358                 g_value_set_string (value, priv->driver);
11359                 break;
11360         case PROP_DRIVER_VERSION:
11361                 g_value_set_string (value, priv->driver_version);
11362                 break;
11363         case PROP_FIRMWARE_VERSION:
11364                 g_value_set_string (value, priv->firmware_version);
11365                 break;
11366         case PROP_CAPABILITIES:
11367                 g_value_set_uint (value, (priv->capabilities & ~NM_DEVICE_CAP_INTERNAL_MASK));
11368                 break;
11369         case PROP_IP4_ADDRESS:
11370                 g_value_set_uint (value, priv->ip4_address);
11371                 break;
11372         case PROP_CARRIER:
11373                 g_value_set_boolean (value, priv->carrier);
11374                 break;
11375         case PROP_MTU:
11376                 g_value_set_uint (value, priv->mtu);
11377                 break;
11378         case PROP_IP4_CONFIG:
11379                 nm_utils_g_value_set_object_path (value, ip_config_valid (priv->state) ? priv->ip4_config : NULL);
11380                 break;
11381         case PROP_DHCP4_CONFIG:
11382                 nm_utils_g_value_set_object_path (value, ip_config_valid (priv->state) ? priv->dhcp4_config : NULL);
11383                 break;
11384         case PROP_IP6_CONFIG:
11385                 nm_utils_g_value_set_object_path (value, ip_config_valid (priv->state) ? priv->ip6_config : NULL);
11386                 break;
11387         case PROP_DHCP6_CONFIG:
11388                 nm_utils_g_value_set_object_path (value, ip_config_valid (priv->state) ? priv->dhcp6_config : NULL);
11389                 break;
11390         case PROP_STATE:
11391                 g_value_set_uint (value, priv->state);
11392                 break;
11393         case PROP_STATE_REASON:
11394                 g_value_take_variant (value,
11395                                       g_variant_new ("(uu)", priv->state, priv->state_reason));
11396                 break;
11397         case PROP_ACTIVE_CONNECTION:
11398                 nm_utils_g_value_set_object_path (value, priv->act_request);
11399                 break;
11400         case PROP_DEVICE_TYPE:
11401                 g_value_set_uint (value, priv->type);
11402                 break;
11403         case PROP_LINK_TYPE:
11404                 g_value_set_uint (value, priv->link_type);
11405                 break;
11406         case PROP_MANAGED:
11407                 /* The managed state exposed on D-Bus only depends on the current device state alone. */
11408                 g_value_set_boolean (value, nm_device_get_state (self) > NM_DEVICE_STATE_UNMANAGED);
11409                 break;
11410         case PROP_AUTOCONNECT:
11411                 g_value_set_boolean (value, priv->autoconnect);
11412                 break;
11413         case PROP_FIRMWARE_MISSING:
11414                 g_value_set_boolean (value, priv->firmware_missing);
11415                 break;
11416         case PROP_NM_PLUGIN_MISSING:
11417                 g_value_set_boolean (value, priv->nm_plugin_missing);
11418                 break;
11419         case PROP_TYPE_DESC:
11420                 g_value_set_string (value, priv->type_desc);
11421                 break;
11422         case PROP_RFKILL_TYPE:
11423                 g_value_set_uint (value, priv->rfkill_type);
11424                 break;
11425         case PROP_AVAILABLE_CONNECTIONS:
11426                 array = g_ptr_array_sized_new (g_hash_table_size (priv->available_connections));
11427                 g_hash_table_iter_init (&iter, priv->available_connections);
11428                 while (g_hash_table_iter_next (&iter, (gpointer) &connection, NULL))
11429                         g_ptr_array_add (array, g_strdup (nm_connection_get_path (connection)));
11430                 g_ptr_array_add (array, NULL);
11431                 g_value_take_boxed (value, (char **) g_ptr_array_free (array, FALSE));
11432                 break;
11433         case PROP_PHYSICAL_PORT_ID:
11434                 g_value_set_string (value, priv->physical_port_id);
11435                 break;
11436         case PROP_IS_MASTER:
11437                 g_value_set_boolean (value, priv->is_master);
11438                 break;
11439         case PROP_MASTER:
11440                 g_value_set_object (value, nm_device_get_master (self));
11441                 break;
11442         case PROP_HW_ADDRESS:
11443                 g_value_set_string (value, priv->hw_addr);
11444                 break;
11445         case PROP_HAS_PENDING_ACTION:
11446                 g_value_set_boolean (value, nm_device_has_pending_action (self));
11447                 break;
11448         case PROP_METERED:
11449                 g_value_set_uint (value, priv->metered);
11450                 break;
11451         case PROP_LLDP_NEIGHBORS:
11452                 if (priv->lldp_listener)
11453                         g_value_set_variant (value, nm_lldp_listener_get_neighbors (priv->lldp_listener));
11454                 else {
11455                         g_variant_builder_init (&array_builder, G_VARIANT_TYPE ("aa{sv}"));
11456                         g_value_take_variant (value, g_variant_builder_end (&array_builder));
11457                 }
11458                 break;
11459         case PROP_REAL:
11460                 g_value_set_boolean (value, nm_device_is_real (self));
11461                 break;
11462         case PROP_SLAVES: {
11463                 GSList *slave_iter;
11464                 char **slave_list;
11465                 guint i;
11466
11467                 slave_list = g_new (char *, g_slist_length (priv->slaves) + 1);
11468                 for (slave_iter = priv->slaves, i = 0; slave_iter; slave_iter = slave_iter->next) {
11469                         SlaveInfo *info = slave_iter->data;
11470                         const char *path;
11471
11472                         if (!NM_DEVICE_GET_PRIVATE (info->slave)->is_enslaved)
11473                                 continue;
11474                         path = nm_exported_object_get_path ((NMExportedObject *) info->slave);
11475                         if (path)
11476                                 slave_list[i++] = g_strdup (path);
11477                 }
11478                 slave_list[i] = NULL;
11479                 g_value_take_boxed (value, slave_list);
11480                 break;
11481         }
11482         default:
11483                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
11484                 break;
11485         }
11486 }
11487
11488 static void
11489 nm_device_class_init (NMDeviceClass *klass)
11490 {
11491         GObjectClass *object_class = G_OBJECT_CLASS (klass);
11492         NMExportedObjectClass *exported_object_class = NM_EXPORTED_OBJECT_CLASS (klass);
11493
11494         g_type_class_add_private (object_class, sizeof (NMDevicePrivate));
11495
11496         exported_object_class->export_path = NM_DBUS_PATH "/Devices/%u";
11497
11498         /* Virtual methods */
11499         object_class->dispose = dispose;
11500         object_class->finalize = finalize;
11501         object_class->set_property = set_property;
11502         object_class->get_property = get_property;
11503         object_class->constructor = constructor;
11504         object_class->constructed = constructed;
11505
11506         klass->link_changed = link_changed;
11507
11508         klass->is_available = is_available;
11509         klass->act_stage1_prepare = act_stage1_prepare;
11510         klass->act_stage2_config = act_stage2_config;
11511         klass->act_stage3_ip4_config_start = act_stage3_ip4_config_start;
11512         klass->act_stage3_ip6_config_start = act_stage3_ip6_config_start;
11513         klass->act_stage4_ip4_config_timeout = act_stage4_ip4_config_timeout;
11514         klass->act_stage4_ip6_config_timeout = act_stage4_ip6_config_timeout;
11515         klass->have_any_ready_slaves = have_any_ready_slaves;
11516
11517         klass->get_type_description = get_type_description;
11518         klass->spec_match_list = spec_match_list;
11519         klass->can_auto_connect = can_auto_connect;
11520         klass->check_connection_compatible = check_connection_compatible;
11521         klass->check_connection_available = check_connection_available;
11522         klass->can_unmanaged_external_down = can_unmanaged_external_down;
11523         klass->realize_start_notify = realize_start_notify;
11524         klass->unrealize_notify = unrealize_notify;
11525         klass->is_up = is_up;
11526         klass->bring_up = bring_up;
11527         klass->take_down = take_down;
11528         klass->carrier_changed = carrier_changed;
11529         klass->get_ip_iface_identifier = get_ip_iface_identifier;
11530
11531         /* Properties */
11532         obj_properties[PROP_UDI] =
11533             g_param_spec_string (NM_DEVICE_UDI, "", "",
11534                                  NULL,
11535                                  G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
11536                                  G_PARAM_STATIC_STRINGS);
11537         obj_properties[PROP_IFACE] =
11538             g_param_spec_string (NM_DEVICE_IFACE, "", "",
11539                                  NULL,
11540                                  G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
11541                                  G_PARAM_STATIC_STRINGS);
11542         obj_properties[PROP_IP_IFACE] =
11543             g_param_spec_string (NM_DEVICE_IP_IFACE, "", "",
11544                                  NULL,
11545                                  G_PARAM_READABLE |
11546                                  G_PARAM_STATIC_STRINGS);
11547         obj_properties[PROP_DRIVER] =
11548             g_param_spec_string (NM_DEVICE_DRIVER, "", "",
11549                                  NULL,
11550                                  G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
11551                                  G_PARAM_STATIC_STRINGS);
11552         obj_properties[PROP_DRIVER_VERSION] =
11553             g_param_spec_string (NM_DEVICE_DRIVER_VERSION, "", "",
11554                                  NULL,
11555                                  G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
11556                                  G_PARAM_STATIC_STRINGS);
11557         obj_properties[PROP_FIRMWARE_VERSION] =
11558             g_param_spec_string (NM_DEVICE_FIRMWARE_VERSION, "", "",
11559                                  NULL,
11560                                  G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
11561                                  G_PARAM_STATIC_STRINGS);
11562         obj_properties[PROP_CAPABILITIES] =
11563             g_param_spec_uint (NM_DEVICE_CAPABILITIES, "", "",
11564                                0, G_MAXUINT32, NM_DEVICE_CAP_NONE,
11565                                G_PARAM_READABLE |
11566                                G_PARAM_STATIC_STRINGS);
11567         obj_properties[PROP_CARRIER] =
11568             g_param_spec_boolean (NM_DEVICE_CARRIER, "", "",
11569                                   FALSE,
11570                                   G_PARAM_READABLE |
11571                                   G_PARAM_STATIC_STRINGS);
11572         obj_properties[PROP_MTU] =
11573             g_param_spec_uint (NM_DEVICE_MTU, "", "",
11574                                0, G_MAXUINT32, 1500,
11575                                G_PARAM_READABLE |
11576                                G_PARAM_STATIC_STRINGS);
11577         obj_properties[PROP_IP4_ADDRESS] =
11578             g_param_spec_uint (NM_DEVICE_IP4_ADDRESS, "", "",
11579                                0, G_MAXUINT32, 0, /* FIXME */
11580                                G_PARAM_READWRITE |
11581                                G_PARAM_STATIC_STRINGS);
11582         obj_properties[PROP_IP4_CONFIG] =
11583             g_param_spec_string (NM_DEVICE_IP4_CONFIG, "", "",
11584                                  NULL,
11585                                  G_PARAM_READWRITE |
11586                                  G_PARAM_STATIC_STRINGS);
11587         obj_properties[PROP_DHCP4_CONFIG] =
11588             g_param_spec_string (NM_DEVICE_DHCP4_CONFIG, "", "",
11589                                  NULL,
11590                                  G_PARAM_READWRITE |
11591                                  G_PARAM_STATIC_STRINGS);
11592         obj_properties[PROP_IP6_CONFIG] =
11593             g_param_spec_string (NM_DEVICE_IP6_CONFIG, "", "",
11594                                  NULL,
11595                                  G_PARAM_READWRITE |
11596                                  G_PARAM_STATIC_STRINGS);
11597         obj_properties[PROP_DHCP6_CONFIG] =
11598             g_param_spec_string (NM_DEVICE_DHCP6_CONFIG, "", "",
11599                                  NULL,
11600                                  G_PARAM_READWRITE |
11601                                  G_PARAM_STATIC_STRINGS);
11602         obj_properties[PROP_STATE] =
11603             g_param_spec_uint (NM_DEVICE_STATE, "", "",
11604                                0, G_MAXUINT32, NM_DEVICE_STATE_UNKNOWN,
11605                                G_PARAM_READABLE |
11606                                G_PARAM_STATIC_STRINGS);
11607         obj_properties[PROP_STATE_REASON] =
11608             g_param_spec_variant (NM_DEVICE_STATE_REASON, "", "",
11609                                   G_VARIANT_TYPE ("(uu)"),
11610                                   NULL,
11611                                   G_PARAM_READABLE |
11612                                   G_PARAM_STATIC_STRINGS);
11613         obj_properties[PROP_ACTIVE_CONNECTION] =
11614             g_param_spec_string (NM_DEVICE_ACTIVE_CONNECTION, "", "",
11615                                  NULL,
11616                                  G_PARAM_READABLE |
11617                                  G_PARAM_STATIC_STRINGS);
11618         obj_properties[PROP_DEVICE_TYPE] =
11619             g_param_spec_uint (NM_DEVICE_DEVICE_TYPE, "", "",
11620                                0, G_MAXUINT32, NM_DEVICE_TYPE_UNKNOWN,
11621                                G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
11622                                G_PARAM_STATIC_STRINGS);
11623         obj_properties[PROP_LINK_TYPE] =
11624             g_param_spec_uint (NM_DEVICE_LINK_TYPE, "", "",
11625                                0, G_MAXUINT32, NM_LINK_TYPE_NONE,
11626                                G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
11627                                G_PARAM_STATIC_STRINGS);
11628         obj_properties[PROP_MANAGED] =
11629             g_param_spec_boolean (NM_DEVICE_MANAGED, "", "",
11630                                   FALSE,
11631                                   G_PARAM_READWRITE |
11632                                   G_PARAM_STATIC_STRINGS);
11633         obj_properties[PROP_AUTOCONNECT] =
11634             g_param_spec_boolean (NM_DEVICE_AUTOCONNECT, "", "",
11635                                   DEFAULT_AUTOCONNECT,
11636                                   G_PARAM_READWRITE |
11637                                   G_PARAM_STATIC_STRINGS);
11638         obj_properties[PROP_FIRMWARE_MISSING] =
11639             g_param_spec_boolean (NM_DEVICE_FIRMWARE_MISSING, "", "",
11640                                   FALSE,
11641                                   G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
11642                                   G_PARAM_STATIC_STRINGS);
11643         obj_properties[PROP_NM_PLUGIN_MISSING] =
11644             g_param_spec_boolean (NM_DEVICE_NM_PLUGIN_MISSING, "", "",
11645                                   FALSE,
11646                                   G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
11647                                   G_PARAM_STATIC_STRINGS);
11648         obj_properties[PROP_TYPE_DESC] =
11649             g_param_spec_string (NM_DEVICE_TYPE_DESC, "", "",
11650                                  NULL,
11651                                  G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
11652                                  G_PARAM_STATIC_STRINGS);
11653         obj_properties[PROP_RFKILL_TYPE] =
11654             g_param_spec_uint (NM_DEVICE_RFKILL_TYPE, "", "",
11655                                RFKILL_TYPE_WLAN,
11656                                RFKILL_TYPE_MAX,
11657                                RFKILL_TYPE_UNKNOWN,
11658                                G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
11659                                G_PARAM_STATIC_STRINGS);
11660         obj_properties[PROP_IFINDEX] =
11661             g_param_spec_int (NM_DEVICE_IFINDEX, "", "",
11662                               0, G_MAXINT, 0,
11663                               G_PARAM_READABLE |
11664                               G_PARAM_STATIC_STRINGS);
11665         obj_properties[PROP_AVAILABLE_CONNECTIONS] =
11666             g_param_spec_boxed (NM_DEVICE_AVAILABLE_CONNECTIONS, "", "",
11667                                 G_TYPE_STRV,
11668                                 G_PARAM_READABLE |
11669                                 G_PARAM_STATIC_STRINGS);
11670         obj_properties[PROP_PHYSICAL_PORT_ID] =
11671             g_param_spec_string (NM_DEVICE_PHYSICAL_PORT_ID, "", "",
11672                                  NULL,
11673                                  G_PARAM_READABLE |
11674                                  G_PARAM_STATIC_STRINGS);
11675         obj_properties[PROP_IS_MASTER] =
11676             g_param_spec_boolean (NM_DEVICE_IS_MASTER, "", "",
11677                                   FALSE,
11678                                   G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
11679                                   G_PARAM_STATIC_STRINGS);
11680         obj_properties[PROP_MASTER] =
11681             g_param_spec_object (NM_DEVICE_MASTER, "", "",
11682                                  NM_TYPE_DEVICE,
11683                                  G_PARAM_READABLE |
11684                                  G_PARAM_STATIC_STRINGS);
11685         obj_properties[PROP_HW_ADDRESS] =
11686             g_param_spec_string (NM_DEVICE_HW_ADDRESS, "", "",
11687                                  NULL,
11688                                  G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
11689                                  G_PARAM_STATIC_STRINGS);
11690         obj_properties[PROP_HAS_PENDING_ACTION] =
11691             g_param_spec_boolean (NM_DEVICE_HAS_PENDING_ACTION, "", "",
11692                                   FALSE,
11693                                   G_PARAM_READABLE |
11694                                   G_PARAM_STATIC_STRINGS);
11695
11696         /**
11697          * NMDevice:metered:
11698          *
11699          * Whether the connection is metered.
11700          *
11701          * Since: 1.2
11702          **/
11703         obj_properties[PROP_METERED] =
11704             g_param_spec_uint (NM_DEVICE_METERED, "", "",
11705                                0, G_MAXUINT32, NM_METERED_UNKNOWN,
11706                                G_PARAM_READABLE |
11707                                G_PARAM_STATIC_STRINGS);
11708         obj_properties[PROP_LLDP_NEIGHBORS] =
11709             g_param_spec_variant (NM_DEVICE_LLDP_NEIGHBORS, "", "",
11710                                   G_VARIANT_TYPE ("aa{sv}"),
11711                                   NULL,
11712                                   G_PARAM_READABLE |
11713                                   G_PARAM_STATIC_STRINGS);
11714         obj_properties[PROP_REAL] =
11715             g_param_spec_boolean (NM_DEVICE_REAL, "", "",
11716                                   FALSE,
11717                                   G_PARAM_READABLE |
11718                                   G_PARAM_STATIC_STRINGS);
11719         obj_properties[PROP_SLAVES] =
11720             g_param_spec_boxed (NM_DEVICE_SLAVES, "", "",
11721                                 G_TYPE_STRV,
11722                                 G_PARAM_READABLE |
11723                                 G_PARAM_STATIC_STRINGS);
11724
11725         g_object_class_install_properties (object_class, _PROPERTY_ENUMS_LAST, obj_properties);
11726
11727         /* Signals */
11728         signals[STATE_CHANGED] =
11729             g_signal_new (NM_DEVICE_STATE_CHANGED,
11730                           G_OBJECT_CLASS_TYPE (object_class),
11731                           G_SIGNAL_RUN_LAST,
11732                           G_STRUCT_OFFSET (NMDeviceClass, state_changed),
11733                           NULL, NULL, NULL,
11734                           G_TYPE_NONE, 3,
11735                           G_TYPE_UINT, G_TYPE_UINT, G_TYPE_UINT);
11736
11737         signals[AUTOCONNECT_ALLOWED] =
11738             g_signal_new ("autoconnect-allowed",
11739                           G_OBJECT_CLASS_TYPE (object_class),
11740                           G_SIGNAL_RUN_LAST,
11741                           0,
11742                           autoconnect_allowed_accumulator, NULL, NULL,
11743                           G_TYPE_BOOLEAN, 0);
11744
11745         signals[AUTH_REQUEST] =
11746             g_signal_new (NM_DEVICE_AUTH_REQUEST,
11747                           G_OBJECT_CLASS_TYPE (object_class),
11748                           G_SIGNAL_RUN_FIRST,
11749                           0, NULL, NULL, NULL,
11750                           /* context, connection, permission, allow_interaction, callback, user_data */
11751                           G_TYPE_NONE, 6, G_TYPE_DBUS_METHOD_INVOCATION, NM_TYPE_CONNECTION, G_TYPE_STRING, G_TYPE_BOOLEAN, G_TYPE_POINTER, G_TYPE_POINTER);
11752
11753         signals[IP4_CONFIG_CHANGED] =
11754             g_signal_new (NM_DEVICE_IP4_CONFIG_CHANGED,
11755                           G_OBJECT_CLASS_TYPE (object_class),
11756                           G_SIGNAL_RUN_FIRST,
11757                           0, NULL, NULL, NULL,
11758                           G_TYPE_NONE, 2, G_TYPE_OBJECT, G_TYPE_OBJECT);
11759
11760         signals[IP6_CONFIG_CHANGED] =
11761             g_signal_new (NM_DEVICE_IP6_CONFIG_CHANGED,
11762                           G_OBJECT_CLASS_TYPE (object_class),
11763                           G_SIGNAL_RUN_FIRST,
11764                           0, NULL, NULL, NULL,
11765                           G_TYPE_NONE, 2, G_TYPE_OBJECT, G_TYPE_OBJECT);
11766
11767         signals[REMOVED] =
11768             g_signal_new (NM_DEVICE_REMOVED,
11769                           G_OBJECT_CLASS_TYPE (object_class),
11770                           G_SIGNAL_RUN_FIRST,
11771                           0, NULL, NULL, NULL,
11772                           G_TYPE_NONE, 0);
11773
11774         signals[RECHECK_AUTO_ACTIVATE] =
11775             g_signal_new (NM_DEVICE_RECHECK_AUTO_ACTIVATE,
11776                           G_OBJECT_CLASS_TYPE (object_class),
11777                           G_SIGNAL_RUN_FIRST,
11778                           0, NULL, NULL, NULL,
11779                           G_TYPE_NONE, 0);
11780
11781         signals[RECHECK_ASSUME] =
11782             g_signal_new (NM_DEVICE_RECHECK_ASSUME,
11783                           G_OBJECT_CLASS_TYPE (object_class),
11784                           G_SIGNAL_RUN_FIRST,
11785                           0, NULL, NULL, NULL,
11786                           G_TYPE_NONE, 0);
11787
11788         nm_exported_object_class_add_interface (NM_EXPORTED_OBJECT_CLASS (klass),
11789                                                 NMDBUS_TYPE_DEVICE_SKELETON,
11790                                                 "Reapply", impl_device_reapply,
11791                                                 "GetAppliedConnection", impl_device_get_applied_connection,
11792                                                 "Disconnect", impl_device_disconnect,
11793                                                 "Delete", impl_device_delete,
11794                                                 NULL);
11795 }