summary refs log tree commit diff
path: root/src/core/devices/wifi
diff options
context:
space:
mode:
Diffstat (limited to 'src/core/devices/wifi')
-rw-r--r--src/core/devices/wifi/meson.build75
-rw-r--r--src/core/devices/wifi/nm-device-iwd.c3508
-rw-r--r--src/core/devices/wifi/nm-device-iwd.h49
-rw-r--r--src/core/devices/wifi/nm-device-olpc-mesh.c551
-rw-r--r--src/core/devices/wifi/nm-device-olpc-mesh.h38
-rw-r--r--src/core/devices/wifi/nm-device-wifi-p2p.c1280
-rw-r--r--src/core/devices/wifi/nm-device-wifi-p2p.h38
-rw-r--r--src/core/devices/wifi/nm-device-wifi.c3879
-rw-r--r--src/core/devices/wifi/nm-device-wifi.h52
-rw-r--r--src/core/devices/wifi/nm-iwd-manager.c1359
-rw-r--r--src/core/devices/wifi/nm-iwd-manager.h53
-rw-r--r--src/core/devices/wifi/nm-wifi-ap.c1051
-rw-r--r--src/core/devices/wifi/nm-wifi-ap.h96
-rw-r--r--src/core/devices/wifi/nm-wifi-common.c176
-rw-r--r--src/core/devices/wifi/nm-wifi-common.h22
-rw-r--r--src/core/devices/wifi/nm-wifi-factory.c157
-rw-r--r--src/core/devices/wifi/nm-wifi-p2p-peer.c699
-rw-r--r--src/core/devices/wifi/nm-wifi-p2p-peer.h91
-rw-r--r--src/core/devices/wifi/nm-wifi-utils.c945
-rw-r--r--src/core/devices/wifi/nm-wifi-utils.h39
-rw-r--r--src/core/devices/wifi/tests/test-devices-wifi.c1609
21 files changed, 15767 insertions, 0 deletions
diff --git a/src/core/devices/wifi/meson.build b/src/core/devices/wifi/meson.build
new file mode 100644
index 00000000..743937db
--- /dev/null
+++ b/src/core/devices/wifi/meson.build
@@ -0,0 +1,75 @@
+# SPDX-License-Identifier: LGPL-2.1-or-later
+
+iwd_sources = files()
+if enable_iwd
+  iwd_sources += files(
+    'nm-device-iwd.c',
+    'nm-iwd-manager.c',
+  )
+endif
+
+libnm_device_plugin_wifi_static = static_library(
+  'nm-device-plugin-wifi-static',
+  sources: files(
+    'nm-device-olpc-mesh.c',
+    'nm-device-wifi-p2p.c',
+    'nm-device-wifi.c',
+    'nm-wifi-ap.c',
+    'nm-wifi-common.c',
+    'nm-wifi-p2p-peer.c',
+    'nm-wifi-utils.c',
+  ) + iwd_sources,
+  dependencies: [
+    core_plugin_dep,
+  ],
+  c_args: daemon_c_flags,
+)
+
+libnm_device_plugin_wifi_static_dep = declare_dependency(
+  link_with: libnm_device_plugin_wifi_static,
+)
+
+libnm_device_plugin_wifi = shared_module(
+  'nm-device-plugin-wifi',
+  sources: files(
+    'nm-wifi-factory.c',
+  ),
+  dependencies: [
+    core_plugin_dep,
+    libnm_device_plugin_wifi_static_dep
+  ],
+  c_args: daemon_c_flags,
+  link_args: ldflags_linker_script_devices,
+  link_depends: linker_script_devices,
+  install: true,
+  install_dir: nm_plugindir,
+)
+
+core_plugins += libnm_device_plugin_wifi
+
+test(
+  'check-local-devices-wifi',
+  check_exports,
+  args: [libnm_device_plugin_wifi.full_path(), linker_script_devices],
+)
+
+if enable_tests
+  test_unit = 'test-devices-wifi'
+
+  exe = executable(
+    test_unit,
+    'tests/' + test_unit + '.c',
+    dependencies: [
+      libNetworkManagerTest_dep,
+      libnm_device_plugin_wifi_static_dep,
+    ],
+    c_args: test_c_flags,
+  )
+
+  test(
+    test_unit,
+    test_script,
+    args: test_args + [exe.full_path()],
+    timeout: default_test_timeout,
+  )
+endif
diff --git a/src/core/devices/wifi/nm-device-iwd.c b/src/core/devices/wifi/nm-device-iwd.c
new file mode 100644
index 00000000..f0de90d3
--- /dev/null
+++ b/src/core/devices/wifi/nm-device-iwd.c
@@ -0,0 +1,3508 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+/*
+ * Copyright (C) 2017 Intel Corporation
+ */
+
+#include "src/core/nm-default-daemon.h"
+
+#include "nm-device-iwd.h"
+
+#include <linux/if_ether.h>
+
+#include "devices/nm-device-private.h"
+#include "devices/nm-device.h"
+#include "nm-act-request.h"
+#include "nm-config.h"
+#include "nm-core-internal.h"
+#include "nm-dbus-manager.h"
+#include "nm-glib-aux/nm-ref-string.h"
+#include "nm-iwd-manager.h"
+#include "nm-libnm-core-intern/nm-common-macros.h"
+#include "nm-setting-8021x.h"
+#include "nm-setting-connection.h"
+#include "nm-setting-wireless-security.h"
+#include "nm-setting-wireless.h"
+#include "nm-std-aux/nm-dbus-compat.h"
+#include "nm-utils.h"
+#include "nm-wifi-common.h"
+#include "nm-wifi-utils.h"
+#include "settings/nm-settings-connection.h"
+#include "settings/nm-settings.h"
+#include "supplicant/nm-supplicant-types.h"
+#include "nm-auth-utils.h"
+#include "nm-manager.h"
+
+#define _NMLOG_DEVICE_TYPE NMDeviceIwd
+#include "devices/nm-device-logging.h"
+
+/*****************************************************************************/
+
+NM_GOBJECT_PROPERTIES_DEFINE(NMDeviceIwd,
+                             PROP_MODE,
+                             PROP_BITRATE,
+                             PROP_ACCESS_POINTS,
+                             PROP_ACTIVE_ACCESS_POINT,
+                             PROP_CAPABILITIES,
+                             PROP_SCANNING,
+                             PROP_LAST_SCAN, );
+
+typedef struct {
+    GDBusObject *                 dbus_obj;
+    GDBusProxy *                  dbus_device_proxy;
+    GDBusProxy *                  dbus_station_proxy;
+    GDBusProxy *                  dbus_ap_proxy;
+    GDBusProxy *                  dbus_adhoc_proxy;
+    CList                         aps_lst_head;
+    NMWifiAP *                    current_ap;
+    GCancellable *                cancellable;
+    NMDeviceWifiCapabilities      capabilities;
+    NMActRequestGetSecretsCallId *wifi_secrets_id;
+    guint                         periodic_scan_id;
+    guint                         periodic_update_id;
+    bool                          enabled : 1;
+    bool                          can_scan : 1;
+    bool                          nm_autoconnect : 1;
+    bool                          iwd_autoconnect : 1;
+    bool                          scanning : 1;
+    bool                          scan_requested : 1;
+    bool                          act_mode_switch : 1;
+    bool                          secrets_failed : 1;
+    bool                          networks_requested : 1;
+    bool                          networks_changed : 1;
+    gint64                        last_scan;
+    uint32_t                      ap_id;
+    guint32                       rate;
+    NMEtherAddr                   current_ap_bssid;
+    GDBusMethodInvocation *       pending_agent_request;
+    NMActiveConnection *          assumed_ac;
+    guint                         assumed_ac_timeout;
+} NMDeviceIwdPrivate;
+
+struct _NMDeviceIwd {
+    NMDevice           parent;
+    NMDeviceIwdPrivate _priv;
+};
+
+struct _NMDeviceIwdClass {
+    NMDeviceClass parent;
+};
+
+/*****************************************************************************/
+
+G_DEFINE_TYPE(NMDeviceIwd, nm_device_iwd, NM_TYPE_DEVICE)
+
+#define NM_DEVICE_IWD_GET_PRIVATE(self) \
+    _NM_GET_PRIVATE(self, NMDeviceIwd, NM_IS_DEVICE_IWD, NMDevice)
+
+/*****************************************************************************/
+
+static void schedule_periodic_scan(NMDeviceIwd *self, gboolean initial_scan);
+
+static gboolean check_scanning_prohibited(NMDeviceIwd *self, gboolean periodic);
+
+/*****************************************************************************/
+
+static void
+_ap_dump(NMDeviceIwd *self, NMLogLevel log_level, const NMWifiAP *ap, const char *prefix)
+{
+    char buf[1024];
+
+    buf[0] = '\0';
+    _NMLOG(log_level,
+           LOGD_WIFI_SCAN,
+           "wifi-ap: %-7s %s",
+           prefix,
+           nm_wifi_ap_to_string(ap, buf, sizeof(buf), 0));
+}
+
+/* Callers ensure we're not removing current_ap */
+static void
+ap_add_remove(NMDeviceIwd *self,
+              gboolean     is_adding, /* or else is removing */
+              NMWifiAP *   ap,
+              gboolean     recheck_available_connections)
+{
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+
+    if (is_adding) {
+        g_object_ref(ap);
+        ap->wifi_device = NM_DEVICE(self);
+        c_list_link_tail(&priv->aps_lst_head, &ap->aps_lst);
+        nm_dbus_object_export(NM_DBUS_OBJECT(ap));
+        _ap_dump(self, LOGL_DEBUG, ap, "added");
+        nm_device_wifi_emit_signal_access_point(NM_DEVICE(self), ap, TRUE);
+    } else {
+        ap->wifi_device = NULL;
+        c_list_unlink(&ap->aps_lst);
+        _ap_dump(self, LOGL_DEBUG, ap, "removed");
+    }
+
+    _notify(self, PROP_ACCESS_POINTS);
+
+    if (!is_adding) {
+        nm_device_wifi_emit_signal_access_point(NM_DEVICE(self), ap, FALSE);
+        nm_dbus_object_clear_and_unexport(&ap);
+    }
+
+    if (priv->enabled && !priv->iwd_autoconnect)
+        nm_device_emit_recheck_auto_activate(NM_DEVICE(self));
+
+    if (recheck_available_connections)
+        nm_device_recheck_available_connections(NM_DEVICE(self));
+}
+
+static void
+set_current_ap(NMDeviceIwd *self, NMWifiAP *new_ap, gboolean recheck_available_connections)
+{
+    NMDeviceIwdPrivate *priv;
+    NMWifiAP *          old_ap;
+
+    g_return_if_fail(NM_IS_DEVICE_IWD(self));
+
+    priv   = NM_DEVICE_IWD_GET_PRIVATE(self);
+    old_ap = priv->current_ap;
+
+    if (old_ap == new_ap)
+        return;
+
+    if (new_ap)
+        priv->current_ap = g_object_ref(new_ap);
+    else
+        priv->current_ap = NULL;
+
+    if (old_ap) {
+        if (nm_wifi_ap_get_fake(old_ap))
+            ap_add_remove(self, FALSE, old_ap, recheck_available_connections);
+        g_object_unref(old_ap);
+    }
+
+    memset(&priv->current_ap_bssid, 0, ETH_ALEN);
+    _notify(self, PROP_ACTIVE_ACCESS_POINT);
+    _notify(self, PROP_MODE);
+}
+
+static void
+remove_all_aps(NMDeviceIwd *self)
+{
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+    NMWifiAP *          ap, *ap_safe;
+
+    if (c_list_is_empty(&priv->aps_lst_head))
+        return;
+
+    c_list_for_each_entry_safe (ap, ap_safe, &priv->aps_lst_head, aps_lst)
+        ap_add_remove(self, FALSE, ap, FALSE);
+
+    if (!priv->iwd_autoconnect)
+        nm_device_emit_recheck_auto_activate(NM_DEVICE(self));
+
+    nm_device_recheck_available_connections(NM_DEVICE(self));
+}
+
+static NM80211ApSecurityFlags
+ap_security_flags_from_network_type(const char *type)
+{
+    NM80211ApSecurityFlags flags;
+
+    if (nm_streq(type, "psk"))
+        flags = NM_802_11_AP_SEC_KEY_MGMT_PSK;
+    else if (nm_streq(type, "8021x"))
+        flags = NM_802_11_AP_SEC_KEY_MGMT_802_1X;
+    else
+        return NM_802_11_AP_SEC_NONE;
+
+    flags |= NM_802_11_AP_SEC_PAIR_CCMP;
+    flags |= NM_802_11_AP_SEC_GROUP_CCMP;
+    return flags;
+}
+
+static NMWifiAP *
+ap_from_network(NMDeviceIwd *self,
+                GDBusProxy * network,
+                NMRefString *bss_path,
+                gint64       last_seen_msec,
+                int16_t      signal)
+{
+    NMDeviceIwdPrivate *priv              = NM_DEVICE_IWD_GET_PRIVATE(self);
+    gs_unref_variant GVariant *name_value = NULL;
+    gs_unref_variant GVariant *type_value = NULL;
+    const char *               name;
+    const char *               type;
+    uint32_t                   ap_id;
+    gs_unref_bytes GBytes *ssid = NULL;
+    NMWifiAP *             ap;
+    NMSupplicantBssInfo    bss_info;
+
+    g_return_val_if_fail(network, NULL);
+
+    name_value = g_dbus_proxy_get_cached_property(network, "Name");
+    type_value = g_dbus_proxy_get_cached_property(network, "Type");
+    if (!name_value || !g_variant_is_of_type(name_value, G_VARIANT_TYPE_STRING) || !type_value
+        || !g_variant_is_of_type(type_value, G_VARIANT_TYPE_STRING))
+        return NULL;
+
+    name = g_variant_get_string(name_value, NULL);
+    type = g_variant_get_string(type_value, NULL);
+
+    if (nm_streq(type, "wep")) {
+        /* WEP not supported */
+        return NULL;
+    }
+
+    /* What we get from IWD are networks, or ESSs, that may contain
+     * multiple APs, or BSSs, each.  We don't get information about any
+     * specific BSSs within an ESS but we can safely present each ESS
+     * as an individual BSS to NM, which will be seen as ESSs comprising
+     * a single BSS each.  NM won't be able to handle roaming but IWD
+     * already does that.  We fake the BSSIDs as they don't play any
+     * role either.
+     */
+    ap_id = priv->ap_id++;
+
+    ssid = g_bytes_new(name, NM_MIN(32u, strlen(name)));
+
+    bss_info = (NMSupplicantBssInfo){
+        .bss_path       = bss_path,
+        .last_seen_msec = last_seen_msec,
+        .bssid_valid    = TRUE,
+        .mode           = NM_802_11_MODE_INFRA,
+        .rsn_flags      = ap_security_flags_from_network_type(type),
+        .ssid           = ssid,
+        .signal_percent = nm_wifi_utils_level_to_quality(signal / 100),
+        .frequency      = 2417,
+        .max_rate       = 65000,
+        .bssid          = NM_ETHER_ADDR_INIT(0x00, 0x01, 0x02, ap_id >> 16, ap_id >> 8, ap_id),
+    };
+
+    ap = nm_wifi_ap_new_from_properties(&bss_info);
+
+    nm_assert(bss_path == nm_wifi_ap_get_supplicant_path(ap));
+
+    return ap;
+}
+
+static void
+insert_ap_from_network(NMDeviceIwd *self,
+                       GHashTable * aps,
+                       const char * path,
+                       gint64       last_seen_msec,
+                       int16_t      signal)
+{
+    gs_unref_object GDBusProxy *network_proxy = NULL;
+    nm_auto_ref_string NMRefString *bss_path  = nm_ref_string_new(path);
+    NMWifiAP *                      ap;
+
+    if (g_hash_table_lookup(aps, bss_path)) {
+        _LOGD(LOGD_WIFI, "Duplicate network at %s", path);
+        return;
+    }
+
+    network_proxy =
+        nm_iwd_manager_get_dbus_interface(nm_iwd_manager_get(), path, NM_IWD_NETWORK_INTERFACE);
+
+    ap = ap_from_network(self, network_proxy, bss_path, last_seen_msec, signal);
+    if (!ap)
+        return;
+
+    g_hash_table_insert(aps, bss_path, ap);
+}
+
+static void
+get_ordered_networks_cb(GObject *source, GAsyncResult *res, gpointer user_data)
+{
+    NMDeviceIwd *       self = user_data;
+    NMDeviceIwdPrivate *priv;
+    gs_free_error GError *error        = NULL;
+    gs_unref_variant GVariant *variant = NULL;
+    GVariantIter *             networks;
+    const char *               path;
+    int16_t                    signal;
+    NMWifiAP *                 ap, *ap_safe, *new_ap;
+    gboolean                   changed;
+    GHashTableIter             ap_iter;
+    gs_unref_hashtable GHashTable *new_aps = NULL;
+    gint64                         last_seen_msec;
+
+    variant = g_dbus_proxy_call_finish(G_DBUS_PROXY(source), res, &error);
+    if (!variant && nm_utils_error_is_cancelled(error))
+        return;
+
+    priv                     = NM_DEVICE_IWD_GET_PRIVATE(self);
+    priv->networks_requested = FALSE;
+
+    if (!variant) {
+        _LOGE(LOGD_WIFI, "Station.GetOrderedNetworks failed: %s", error->message);
+        return;
+    }
+
+    if (!g_variant_is_of_type(variant, G_VARIANT_TYPE("(a(on))"))) {
+        _LOGE(LOGD_WIFI,
+              "Station.GetOrderedNetworks returned type %s instead of (a(on))",
+              g_variant_get_type_string(variant));
+        return;
+    }
+
+    new_aps = g_hash_table_new_full(nm_direct_hash, NULL, NULL, g_object_unref);
+    g_variant_get(variant, "(a(on))", &networks);
+
+    last_seen_msec = nm_utils_get_monotonic_timestamp_msec();
+    while (g_variant_iter_next(networks, "(&on)", &path, &signal))
+        insert_ap_from_network(self, new_aps, path, last_seen_msec, signal);
+
+    g_variant_iter_free(networks);
+
+    changed                = priv->networks_changed;
+    priv->networks_changed = FALSE;
+
+    c_list_for_each_entry_safe (ap, ap_safe, &priv->aps_lst_head, aps_lst) {
+        new_ap = g_hash_table_lookup(new_aps, nm_wifi_ap_get_supplicant_path(ap));
+        if (new_ap) {
+            if (nm_wifi_ap_set_strength(ap, nm_wifi_ap_get_strength(new_ap))) {
+                _ap_dump(self, LOGL_TRACE, ap, "updated");
+                changed = TRUE;
+            }
+            g_hash_table_remove(new_aps, nm_wifi_ap_get_supplicant_path(ap));
+            continue;
+        }
+
+        if (ap == priv->current_ap) {
+            /* Normally IWD will prevent the current AP from being
+             * removed from the list and set a low signal strength,
+             * but just making sure.
+             */
+            continue;
+        }
+
+        ap_add_remove(self, FALSE, ap, FALSE);
+        changed = TRUE;
+    }
+
+    g_hash_table_iter_init(&ap_iter, new_aps);
+    while (g_hash_table_iter_next(&ap_iter, NULL, (gpointer) &ap)) {
+        ap_add_remove(self, TRUE, ap, FALSE);
+        g_hash_table_iter_remove(&ap_iter);
+        changed = TRUE;
+    }
+
+    if (changed) {
+        if (!priv->iwd_autoconnect)
+            nm_device_emit_recheck_auto_activate(NM_DEVICE(self));
+
+        nm_device_recheck_available_connections(NM_DEVICE(self));
+    }
+}
+
+static void
+update_aps(NMDeviceIwd *self)
+{
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+
+    if (!priv->cancellable)
+        priv->cancellable = g_cancellable_new();
+
+    g_dbus_proxy_call(priv->dbus_station_proxy,
+                      "GetOrderedNetworks",
+                      NULL,
+                      G_DBUS_CALL_FLAGS_NONE,
+                      2000,
+                      priv->cancellable,
+                      get_ordered_networks_cb,
+                      self);
+    priv->networks_requested = TRUE;
+}
+
+static void
+periodic_update(NMDeviceIwd *self)
+{
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+    int                 ifindex;
+    guint32             new_rate;
+    int                 percent;
+    NMEtherAddr         bssid;
+    gboolean            ap_changed = FALSE;
+    NMPlatform *        platform;
+
+    ifindex = nm_device_get_ifindex(NM_DEVICE(self));
+    if (ifindex <= 0)
+        g_return_if_reached();
+
+    platform = nm_device_get_platform(NM_DEVICE(self));
+
+    /* TODO: obtain quality through the net.connman.iwd.SignalLevelAgent API.
+     * For now we're waking up for the rate/BSSID updates anyway.
+     */
+    if (!nm_platform_wifi_get_station(platform, ifindex, &bssid, &percent, &new_rate)) {
+        _LOGD(LOGD_WIFI, "BSSID / quality / rate platform query failed");
+        return;
+    }
+
+    if (nm_wifi_ap_set_strength(priv->current_ap, (gint8) percent)) {
+#if NM_MORE_LOGGING
+        ap_changed = TRUE;
+#endif
+    }
+
+    if (new_rate != priv->rate) {
+        priv->rate = new_rate;
+        _notify(self, PROP_BITRATE);
+    }
+
+    if (nm_ether_addr_is_valid(&bssid) && !nm_ether_addr_equal(&bssid, &priv->current_ap_bssid)) {
+        priv->current_ap_bssid = bssid;
+        ap_changed |= nm_wifi_ap_set_address_bin(priv->current_ap, &bssid);
+        ap_changed |= nm_wifi_ap_set_freq(priv->current_ap,
+                                          nm_platform_wifi_get_frequency(platform, ifindex));
+    }
+
+    if (ap_changed)
+        _ap_dump(self, LOGL_DEBUG, priv->current_ap, "updated");
+}
+
+static gboolean
+periodic_update_cb(gpointer user_data)
+{
+    periodic_update(user_data);
+    return TRUE;
+}
+
+static void
+send_disconnect(NMDeviceIwd *self)
+{
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+
+    g_dbus_proxy_call(priv->dbus_station_proxy,
+                      "Disconnect",
+                      NULL,
+                      G_DBUS_CALL_FLAGS_NONE,
+                      -1,
+                      NULL,
+                      NULL,
+                      NULL);
+}
+
+static void
+wifi_secrets_cancel(NMDeviceIwd *self)
+{
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+
+    if (priv->wifi_secrets_id)
+        nm_act_request_cancel_secrets(NULL, priv->wifi_secrets_id);
+    nm_assert(!priv->wifi_secrets_id);
+
+    if (priv->pending_agent_request) {
+        g_dbus_method_invocation_return_error_literal(priv->pending_agent_request,
+                                                      NM_DEVICE_ERROR,
+                                                      NM_DEVICE_ERROR_INVALID_CONNECTION,
+                                                      "NM secrets request cancelled");
+        g_clear_object(&priv->pending_agent_request);
+    }
+}
+
+static void
+cleanup_assumed_connect(NMDeviceIwd *self)
+{
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+
+    if (!priv->assumed_ac)
+        return;
+
+    g_signal_handlers_disconnect_by_data(priv->assumed_ac, self);
+    g_clear_object(&priv->assumed_ac);
+}
+
+static void
+cleanup_association_attempt(NMDeviceIwd *self, gboolean disconnect)
+{
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+
+    cleanup_assumed_connect(self);
+    wifi_secrets_cancel(self);
+
+    set_current_ap(self, NULL, TRUE);
+    nm_clear_g_source(&priv->periodic_update_id);
+    nm_clear_g_source(&priv->assumed_ac_timeout);
+
+    if (disconnect && priv->dbus_station_proxy)
+        send_disconnect(self);
+}
+
+static void
+reset_mode(NMDeviceIwd *       self,
+           GCancellable *      cancellable,
+           GAsyncReadyCallback callback,
+           gpointer            user_data)
+{
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+
+    g_dbus_proxy_call(
+        priv->dbus_device_proxy,
+        DBUS_INTERFACE_PROPERTIES ".Set",
+        g_variant_new("(ssv)", NM_IWD_DEVICE_INTERFACE, "Mode", g_variant_new_string("station")),
+        G_DBUS_CALL_FLAGS_NONE,
+        2000,
+        cancellable,
+        callback,
+        user_data);
+}
+
+static gboolean
+get_variant_boolean(GVariant *v, const char *property)
+{
+    if (!v || !g_variant_is_of_type(v, G_VARIANT_TYPE_BOOLEAN)) {
+        nm_log_warn(LOGD_DEVICE | LOGD_WIFI,
+                    "Property %s not cached or not boolean type",
+                    property);
+
+        return FALSE;
+    }
+
+    return g_variant_get_boolean(v);
+}
+
+static const char *
+get_variant_state(GVariant *v)
+{
+    if (!v || !g_variant_is_of_type(v, G_VARIANT_TYPE_STRING)) {
+        nm_log_warn(LOGD_DEVICE | LOGD_WIFI, "State property not cached or not a string");
+
+        return "unknown";
+    }
+
+    return g_variant_get_string(v, NULL);
+}
+
+static void
+deactivate(NMDevice *device)
+{
+    NMDeviceIwd *       self = NM_DEVICE_IWD(device);
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+
+    if (!priv->dbus_obj)
+        return;
+
+    if (priv->dbus_station_proxy) {
+        gs_unref_variant GVariant *value =
+            g_dbus_proxy_get_cached_property(priv->dbus_station_proxy, "State");
+
+        if (NM_IN_STRSET(get_variant_state(value), "disconnecting", "disconnected"))
+            return;
+    }
+
+    cleanup_association_attempt(self, TRUE);
+    priv->act_mode_switch = FALSE;
+
+    if (!priv->dbus_station_proxy)
+        reset_mode(self, NULL, NULL, NULL);
+}
+
+static void
+disconnect_cb(GObject *source, GAsyncResult *res, gpointer user_data)
+{
+    gs_unref_object NMDeviceIwd *self = NULL;
+    NMDeviceDeactivateCallback   callback;
+    gpointer                     callback_user_data;
+    gs_unref_variant GVariant *variant = NULL;
+    gs_free_error GError *error        = NULL;
+
+    nm_utils_user_data_unpack(user_data, &self, &callback, &callback_user_data);
+
+    variant = g_dbus_proxy_call_finish(G_DBUS_PROXY(source), res, &error);
+    callback(NM_DEVICE(self), error, callback_user_data);
+}
+
+static void
+disconnect_cb_on_idle(gpointer user_data, GCancellable *cancellable)
+{
+    gs_unref_object NMDeviceIwd *self = NULL;
+    NMDeviceDeactivateCallback   callback;
+    gpointer                     callback_user_data;
+    gs_free_error GError *cancelled_error = NULL;
+
+    nm_utils_user_data_unpack(user_data, &self, &callback, &callback_user_data);
+
+    g_cancellable_set_error_if_cancelled(cancellable, &cancelled_error);
+    callback(NM_DEVICE(self), cancelled_error, callback_user_data);
+}
+
+static void
+deactivate_async(NMDevice *                 device,
+                 GCancellable *             cancellable,
+                 NMDeviceDeactivateCallback callback,
+                 gpointer                   callback_user_data)
+{
+    NMDeviceIwd *       self = NM_DEVICE_IWD(device);
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+    gpointer            user_data;
+
+    nm_assert(G_IS_CANCELLABLE(cancellable));
+    nm_assert(callback);
+
+    user_data = nm_utils_user_data_pack(g_object_ref(self), callback, callback_user_data);
+
+    if (!priv->dbus_obj) {
+        nm_utils_invoke_on_idle(cancellable, disconnect_cb_on_idle, user_data);
+        return;
+    }
+
+    cleanup_association_attempt(self, FALSE);
+    priv->act_mode_switch = FALSE;
+
+    if (priv->dbus_station_proxy) {
+        g_dbus_proxy_call(priv->dbus_station_proxy,
+                          "Disconnect",
+                          NULL,
+                          G_DBUS_CALL_FLAGS_NONE,
+                          -1,
+                          cancellable,
+                          disconnect_cb,
+                          user_data);
+    } else
+        reset_mode(self, cancellable, disconnect_cb, user_data);
+}
+
+static gboolean
+is_connection_known_network(NMConnection *connection)
+{
+    NMIwdNetworkSecurity security;
+    gs_free char *       ssid = NULL;
+
+    if (!nm_wifi_connection_get_iwd_ssid_and_security(connection, &ssid, &security))
+        return FALSE;
+
+    return nm_iwd_manager_is_known_network(nm_iwd_manager_get(), ssid, security);
+}
+
+static gboolean
+is_ap_known_network(NMWifiAP *ap)
+{
+    gs_unref_object GDBusProxy *network_proxy = NULL;
+    gs_unref_variant GVariant *known_network  = NULL;
+
+    network_proxy =
+        nm_iwd_manager_get_dbus_interface(nm_iwd_manager_get(),
+                                          nm_ref_string_get_str(nm_wifi_ap_get_supplicant_path(ap)),
+                                          NM_IWD_NETWORK_INTERFACE);
+    if (!network_proxy)
+        return FALSE;
+
+    known_network = g_dbus_proxy_get_cached_property(network_proxy, "KnownNetwork");
+    return nm_g_variant_is_of_type(known_network, G_VARIANT_TYPE_OBJECT_PATH);
+}
+
+static gboolean
+check_connection_compatible(NMDevice *device, NMConnection *connection, GError **error)
+{
+    NMDeviceIwd *        self = NM_DEVICE_IWD(device);
+    NMDeviceIwdPrivate * priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+    NMSettingWireless *  s_wireless;
+    const char *         mac;
+    const char *const *  mac_blacklist;
+    int                  i;
+    const char *         perm_hw_addr;
+    const char *         mode;
+    NMIwdNetworkSecurity security;
+    GBytes *             ssid;
+    const guint8 *       ssid_bytes;
+    gsize                ssid_len;
+
+    if (!NM_DEVICE_CLASS(nm_device_iwd_parent_class)
+             ->check_connection_compatible(device, connection, error))
+        return FALSE;
+
+    s_wireless = nm_connection_get_setting_wireless(connection);
+
+    /* complete_connection would be called (if at all) before this function
+     * so an SSID should always be set.  IWD doesn't support non-UTF8 SSIDs
+     * (ignores BSSes with such SSIDs and has no way to represent them on
+     * DBus) so we can cut it short for connections with a non-UTF8 SSID.
+     */
+    ssid = nm_setting_wireless_get_ssid(s_wireless);
+    if (!ssid)
+        return FALSE;
+
+    ssid_bytes = g_bytes_get_data(ssid, &ssid_len);
+    if (!g_utf8_validate((const char *) ssid_bytes, ssid_len, NULL)) {
+        nm_utils_error_set_literal(error,
+                                   NM_UTILS_ERROR_CONNECTION_AVAILABLE_INCOMPATIBLE,
+                                   "non-UTF-8 connection SSID not supported by IWD backend");
+        return FALSE;
+    }
+
+    perm_hw_addr = nm_device_get_permanent_hw_address(device);
+    mac          = nm_setting_wireless_get_mac_address(s_wireless);
+    if (perm_hw_addr) {
+        if (mac && !nm_utils_hwaddr_matches(mac, -1, perm_hw_addr, -1)) {
+            nm_utils_error_set_literal(error,
+                                       NM_UTILS_ERROR_CONNECTION_AVAILABLE_INCOMPATIBLE,
+                                       "device MAC address does not match the profile");
+            return FALSE;
+        }
+
+        /* Check for MAC address blacklist */
+        mac_blacklist = nm_setting_wireless_get_mac_address_blacklist(s_wireless);
+        for (i = 0; mac_blacklist[i]; i++) {
+            nm_assert(nm_utils_hwaddr_valid(mac_blacklist[i], ETH_ALEN));
+
+            if (nm_utils_hwaddr_matches(mac_blacklist[i], -1, perm_hw_addr, -1)) {
+                nm_utils_error_set_literal(error,
+                                           NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
+                                           "MAC address blacklisted");
+                return FALSE;
+            }
+        }
+    } else if (mac) {
+        nm_utils_error_set_literal(error,
+                                   NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
+                                   "device has no valid MAC address as required by profile");
+        return FALSE;
+    }
+
+    if (!nm_wifi_connection_get_iwd_ssid_and_security(connection, NULL, &security)
+        || security == NM_IWD_NETWORK_SECURITY_WEP) {
+        nm_utils_error_set_literal(error,
+                                   NM_UTILS_ERROR_CONNECTION_AVAILABLE_INCOMPATIBLE,
+                                   "connection authentication type not supported by IWD backend");
+        return FALSE;
+    }
+
+    mode = nm_setting_wireless_get_mode(s_wireless);
+
+    /* Hidden SSIDs only supported in client mode */
+    if (nm_setting_wireless_get_hidden(s_wireless)
+        && !NM_IN_STRSET(mode, NULL, NM_SETTING_WIRELESS_MODE_INFRA)) {
+        nm_utils_error_set_literal(
+            error,
+            NM_UTILS_ERROR_CONNECTION_AVAILABLE_INCOMPATIBLE,
+            "non-infrastructure hidden networks not supported by the IWD backend");
+        return FALSE;
+    }
+
+    if (NM_IN_STRSET(mode, NULL, NM_SETTING_WIRELESS_MODE_INFRA)) {
+        /* 8021x networks can only be used if they've been provisioned on the IWD side and
+         * thus are Known Networks.
+         */
+        if (security == NM_IWD_NETWORK_SECURITY_8021X) {
+            if (!is_connection_known_network(connection)) {
+                nm_utils_error_set_literal(error,
+                                           NM_UTILS_ERROR_CONNECTION_AVAILABLE_INCOMPATIBLE,
+                                           "802.1x connections must have IWD provisioning files");
+                return FALSE;
+            }
+        } else if (!NM_IN_SET(security,
+                              NM_IWD_NETWORK_SECURITY_OPEN,
+                              NM_IWD_NETWORK_SECURITY_PSK)) {
+            nm_utils_error_set_literal(error,
+                                       NM_UTILS_ERROR_CONNECTION_AVAILABLE_INCOMPATIBLE,
+                                       "IWD backend only supports Open, PSK and 802.1x network "
+                                       "authentication in Infrastructure mode");
+            return FALSE;
+        }
+    } else if (nm_streq(mode, NM_SETTING_WIRELESS_MODE_AP)) {
+        NMSettingWirelessSecurity *s_wireless_sec =
+            nm_connection_get_setting_wireless_security(connection);
+
+        if (!(priv->capabilities & NM_WIFI_DEVICE_CAP_AP)) {
+            nm_utils_error_set_literal(error,
+                                       NM_UTILS_ERROR_CONNECTION_AVAILABLE_INCOMPATIBLE,
+                                       "device does not support Access Point mode");
+            return FALSE;
+        }
+
+        if (!NM_IN_SET(security, NM_IWD_NETWORK_SECURITY_PSK) || !s_wireless_sec
+            || !nm_streq0(nm_setting_wireless_security_get_key_mgmt(s_wireless_sec), "wpa-psk")) {
+            nm_utils_error_set_literal(error,
+                                       NM_UTILS_ERROR_CONNECTION_AVAILABLE_INCOMPATIBLE,
+                                       "IWD backend only supports PSK authentication in AP mode");
+            return FALSE;
+        }
+    } else if (nm_streq(mode, NM_SETTING_WIRELESS_MODE_ADHOC)) {
+        NMSettingWirelessSecurity *s_wireless_sec =
+            nm_connection_get_setting_wireless_security(connection);
+
+        if (!(priv->capabilities & NM_WIFI_DEVICE_CAP_ADHOC)) {
+            nm_utils_error_set_literal(error,
+                                       NM_UTILS_ERROR_CONNECTION_AVAILABLE_INCOMPATIBLE,
+                                       "device does not support Ad-Hoc mode");
+            return FALSE;
+        }
+
+        if (!NM_IN_SET(security, NM_IWD_NETWORK_SECURITY_OPEN, NM_IWD_NETWORK_SECURITY_PSK)
+            || (s_wireless_sec
+                && !nm_streq0(nm_setting_wireless_security_get_key_mgmt(s_wireless_sec),
+                              "wpa-psk"))) {
+            nm_utils_error_set_literal(
+                error,
+                NM_UTILS_ERROR_CONNECTION_AVAILABLE_INCOMPATIBLE,
+                "IWD backend only supports Open and PSK authentication in Ad-Hoc mode");
+            return FALSE;
+        }
+    } else {
+        nm_utils_error_set(error,
+                           NM_UTILS_ERROR_CONNECTION_AVAILABLE_INCOMPATIBLE,
+                           "'%s' type profiles not supported by IWD backend",
+                           mode);
+        return FALSE;
+    }
+
+    return TRUE;
+}
+
+static gboolean
+check_connection_available(NMDevice *                     device,
+                           NMConnection *                 connection,
+                           NMDeviceCheckConAvailableFlags flags,
+                           const char *                   specific_object,
+                           GError **                      error)
+{
+    NMDeviceIwd *        self = NM_DEVICE_IWD(device);
+    NMDeviceIwdPrivate * priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+    NMSettingWireless *  s_wifi;
+    const char *         mode;
+    NMWifiAP *           ap = NULL;
+    NMIwdNetworkSecurity security;
+
+    s_wifi = nm_connection_get_setting_wireless(connection);
+    g_return_val_if_fail(s_wifi, FALSE);
+
+    /* a connection that is available for a certain @specific_object, MUST
+     * also be available in general (without @specific_object). */
+
+    if (specific_object) {
+        ap = nm_wifi_ap_lookup_for_device(NM_DEVICE(self), specific_object);
+        if (!ap) {
+            nm_utils_error_set_literal(error,
+                                       NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
+                                       "requested access point not found");
+            return FALSE;
+        }
+        if (!nm_wifi_ap_check_compatible(ap, connection)) {
+            nm_utils_error_set_literal(error,
+                                       NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
+                                       "requested access point is not compatible with profile");
+            return FALSE;
+        }
+    }
+
+    /* AP and Ad-Hoc connections can be activated independent of the scan list */
+    mode = nm_setting_wireless_get_mode(s_wifi);
+    if (NM_IN_STRSET(mode, NM_SETTING_WIRELESS_MODE_AP, NM_SETTING_WIRELESS_MODE_ADHOC))
+        return TRUE;
+
+    /* Hidden SSIDs obviously don't always appear in the scan list either.
+     *
+     * For an explicit user-activation-request, a connection is considered
+     * available because for hidden Wi-Fi, clients didn't consistently
+     * set the 'hidden' property to indicate hidden SSID networks.  If
+     * activating but the network isn't available let the device recheck
+     * availability.
+     */
+    if (nm_setting_wireless_get_hidden(s_wifi)
+        || NM_FLAGS_HAS(flags, _NM_DEVICE_CHECK_CON_AVAILABLE_FOR_USER_REQUEST_IGNORE_AP))
+        return TRUE;
+
+    if (!ap)
+        ap = nm_wifi_aps_find_first_compatible(&priv->aps_lst_head, connection);
+
+    if (!ap) {
+        nm_utils_error_set_literal(error,
+                                   NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
+                                   "no compatible access point found");
+        return FALSE;
+    }
+
+    /* 8021x networks can only be used if they've been provisioned on the IWD side and
+     * thus are Known Networks.
+     */
+    if (nm_wifi_connection_get_iwd_ssid_and_security(connection, NULL, &security)
+        && security == NM_IWD_NETWORK_SECURITY_8021X) {
+        if (!is_ap_known_network(ap)) {
+            nm_utils_error_set_literal(
+                error,
+                NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
+                "802.1x network is not an IWD Known Network (missing provisioning file?)");
+            return FALSE;
+        }
+    }
+
+    return TRUE;
+}
+
+/* To be used where the SSID has been validated before */
+static char *
+iwd_ssid_to_str(const GBytes *ssid)
+{
+    const guint8 *ssid_bytes;
+    gsize         ssid_len;
+
+    ssid_bytes = g_bytes_get_data((GBytes *) ssid, &ssid_len);
+    nm_assert(ssid && g_utf8_validate((const char *) ssid_bytes, ssid_len, NULL));
+    return g_strndup((const char *) ssid_bytes, ssid_len);
+}
+
+static gboolean
+complete_connection(NMDevice *           device,
+                    NMConnection *       connection,
+                    const char *         specific_object,
+                    NMConnection *const *existing_connections,
+                    GError **            error)
+{
+    NMDeviceIwd *       self = NM_DEVICE_IWD(device);
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+    NMSettingWireless * s_wifi;
+    gs_free char *      ssid_utf8 = NULL;
+    NMWifiAP *          ap;
+    GBytes *            ssid   = NULL;
+    gboolean            hidden = FALSE;
+    const char *        mode;
+
+    s_wifi = nm_connection_get_setting_wireless(connection);
+
+    mode = s_wifi ? nm_setting_wireless_get_mode(s_wifi) : NULL;
+
+    if (nm_streq0(mode, NM_SETTING_WIRELESS_MODE_AP) || !specific_object) {
+        const guint8 *ssid_bytes;
+        gsize         ssid_len;
+
+        /* If not given a specific object, we need at minimum an SSID */
+        if (!s_wifi) {
+            g_set_error_literal(error,
+                                NM_DEVICE_ERROR,
+                                NM_DEVICE_ERROR_INVALID_CONNECTION,
+                                "A 'wireless' setting is required if no AP path was given.");
+            return FALSE;
+        }
+
+        ssid       = nm_setting_wireless_get_ssid(s_wifi);
+        ssid_bytes = g_bytes_get_data(ssid, &ssid_len);
+
+        if (!ssid || ssid_len == 0 || !g_utf8_validate((const char *) ssid_bytes, ssid_len, NULL)) {
+            g_set_error_literal(error,
+                                NM_DEVICE_ERROR,
+                                NM_DEVICE_ERROR_INVALID_CONNECTION,
+                                "A 'wireless' setting with a valid UTF-8 SSID is required if no AP "
+                                "path was given.");
+            return FALSE;
+        }
+    }
+
+    if (nm_streq0(mode, NM_SETTING_WIRELESS_MODE_AP)) {
+        if (!nm_setting_verify(NM_SETTING(s_wifi), connection, error))
+            return FALSE;
+        ap = NULL;
+    } else if (!specific_object) {
+        /* Find a compatible AP in the scan list */
+        ap = nm_wifi_aps_find_first_compatible(&priv->aps_lst_head, connection);
+        if (!ap) {
+            /* If we still don't have an AP, then the WiFI settings needs to be
+             * fully specified by the client.  Might not be able to find an AP
+             * if the network isn't broadcasting the SSID for example.
+             */
+            if (!nm_setting_verify(NM_SETTING(s_wifi), connection, error))
+                return FALSE;
+
+            /* We could either require the profile to be marked as hidden by the
+             * client or at least check that a hidden AP with a matching security
+             * type is in range using Station.GetHiddenAccessPoints().  For now
+             * assume it is hidden even though that will reveal the SSID on the
+             * air.
+             */
+            hidden = TRUE;
+        }
+    } else {
+        ap = nm_wifi_ap_lookup_for_device(NM_DEVICE(self), specific_object);
+        if (!ap) {
+            g_set_error(error,
+                        NM_DEVICE_ERROR,
+                        NM_DEVICE_ERROR_SPECIFIC_OBJECT_NOT_FOUND,
+                        "The access point %s was not in the scan list.",
+                        specific_object);
+            return FALSE;
+        }
+
+        ssid = nm_wifi_ap_get_ssid(ap);
+
+        /* Add a wifi setting if one doesn't exist yet */
+        if (!s_wifi) {
+            s_wifi = (NMSettingWireless *) nm_setting_wireless_new();
+            nm_connection_add_setting(connection, NM_SETTING(s_wifi));
+        }
+    }
+
+    if (ap) {
+        if (!nm_wifi_ap_complete_connection(ap, connection, FALSE, error))
+            return FALSE;
+    }
+
+    ssid_utf8 = iwd_ssid_to_str(ssid);
+    nm_utils_complete_generic(
+        nm_device_get_platform(device),
+        connection,
+        NM_SETTING_WIRELESS_SETTING_NAME,
+        existing_connections,
+        ssid_utf8,
+        ssid_utf8,
+        NULL,
+        nm_setting_wireless_get_mac_address(s_wifi) ? NULL : nm_device_get_iface(device),
+        TRUE);
+
+    if (hidden)
+        g_object_set(s_wifi, NM_SETTING_WIRELESS_HIDDEN, TRUE, NULL);
+
+    return TRUE;
+}
+
+static gboolean
+is_available(NMDevice *device, NMDeviceCheckDevAvailableFlags flags)
+{
+    NMDeviceIwd *       self  = NM_DEVICE_IWD(device);
+    NMDeviceIwdPrivate *priv  = NM_DEVICE_IWD_GET_PRIVATE(self);
+    NMDeviceState       state = nm_device_get_state(device);
+
+    /* Available if either the device is UP and in station mode
+     * or in AP/Ad-Hoc modes while activating or activated.  Device
+     * may be temporarily DOWN while activating or deactivating and
+     * we don't want it to be marked unavailable because of this.
+     *
+     * For reference:
+     * We call nm_device_queue_recheck_available whenever
+     * priv->enabled changes or priv->dbus_station_proxy changes.
+     */
+    return priv->dbus_obj && priv->enabled
+           && (priv->dbus_station_proxy
+               || (state >= NM_DEVICE_STATE_CONFIG && state <= NM_DEVICE_STATE_DEACTIVATING));
+}
+
+static gboolean
+get_autoconnect_allowed(NMDevice *device)
+{
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(NM_DEVICE_IWD(device));
+
+    return priv->nm_autoconnect;
+}
+
+static gboolean
+can_auto_connect(NMDevice *device, NMSettingsConnection *sett_conn, char **specific_object)
+{
+    NMDeviceIwd *       self = NM_DEVICE_IWD(device);
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+    NMConnection *      connection;
+    NMSettingWireless * s_wifi;
+    NMWifiAP *          ap;
+    const char *        mode;
+    guint64             timestamp = 0;
+
+    nm_assert(!specific_object || !*specific_object);
+
+    if (!NM_DEVICE_CLASS(nm_device_iwd_parent_class)->can_auto_connect(device, sett_conn, NULL))
+        return FALSE;
+
+    connection = nm_settings_connection_get_connection(sett_conn);
+
+    s_wifi = nm_connection_get_setting_wireless(connection);
+    g_return_val_if_fail(s_wifi, FALSE);
+
+    /* Don't auto-activate AP or Ad-Hoc connections.
+     * Note the wpa_supplicant backend has the opposite policy.
+     */
+    mode = nm_setting_wireless_get_mode(s_wifi);
+    if (mode && g_strcmp0(mode, NM_SETTING_WIRELESS_MODE_INFRA) != 0)
+        return FALSE;
+
+    /* Don't autoconnect to networks that have been tried at least once
+     * but haven't been successful, since these are often accidental choices
+     * from the menu and the user may not know the password.
+     */
+    if (nm_settings_connection_get_timestamp(sett_conn, &timestamp)) {
+        if (timestamp == 0)
+            return FALSE;
+    }
+
+    ap = nm_wifi_aps_find_first_compatible(&priv->aps_lst_head, connection);
+    if (ap) {
+        /* All good; connection is usable */
+        NM_SET_OUT(specific_object, g_strdup(nm_dbus_object_get_path(NM_DBUS_OBJECT(ap))));
+        return TRUE;
+    }
+
+    return FALSE;
+}
+
+const CList *
+_nm_device_iwd_get_aps(NMDeviceIwd *self)
+{
+    return &NM_DEVICE_IWD_GET_PRIVATE(self)->aps_lst_head;
+}
+
+static void
+scan_cb(GObject *source, GAsyncResult *res, gpointer user_data)
+{
+    NMDeviceIwd *       self = user_data;
+    NMDeviceIwdPrivate *priv;
+    gs_unref_variant GVariant *variant = NULL;
+    gs_free_error GError *error        = NULL;
+
+    variant = g_dbus_proxy_call_finish(G_DBUS_PROXY(source), res, &error);
+    if (!variant && nm_utils_error_is_cancelled(error))
+        return;
+
+    priv                 = NM_DEVICE_IWD_GET_PRIVATE(self);
+    priv->scan_requested = FALSE;
+    priv->last_scan      = nm_utils_get_monotonic_timestamp_msec();
+    _notify(self, PROP_LAST_SCAN);
+
+    /* On success, priv->scanning becomes true right before or right
+     * after this callback, so the next automatic scan will be
+     * scheduled when priv->scanning goes back to false.  On error,
+     * schedule a retry now.
+     */
+    if (error && !priv->scanning)
+        schedule_periodic_scan(self, FALSE);
+}
+
+static void
+dbus_request_scan_cb(NMDevice *             device,
+                     GDBusMethodInvocation *context,
+                     NMAuthSubject *        subject,
+                     GError *               error,
+                     gpointer               user_data)
+{
+    NMDeviceIwd *       self = NM_DEVICE_IWD(device);
+    NMDeviceIwdPrivate *priv;
+    gs_unref_variant GVariant *scan_options = user_data;
+
+    if (error) {
+        g_dbus_method_invocation_return_gerror(context, error);
+        return;
+    }
+
+    if (check_scanning_prohibited(self, FALSE)) {
+        g_dbus_method_invocation_return_error_literal(context,
+                                                      NM_DEVICE_ERROR,
+                                                      NM_DEVICE_ERROR_NOT_ALLOWED,
+                                                      "Scanning not allowed at this time");
+        return;
+    }
+
+    priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+
+    if (!priv->can_scan) {
+        g_dbus_method_invocation_return_error_literal(context,
+                                                      NM_DEVICE_ERROR,
+                                                      NM_DEVICE_ERROR_NOT_ALLOWED,
+                                                      "Scanning not allowed while unavailable");
+        return;
+    }
+
+    if (scan_options) {
+        gs_unref_variant GVariant *val = g_variant_lookup_value(scan_options, "ssids", NULL);
+
+        if (val) {
+            g_dbus_method_invocation_return_error_literal(context,
+                                                          NM_DEVICE_ERROR,
+                                                          NM_DEVICE_ERROR_NOT_ALLOWED,
+                                                          "'ssid' scan option not supported");
+            return;
+        }
+    }
+
+    if (!priv->scanning && !priv->scan_requested) {
+        g_dbus_proxy_call(priv->dbus_station_proxy,
+                          "Scan",
+                          NULL,
+                          G_DBUS_CALL_FLAGS_NONE,
+                          -1,
+                          priv->cancellable,
+                          scan_cb,
+                          self);
+        priv->scan_requested = TRUE;
+    }
+
+    g_dbus_method_invocation_return_value(context, NULL);
+}
+
+void
+_nm_device_iwd_request_scan(NMDeviceIwd *self, GVariant *options, GDBusMethodInvocation *invocation)
+{
+    NMDeviceIwdPrivate *priv   = NM_DEVICE_IWD_GET_PRIVATE(self);
+    NMDevice *          device = NM_DEVICE(self);
+
+    if (!priv->can_scan) {
+        g_dbus_method_invocation_return_error_literal(invocation,
+                                                      NM_DEVICE_ERROR,
+                                                      NM_DEVICE_ERROR_NOT_ALLOWED,
+                                                      "Scanning not allowed while unavailable");
+        return;
+    }
+
+    nm_device_auth_request(device,
+                           invocation,
+                           NULL,
+                           NM_AUTH_PERMISSION_WIFI_SCAN,
+                           TRUE,
+                           NULL,
+                           dbus_request_scan_cb,
+                           nm_g_variant_ref(options));
+}
+
+static gboolean
+check_scanning_prohibited(NMDeviceIwd *self, gboolean periodic)
+{
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+
+    g_return_val_if_fail(priv->dbus_obj != NULL, TRUE);
+
+    switch (nm_device_get_state(NM_DEVICE(self))) {
+    case NM_DEVICE_STATE_UNKNOWN:
+    case NM_DEVICE_STATE_UNMANAGED:
+    case NM_DEVICE_STATE_UNAVAILABLE:
+    case NM_DEVICE_STATE_PREPARE:
+    case NM_DEVICE_STATE_CONFIG:
+    case NM_DEVICE_STATE_IP_CONFIG:
+    case NM_DEVICE_STATE_IP_CHECK:
+    case NM_DEVICE_STATE_SECONDARIES:
+    case NM_DEVICE_STATE_DEACTIVATING:
+        /* Prohibit scans when unusable or activating */
+        return TRUE;
+    case NM_DEVICE_STATE_DISCONNECTED:
+    case NM_DEVICE_STATE_FAILED:
+    case NM_DEVICE_STATE_ACTIVATED:
+    case NM_DEVICE_STATE_NEED_AUTH:
+        break;
+    }
+
+    /* Prohibit scans if IWD is busy */
+    return !priv->can_scan;
+}
+
+static const char *
+get_agent_request_network_path(GDBusMethodInvocation *invocation)
+{
+    const char *method_name  = g_dbus_method_invocation_get_method_name(invocation);
+    GVariant *  params       = g_dbus_method_invocation_get_parameters(invocation);
+    const char *network_path = NULL;
+
+    if (nm_streq(method_name, "RequestPassphrase"))
+        g_variant_get(params, "(o)", &network_path);
+    else if (nm_streq(method_name, "RequestPrivateKeyPassphrase"))
+        g_variant_get(params, "(o)", &network_path);
+    else if (nm_streq(method_name, "RequestUserNameAndPassword"))
+        g_variant_get(params, "(o)", &network_path);
+    else if (nm_streq(method_name, "RequestUserPassword")) {
+        const char *user;
+        g_variant_get(params, "(os)", &network_path, &user);
+    }
+
+    return network_path;
+}
+
+/*
+ * try_reply_agent_request
+ *
+ * Check if the connection settings already have the secrets corresponding
+ * to the IWD agent method that was invoked.  If they do, send the method reply
+ * with the appropriate secrets.  Otherwise, return the missing secret's setting
+ * name and key so the caller can send a NM secrets request with this data.
+ * Return TRUE in either case, return FALSE if an error is detected.
+ */
+static gboolean
+try_reply_agent_request(NMDeviceIwd *          self,
+                        NMConnection *         connection,
+                        GDBusMethodInvocation *invocation,
+                        const char **          setting_name,
+                        const char **          setting_key,
+                        gboolean *             replied)
+{
+    const char *               method_name = g_dbus_method_invocation_get_method_name(invocation);
+    NMSettingWirelessSecurity *s_wireless_sec;
+    NMSetting8021x *           s_8021x;
+
+    s_wireless_sec = nm_connection_get_setting_wireless_security(connection);
+    s_8021x        = nm_connection_get_setting_802_1x(connection);
+
+    *replied = FALSE;
+
+    if (nm_streq(method_name, "RequestPassphrase")) {
+        const char *psk;
+
+        if (!s_wireless_sec)
+            return FALSE;
+
+        psk = nm_setting_wireless_security_get_psk(s_wireless_sec);
+        if (psk) {
+            _LOGD(LOGD_DEVICE | LOGD_WIFI, "Returning the PSK to the IWD Agent");
+
+            g_dbus_method_invocation_return_value(invocation, g_variant_new("(s)", psk));
+            *replied = TRUE;
+            return TRUE;
+        }
+
+        *setting_name = NM_SETTING_WIRELESS_SECURITY_SETTING_NAME;
+        *setting_key  = NM_SETTING_WIRELESS_SECURITY_PSK;
+        return TRUE;
+    } else if (nm_streq(method_name, "RequestPrivateKeyPassphrase")) {
+        const char *password;
+
+        if (!s_8021x)
+            return FALSE;
+
+        password = nm_setting_802_1x_get_private_key_password(s_8021x);
+        if (password) {
+            _LOGD(LOGD_DEVICE | LOGD_WIFI, "Returning the private key password to the IWD Agent");
+
+            g_dbus_method_invocation_return_value(invocation, g_variant_new("(s)", password));
+            *replied = TRUE;
+            return TRUE;
+        }
+
+        *setting_name = NM_SETTING_802_1X_SETTING_NAME;
+        *setting_key  = NM_SETTING_802_1X_PRIVATE_KEY_PASSWORD;
+        return TRUE;
+    } else if (nm_streq(method_name, "RequestUserNameAndPassword")) {
+        const char *identity, *password;
+
+        if (!s_8021x)
+            return FALSE;
+
+        identity = nm_setting_802_1x_get_identity(s_8021x);
+        password = nm_setting_802_1x_get_password(s_8021x);
+        if (identity && password) {
+            _LOGD(LOGD_DEVICE | LOGD_WIFI, "Returning the username and password to the IWD Agent");
+
+            g_dbus_method_invocation_return_value(invocation,
+                                                  g_variant_new("(ss)", identity, password));
+            *replied = TRUE;
+            return TRUE;
+        }
+
+        *setting_name = NM_SETTING_802_1X_SETTING_NAME;
+        if (!identity)
+            *setting_key = NM_SETTING_802_1X_IDENTITY;
+        else
+            *setting_key = NM_SETTING_802_1X_PASSWORD;
+        return TRUE;
+    } else if (nm_streq(method_name, "RequestUserPassword")) {
+        const char *password;
+
+        if (!s_8021x)
+            return FALSE;
+
+        password = nm_setting_802_1x_get_password(s_8021x);
+        if (password) {
+            _LOGD(LOGD_DEVICE | LOGD_WIFI, "Returning the user password to the IWD Agent");
+
+            g_dbus_method_invocation_return_value(invocation, g_variant_new("(s)", password));
+            *replied = TRUE;
+            return TRUE;
+        }
+
+        *setting_name = NM_SETTING_802_1X_SETTING_NAME;
+        *setting_key  = NM_SETTING_802_1X_PASSWORD;
+        return TRUE;
+    } else
+        return FALSE;
+}
+
+static gboolean
+assumed_ac_timeout_cb(gpointer user_data)
+{
+    NMDeviceIwd *       self = user_data;
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+
+    nm_assert(priv->assumed_ac);
+
+    priv->assumed_ac_timeout = 0;
+    nm_device_state_changed(NM_DEVICE(self),
+                            NM_DEVICE_STATE_FAILED,
+                            NM_DEVICE_STATE_REASON_SUPPLICANT_TIMEOUT);
+    /* NMDevice's state change -> NMActRequests/NMActiveConnection's state
+     * change -> assumed_connection_state_changed_before_managed() ->
+     * cleanup_association_attempt() so no need to call it explicitly.
+     */
+    return G_SOURCE_REMOVE;
+}
+
+static void wifi_secrets_get_one(NMDeviceIwd *                self,
+                                 const char *                 setting_name,
+                                 NMSecretAgentGetSecretsFlags flags,
+                                 const char *                 setting_key,
+                                 GDBusMethodInvocation *      invocation);
+
+static void
+wifi_secrets_cb(NMActRequest *                req,
+                NMActRequestGetSecretsCallId *call_id,
+                NMSettingsConnection *        s_connection,
+                GError *                      error,
+                gpointer                      user_data)
+{
+    NMDeviceIwd *                self;
+    NMDeviceIwdPrivate *         priv;
+    NMDevice *                   device;
+    GDBusMethodInvocation *      invocation;
+    const char *                 setting_name;
+    const char *                 setting_key;
+    gboolean                     replied;
+    NMSecretAgentGetSecretsFlags get_secret_flags =
+        NM_SECRET_AGENT_GET_SECRETS_FLAG_ALLOW_INTERACTION;
+
+    nm_utils_user_data_unpack(user_data, &self, &invocation);
+
+    g_return_if_fail(NM_IS_DEVICE_IWD(self));
+
+    priv   = NM_DEVICE_IWD_GET_PRIVATE(self);
+    device = NM_DEVICE(self);
+
+    g_return_if_fail(priv->wifi_secrets_id == call_id);
+
+    priv->wifi_secrets_id = NULL;
+
+    if (nm_utils_error_is_cancelled(error)) {
+        priv->secrets_failed = TRUE;
+        g_dbus_method_invocation_return_error_literal(invocation,
+                                                      NM_DEVICE_ERROR,
+                                                      NM_DEVICE_ERROR_INVALID_CONNECTION,
+                                                      "NM secrets request cancelled");
+        return;
+    }
+
+    g_return_if_fail(req == nm_device_get_act_request(device));
+    g_return_if_fail(nm_act_request_get_settings_connection(req) == s_connection);
+
+    if (nm_device_get_state(device) != NM_DEVICE_STATE_NEED_AUTH)
+        goto secrets_error;
+
+    if (error) {
+        _LOGW(LOGD_WIFI, "%s", error->message);
+        goto secrets_error;
+    }
+
+    if (!try_reply_agent_request(self,
+                                 nm_act_request_get_applied_connection(req),
+                                 invocation,
+                                 &setting_name,
+                                 &setting_key,
+                                 &replied))
+        goto secrets_error;
+
+    if (replied) {
+        /* If we replied to the secrets request from IWD in the "disconnected"
+         * state and IWD doesn't move to a new state within 1 second, assume
+         * something went wrong (shouldn't happen).  If a state change arrives
+         * after that nothing is lost, state_changed() will try to assume the
+         * connection again.
+         */
+        if (priv->assumed_ac) {
+            gs_unref_variant GVariant *value =
+                g_dbus_proxy_get_cached_property(priv->dbus_station_proxy, "State");
+
+            if (nm_streq(get_variant_state(value), "disconnected"))
+                priv->assumed_ac_timeout = g_timeout_add_seconds(1, assumed_ac_timeout_cb, self);
+        }
+
+        /* Change state back to what it was before NEED_AUTH */
+        nm_device_state_changed(device, NM_DEVICE_STATE_CONFIG, NM_DEVICE_STATE_REASON_NONE);
+        return;
+    }
+
+    if (nm_settings_connection_get_timestamp(nm_act_request_get_settings_connection(req), NULL))
+        get_secret_flags |= NM_SECRET_AGENT_GET_SECRETS_FLAG_REQUEST_NEW;
+
+    /* Request further secrets if we still need something */
+    wifi_secrets_get_one(self, setting_name, get_secret_flags, setting_key, invocation);
+    return;
+
+secrets_error:
+    g_dbus_method_invocation_return_error_literal(invocation,
+                                                  NM_DEVICE_ERROR,
+                                                  NM_DEVICE_ERROR_INVALID_CONNECTION,
+                                                  "NM secrets request failed");
+
+    if (priv->assumed_ac) {
+        nm_device_state_changed(device, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_NO_SECRETS);
+        /* NMDevice's state change -> NMActRequests/NMActiveConnection's state
+         * change -> assumed_connection_state_changed_before_managed() ->
+         * cleanup_association_attempt() so no need to call it explicitly.
+         */
+    } else {
+        priv->secrets_failed = TRUE;
+        /* Now wait for the Connect callback to update device state */
+    }
+}
+
+static void
+wifi_secrets_get_one(NMDeviceIwd *                self,
+                     const char *                 setting_name,
+                     NMSecretAgentGetSecretsFlags flags,
+                     const char *                 setting_key,
+                     GDBusMethodInvocation *      invocation)
+{
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+    NMActRequest *      req;
+
+    wifi_secrets_cancel(self);
+
+    req = nm_device_get_act_request(NM_DEVICE(self));
+    g_return_if_fail(NM_IS_ACT_REQUEST(req));
+
+    priv->wifi_secrets_id = nm_act_request_get_secrets(req,
+                                                       TRUE,
+                                                       setting_name,
+                                                       flags,
+                                                       NM_MAKE_STRV(setting_key),
+                                                       wifi_secrets_cb,
+                                                       nm_utils_user_data_pack(self, invocation));
+}
+
+static void
+network_connect_cb(GObject *source, GAsyncResult *res, gpointer user_data)
+{
+    NMDeviceIwd *       self           = user_data;
+    NMDevice *          device         = NM_DEVICE(self);
+    NMDeviceIwdPrivate *priv           = NM_DEVICE_IWD_GET_PRIVATE(self);
+    gs_unref_variant GVariant *variant = NULL;
+    gs_free_error GError *error        = NULL;
+    NMConnection *        connection;
+    gs_free char *        ssid   = NULL;
+    NMDeviceStateReason   reason = NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED;
+    GVariant *            value;
+    gboolean              disconnect;
+
+    disconnect = !priv->iwd_autoconnect
+                 || nm_device_autoconnect_blocked_get(device, NM_DEVICE_AUTOCONNECT_BLOCKED_ALL);
+
+    variant = g_dbus_proxy_call_finish(G_DBUS_PROXY(source), res, &error);
+    if (!variant) {
+        gs_free char *dbus_error = NULL;
+
+        /* Connection failed; radio problems or if the network wasn't
+         * open, the passwords or certificates may be wrong.
+         */
+
+        _LOGE(LOGD_DEVICE | LOGD_WIFI,
+              "Activation: (wifi) Network.Connect failed: %s",
+              error->message);
+
+        if (nm_utils_error_is_cancelled(error))
+            return;
+
+        if (!NM_IN_SET(nm_device_get_state(device),
+                       NM_DEVICE_STATE_CONFIG,
+                       NM_DEVICE_STATE_NEED_AUTH))
+            return;
+
+        connection = nm_device_get_applied_connection(device);
+        if (!connection)
+            goto failed;
+
+        if (g_error_matches(error, G_IO_ERROR, G_IO_ERROR_DBUS_ERROR))
+            dbus_error = g_dbus_error_get_remote_error(error);
+
+        if (nm_streq0(dbus_error, "net.connman.iwd.Failed")) {
+            nm_connection_clear_secrets(connection);
+
+            /* If secrets were wrong, we'd be getting a net.connman.iwd.Failed */
+            reason = NM_DEVICE_STATE_REASON_NO_SECRETS;
+        } else if (nm_streq0(dbus_error, "net.connman.iwd.Aborted") && priv->secrets_failed) {
+            /* If agent call was cancelled we'd be getting a net.connman.iwd.Aborted */
+            reason = NM_DEVICE_STATE_REASON_NO_SECRETS;
+        }
+
+        goto failed;
+    }
+
+    nm_assert(nm_device_get_state(device) == NM_DEVICE_STATE_CONFIG);
+
+    disconnect = TRUE;
+
+    connection = nm_device_get_applied_connection(device);
+    if (!connection)
+        goto failed;
+
+    if (!nm_wifi_connection_get_iwd_ssid_and_security(connection, &ssid, NULL))
+        goto failed;
+
+    _LOGI(LOGD_DEVICE | LOGD_WIFI,
+          "Activation: (wifi) Stage 2 of 5 (Device Configure) successful.  Connected to '%s'.",
+          ssid);
+    nm_device_activate_schedule_stage3_ip_config_start(device);
+
+    return;
+
+failed:
+    /* If necessary call Disconnect to make sure IWD's autoconnect is disabled */
+    cleanup_association_attempt(self, disconnect);
+
+    nm_device_state_changed(device, NM_DEVICE_STATE_FAILED, reason);
+
+    value = g_dbus_proxy_get_cached_property(priv->dbus_station_proxy, "State");
+    if (!priv->iwd_autoconnect && nm_streq(get_variant_state(value), "disconnected")) {
+        schedule_periodic_scan(self, TRUE);
+
+        if (!priv->nm_autoconnect) {
+            priv->nm_autoconnect = true;
+            nm_device_emit_recheck_auto_activate(device);
+        }
+    }
+    g_variant_unref(value);
+}
+
+static void
+act_failed_cb(GObject *source, GAsyncResult *res, gpointer user_data)
+{
+    NMDeviceIwd *    self              = user_data;
+    NMDevice *       device            = NM_DEVICE(self);
+    gs_unref_variant GVariant *variant = NULL;
+    gs_free_error GError *error        = NULL;
+
+    variant = g_dbus_proxy_call_finish(G_DBUS_PROXY(source), res, &error);
+    if (!variant && nm_utils_error_is_cancelled(error))
+        return;
+
+    /* Change state to FAILED unless already done by state_changed
+     * which may have been triggered by the station interface
+     * appearing on DBus.
+     */
+    if (nm_device_get_state(device) == NM_DEVICE_STATE_CONFIG)
+        nm_device_queue_state(device,
+                              NM_DEVICE_STATE_FAILED,
+                              NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
+}
+
+static void
+act_start_cb(GObject *source, GAsyncResult *res, gpointer user_data)
+{
+    NMDeviceIwd *       self           = user_data;
+    NMDeviceIwdPrivate *priv           = NM_DEVICE_IWD_GET_PRIVATE(self);
+    NMDevice *          device         = NM_DEVICE(self);
+    gs_unref_variant GVariant *variant = NULL;
+    gs_free_error GError *error        = NULL;
+    gs_free char *        ssid         = NULL;
+
+    variant = g_dbus_proxy_call_finish(G_DBUS_PROXY(source), res, &error);
+    if (!variant) {
+        _LOGE(LOGD_DEVICE | LOGD_WIFI,
+              "Activation: (wifi) {AccessPoint,AdHoc}.Start() failed: %s",
+              error->message);
+
+        if (nm_utils_error_is_cancelled(error))
+            return;
+
+        if (!NM_IN_SET(nm_device_get_state(device), NM_DEVICE_STATE_CONFIG))
+            return;
+
+        goto error;
+    }
+
+    nm_assert(nm_device_get_state(device) == NM_DEVICE_STATE_CONFIG);
+
+    if (!nm_wifi_connection_get_iwd_ssid_and_security(nm_device_get_applied_connection(device),
+                                                      &ssid,
+                                                      NULL))
+        goto error;
+
+    _LOGI(LOGD_DEVICE | LOGD_WIFI,
+          "Activation: (wifi) Stage 2 of 5 (Device Configure) successful.  Started '%s'.",
+          ssid);
+    nm_device_activate_schedule_stage3_ip_config_start(device);
+
+    return;
+
+error:
+    reset_mode(self, priv->cancellable, act_failed_cb, self);
+}
+
+/* Check if we're activating an AP/AdHoc connection and if the target
+ * DBus interface has appeared already.  If so proceed to call Start or
+ * StartOpen on that interface.
+ */
+static void
+act_check_interface(NMDeviceIwd *self)
+{
+    NMDeviceIwdPrivate * priv   = NM_DEVICE_IWD_GET_PRIVATE(self);
+    NMDevice *           device = NM_DEVICE(self);
+    NMSettingWireless *  s_wireless;
+    GDBusProxy *         proxy = NULL;
+    gs_free char *       ssid  = NULL;
+    const char *         mode;
+    NMIwdNetworkSecurity security;
+
+    if (!priv->act_mode_switch)
+        return;
+
+    s_wireless =
+        (NMSettingWireless *) nm_device_get_applied_setting(device, NM_TYPE_SETTING_WIRELESS);
+
+    mode = nm_setting_wireless_get_mode(s_wireless);
+    if (nm_streq0(mode, NM_SETTING_WIRELESS_MODE_AP))
+        proxy = priv->dbus_ap_proxy;
+    else if (nm_streq0(mode, NM_SETTING_WIRELESS_MODE_ADHOC))
+        proxy = priv->dbus_adhoc_proxy;
+
+    if (!proxy)
+        return;
+
+    priv->act_mode_switch = FALSE;
+
+    if (!NM_IN_SET(nm_device_get_state(device), NM_DEVICE_STATE_CONFIG))
+        return;
+
+    if (!nm_wifi_connection_get_iwd_ssid_and_security(nm_device_get_applied_connection(device),
+                                                      &ssid,
+                                                      &security))
+        goto failed;
+
+    if (security == NM_IWD_NETWORK_SECURITY_OPEN) {
+        g_dbus_proxy_call(proxy,
+                          "StartOpen",
+                          g_variant_new("(s)", ssid),
+                          G_DBUS_CALL_FLAGS_NONE,
+                          G_MAXINT,
+                          priv->cancellable,
+                          act_start_cb,
+                          self);
+    } else if (security == NM_IWD_NETWORK_SECURITY_PSK) {
+        NMSettingWirelessSecurity *s_wireless_sec;
+        const char *               psk;
+
+        s_wireless_sec = (NMSettingWirelessSecurity *) nm_device_get_applied_setting(
+            device,
+            NM_TYPE_SETTING_WIRELESS_SECURITY);
+        psk = nm_setting_wireless_security_get_psk(s_wireless_sec);
+
+        if (!psk) {
+            _LOGE(LOGD_DEVICE | LOGD_WIFI, "Activation: (wifi) No PSK for '%s'.", ssid);
+            goto failed;
+        }
+
+        g_dbus_proxy_call(proxy,
+                          "Start",
+                          g_variant_new("(ss)", ssid, psk),
+                          G_DBUS_CALL_FLAGS_NONE,
+                          G_MAXINT,
+                          priv->cancellable,
+                          act_start_cb,
+                          self);
+    } else
+        goto failed;
+
+    _LOGD(LOGD_DEVICE | LOGD_WIFI, "Activation: (wifi) Called Start('%s').", ssid);
+    return;
+
+failed:
+    reset_mode(self, priv->cancellable, act_failed_cb, self);
+}
+
+static void
+act_set_mode_cb(GObject *source, GAsyncResult *res, gpointer user_data)
+{
+    NMDeviceIwd *       self           = user_data;
+    NMDeviceIwdPrivate *priv           = NM_DEVICE_IWD_GET_PRIVATE(self);
+    NMDevice *          device         = NM_DEVICE(self);
+    gs_unref_variant GVariant *variant = NULL;
+    gs_free_error GError *error        = NULL;
+
+    variant = g_dbus_proxy_call_finish(G_DBUS_PROXY(source), res, &error);
+    if (!variant) {
+        _LOGE(LOGD_DEVICE | LOGD_WIFI,
+              "Activation: (wifi) Setting Device.Mode failed: %s",
+              error->message);
+
+        if (nm_utils_error_is_cancelled(error))
+            return;
+
+        if (!NM_IN_SET(nm_device_get_state(device), NM_DEVICE_STATE_CONFIG)
+            || !priv->act_mode_switch)
+            return;
+
+        priv->act_mode_switch = FALSE;
+        nm_device_queue_state(device,
+                              NM_DEVICE_STATE_FAILED,
+                              NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
+        return;
+    }
+
+    _LOGD(LOGD_DEVICE | LOGD_WIFI, "Activation: (wifi) IWD Device.Mode set successfully");
+
+    act_check_interface(self);
+}
+
+static void
+act_set_mode(NMDeviceIwd *self)
+{
+    NMDeviceIwdPrivate *priv   = NM_DEVICE_IWD_GET_PRIVATE(self);
+    NMDevice *          device = NM_DEVICE(self);
+    const char *        iwd_mode;
+    const char *        mode;
+    NMSettingWireless * s_wireless;
+
+    s_wireless =
+        (NMSettingWireless *) nm_device_get_applied_setting(device, NM_TYPE_SETTING_WIRELESS);
+    mode = nm_setting_wireless_get_mode(s_wireless);
+
+    /* We need to first set interface mode (Device.Mode) to ap or ad-hoc.
+     * We can't directly queue a call to the Start/StartOpen method on
+     * the DBus interface that's going to be created after the property
+     * set call returns.
+     */
+    iwd_mode = nm_streq(mode, NM_SETTING_WIRELESS_MODE_AP) ? "ap" : "ad-hoc";
+
+    if (!priv->cancellable)
+        priv->cancellable = g_cancellable_new();
+
+    g_dbus_proxy_call(
+        priv->dbus_device_proxy,
+        DBUS_INTERFACE_PROPERTIES ".Set",
+        g_variant_new("(ssv)", NM_IWD_DEVICE_INTERFACE, "Mode", g_variant_new("s", iwd_mode)),
+        G_DBUS_CALL_FLAGS_NONE,
+        2000,
+        priv->cancellable,
+        act_set_mode_cb,
+        self);
+    priv->act_mode_switch = TRUE;
+}
+
+static void
+act_psk_cb(NMActRequest *                req,
+           NMActRequestGetSecretsCallId *call_id,
+           NMSettingsConnection *        s_connection,
+           GError *                      error,
+           gpointer                      user_data)
+{
+    NMDeviceIwd *       self = user_data;
+    NMDeviceIwdPrivate *priv;
+    NMDevice *          device;
+
+    if (nm_utils_error_is_cancelled(error))
+        return;
+
+    priv   = NM_DEVICE_IWD_GET_PRIVATE(self);
+    device = NM_DEVICE(self);
+
+    g_return_if_fail(priv->wifi_secrets_id == call_id);
+    priv->wifi_secrets_id = NULL;
+
+    g_return_if_fail(req == nm_device_get_act_request(device));
+    g_return_if_fail(nm_act_request_get_settings_connection(req) == s_connection);
+
+    if (nm_device_get_state(device) != NM_DEVICE_STATE_NEED_AUTH)
+        goto secrets_error;
+
+    if (error) {
+        _LOGW(LOGD_WIFI, "%s", error->message);
+        goto secrets_error;
+    }
+
+    _LOGD(LOGD_DEVICE | LOGD_WIFI, "Activation: (wifi) missing PSK request completed");
+
+    /* Change state back to what it was before NEED_AUTH */
+    nm_device_state_changed(device, NM_DEVICE_STATE_CONFIG, NM_DEVICE_STATE_REASON_NONE);
+    act_set_mode(self);
+    return;
+
+secrets_error:
+    nm_device_state_changed(device, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_NO_SECRETS);
+    cleanup_association_attempt(self, FALSE);
+}
+
+static void
+set_powered(NMDeviceIwd *self, gboolean powered)
+{
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+
+    g_dbus_proxy_call(
+        priv->dbus_device_proxy,
+        DBUS_INTERFACE_PROPERTIES ".Set",
+        g_variant_new("(ssv)", NM_IWD_DEVICE_INTERFACE, "Powered", g_variant_new("b", powered)),
+        G_DBUS_CALL_FLAGS_NONE,
+        2000,
+        NULL,
+        NULL,
+        NULL);
+}
+
+/*****************************************************************************/
+
+static NMWifiAP *
+find_ap_by_supplicant_path(NMDeviceIwd *self, const NMRefString *path)
+{
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+    NMWifiAP *          tmp;
+
+    c_list_for_each_entry (tmp, &priv->aps_lst_head, aps_lst)
+        if (nm_wifi_ap_get_supplicant_path(tmp) == path)
+            return tmp;
+
+    return NULL;
+}
+
+static void
+assumed_connection_state_changed(NMActiveConnection *active, GParamSpec *pspec, NMDeviceIwd *self)
+{
+    NMSettingsConnection *  sett_conn = nm_active_connection_get_settings_connection(active);
+    NMActiveConnectionState state     = nm_active_connection_get_state(active);
+
+    /* Delete the temporary connection created for an external IWD connection
+     * (triggered by somebody outside of NM, be it IWD autoconnect or a
+     * parallel client), unless it's been referenced by a Known Network
+     * object since, which would remove the EXTERNAL flag.
+     *
+     * Note we can't do this too early, e.g. at the same time that we're
+     * setting the device state to FAILED or DISCONNECTING because the
+     * connection shouldn't disappear while it's still being used.  We do
+     * this on the connection's transition to DEACTIVATED same as as
+     * NMManager does for external activations.
+     */
+    if (state != NM_ACTIVE_CONNECTION_STATE_DEACTIVATED)
+        return;
+
+    g_signal_handlers_disconnect_by_func(active, assumed_connection_state_changed, NULL);
+
+    if (sett_conn
+        && NM_FLAGS_HAS(nm_settings_connection_get_flags(sett_conn),
+                        NM_SETTINGS_CONNECTION_INT_FLAGS_EXTERNAL))
+        nm_settings_connection_delete(sett_conn, FALSE);
+}
+
+static void
+assumed_connection_state_changed_before_managed(NMActiveConnection *active,
+                                                GParamSpec *        pspec,
+                                                NMDeviceIwd *       self)
+{
+    NMDeviceIwdPrivate *    priv  = NM_DEVICE_IWD_GET_PRIVATE(self);
+    NMActiveConnectionState state = nm_active_connection_get_state(active);
+    gboolean                disconnect;
+
+    if (state != NM_ACTIVE_CONNECTION_STATE_DEACTIVATED)
+        return;
+
+    /* When an assumed connection fails we always get called, even if the
+     * activation hasn't reached PREPARE or CONFIG, e.g. because of a policy
+     * or authorization problem in NMManager.  .deactivate would only be
+     * called starting at some stage so we can't rely on that.
+     *
+     * If the error happened before PREPARE (where we set a non-NULL
+     * priv->current_ap) that will mean NM is somehow blocking autoconnect
+     * so we want to call IWD's Station.Disconnect() to block its
+     * autoconnect.  If this happens during or after PREPARE, we just
+     * clean up and wait for a new attempt by IWD.
+     *
+     * cleanup_association_attempt will clear priv->assumed_ac, disconnect
+     * this callback from the signal and also send a Disconnect to IWD if
+     * needed.
+     *
+     * Note this function won't be called after IWD transitions to
+     * "connected" (and NMDevice to IP_CONFIG) as we disconnect from the
+     * signal at that point, cleanup_association_attempt() will be
+     * triggered by an IWD state change instead.
+     */
+    disconnect = !priv->current_ap;
+    cleanup_association_attempt(self, disconnect);
+}
+
+static void
+assume_connection(NMDeviceIwd *self, NMWifiAP *ap)
+{
+    NMDeviceIwdPrivate *  priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+    NMSettingsConnection *sett_conn;
+    gs_unref_object NMAuthSubject *subject = NULL;
+    NMActiveConnection *           ac;
+    gs_free_error GError *error = NULL;
+
+    /* We can use the .update_connection / nm_device_emit_recheck_assume
+     * API but we can also pass an assumed/external activation type
+     * directly to nm_manager_activate_connection() and skip the
+     * complicated process of creating a matching connection, taking
+     * advantage of the Known Networks pointing directly to a mirror
+     * connection.  The only downside seems to be
+     * nm_manager_activate_connection() goes through the extra
+     * authorization.
+     *
+     * However for now we implement a similar behaviour using a normal
+     * "managed" activation.  For one, assumed/external
+     * connection state is not reflected in nm_manager_get_state() until
+     * fully activated.  Secondly setting the device state to FAILED
+     * is treated as ACTIVATED so we'd have to find another way to signal
+     * that stage2 is failing asynchronously.  Thirdly the connection
+     * becomes "managed" only when ACTIVATED but for IWD it's really
+     * managed when IP_CONFIG starts.
+     */
+    sett_conn = nm_iwd_manager_get_ap_mirror_connection(nm_iwd_manager_get(), ap);
+    if (!sett_conn)
+        goto error;
+
+    subject = nm_auth_subject_new_internal();
+    ac      = nm_manager_activate_connection(
+        NM_MANAGER_GET,
+        sett_conn,
+        NULL,
+        nm_dbus_object_get_path(NM_DBUS_OBJECT(ap)),
+        NM_DEVICE(self),
+        subject,
+        NM_ACTIVATION_TYPE_MANAGED,
+        NM_ACTIVATION_REASON_ASSUME,
+        NM_ACTIVATION_STATE_FLAG_LIFETIME_BOUND_TO_PROFILE_VISIBILITY,
+        &error);
+
+    if (!ac) {
+        _LOGW(LOGD_WIFI, "Activation: (wifi) assume error: %s", error->message);
+        goto error;
+    }
+
+    /* If no Known Network existed for this AP, we generated a temporary
+     * NMSettingsConnection with the EXTERNAL flag.  It is not referenced by
+     * any Known Network objects at this time so we want to delete it if the
+     * IWD connection ends up failing or a later part of the activation fails
+     * before IWD created a Known Network.
+     * Setting the activation type to EXTERNAL would do this by causing
+     * NM_ACTIVATION_STATE_FLAG_EXTERNAL to be set on the NMActiveConnection
+     * but we don't want the connection to be marked EXTERNAL because we
+     * will be assuming the ownership of it in IP_CONFIG or thereabouts.
+     *
+     * This callback stays connected forever while the second one gets
+     * disconnected when we reset the activation type to managed.
+     */
+    g_signal_connect(ac,
+                     "notify::" NM_ACTIVE_CONNECTION_STATE,
+                     G_CALLBACK(assumed_connection_state_changed),
+                     NULL);
+    g_signal_connect(ac,
+                     "notify::" NM_ACTIVE_CONNECTION_STATE,
+                     G_CALLBACK(assumed_connection_state_changed_before_managed),
+                     self);
+    priv->assumed_ac = g_object_ref(ac);
+
+    return;
+
+error:
+    send_disconnect(self);
+
+    if (sett_conn
+        && NM_FLAGS_HAS(nm_settings_connection_get_flags(sett_conn),
+                        NM_SETTINGS_CONNECTION_INT_FLAGS_EXTERNAL))
+        nm_settings_connection_delete(sett_conn, FALSE);
+}
+
+static void
+assumed_connection_progress_to_ip_config(NMDeviceIwd *self, gboolean was_postponed)
+{
+    NMDeviceIwdPrivate *priv      = NM_DEVICE_IWD_GET_PRIVATE(self);
+    NMDevice *          device    = NM_DEVICE(self);
+    NMDeviceState       dev_state = nm_device_get_state(device);
+
+    wifi_secrets_cancel(self);
+    nm_clear_g_source(&priv->assumed_ac_timeout);
+
+    /* NM takes over the activation from this point on so clear the assumed
+     * activation state and if we were using NM_ACTIVATION_TYPE_ASSUMED or
+     * _EXTERNAL we'd need to reset the activation type to _MANAGED at this
+     * point instead of waiting for the ACTIVATED state (as done in
+     * nm_active_connection_set_state).
+     */
+    cleanup_assumed_connect(self);
+
+    if (dev_state == NM_DEVICE_STATE_NEED_AUTH)
+        nm_device_state_changed(NM_DEVICE(self),
+                                NM_DEVICE_STATE_CONFIG,
+                                NM_DEVICE_STATE_REASON_NONE);
+
+    /* If stage2 had returned NM_ACT_STAGE_RETURN_POSTPONE, we tell NMDevice
+     * that stage2 is done.
+     */
+    if (was_postponed)
+        nm_device_activate_schedule_stage3_ip_config_start(NM_DEVICE(self));
+}
+
+static void
+initial_check_assume(NMDeviceIwd *self)
+{
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+    const char *        network_path_str;
+    nm_auto_ref_string NMRefString *network_path = NULL;
+    NMWifiAP *                      ap           = NULL;
+    gs_unref_variant GVariant *state_value =
+        g_dbus_proxy_get_cached_property(priv->dbus_station_proxy, "State");
+    gs_unref_variant GVariant *cn_value =
+        g_dbus_proxy_get_cached_property(priv->dbus_station_proxy, "ConnectedNetwork");
+
+    if (!NM_IN_STRSET(get_variant_state(state_value), "connecting", "connected", "roaming"))
+        return;
+
+    if (!priv->iwd_autoconnect) {
+        send_disconnect(self);
+        return;
+    }
+
+    if (!cn_value || !g_variant_is_of_type(cn_value, G_VARIANT_TYPE_OBJECT_PATH)) {
+        _LOGW(LOGD_DEVICE | LOGD_WIFI,
+              "ConnectedNetwork property not cached or not an object path");
+        return;
+    }
+
+    network_path_str = g_variant_get_string(cn_value, NULL);
+    network_path     = nm_ref_string_new(network_path_str);
+    ap               = find_ap_by_supplicant_path(self, network_path);
+
+    if (!ap) {
+        _LOGW(LOGD_DEVICE | LOGD_WIFI,
+              "ConnectedNetwork points to an unknown Network %s",
+              network_path_str);
+        return;
+    }
+
+    _LOGD(LOGD_DEVICE | LOGD_WIFI, "assuming connection in initial_check_assume");
+    assume_connection(self, ap);
+}
+
+static NMActStageReturn
+act_stage1_prepare(NMDevice *device, NMDeviceStateReason *out_failure_reason)
+{
+    NMDeviceIwd *       self          = NM_DEVICE_IWD(device);
+    NMDeviceIwdPrivate *priv          = NM_DEVICE_IWD_GET_PRIVATE(self);
+    NMWifiAP *          ap            = NULL;
+    gs_unref_object NMWifiAP *ap_fake = NULL;
+    NMActRequest *            req;
+    NMConnection *            connection;
+    NMSettingWireless *       s_wireless;
+    const char *              mode;
+    const char *              ap_path;
+
+    req = nm_device_get_act_request(device);
+    g_return_val_if_fail(req, NM_ACT_STAGE_RETURN_FAILURE);
+
+    connection = nm_act_request_get_applied_connection(req);
+    g_return_val_if_fail(connection, NM_ACT_STAGE_RETURN_FAILURE);
+
+    s_wireless = nm_connection_get_setting_wireless(connection);
+    g_return_val_if_fail(s_wireless, NM_ACT_STAGE_RETURN_FAILURE);
+
+    /* AP, Ad-Hoc modes never use a specific object or existing scanned AP */
+    mode = nm_setting_wireless_get_mode(s_wireless);
+    if (NM_IN_STRSET(mode, NM_SETTING_WIRELESS_MODE_AP, NM_SETTING_WIRELESS_MODE_ADHOC))
+        goto add_new;
+
+    ap_path = nm_active_connection_get_specific_object(NM_ACTIVE_CONNECTION(req));
+    ap      = ap_path ? nm_wifi_ap_lookup_for_device(NM_DEVICE(self), ap_path) : NULL;
+    if (ap) {
+        set_current_ap(self, ap, TRUE);
+        return NM_ACT_STAGE_RETURN_SUCCESS;
+    }
+
+    ap = nm_wifi_aps_find_first_compatible(&priv->aps_lst_head, connection);
+    if (ap) {
+        nm_active_connection_set_specific_object(NM_ACTIVE_CONNECTION(req),
+                                                 nm_dbus_object_get_path(NM_DBUS_OBJECT(ap)));
+        set_current_ap(self, ap, TRUE);
+        return NM_ACT_STAGE_RETURN_SUCCESS;
+    }
+
+    /* In infrastructure mode the specific object should be set by now except
+     * for a first-time connection to a hidden network.  If a hidden network is
+     * a Known Network it should still have been in the AP list.
+     */
+    if (!nm_setting_wireless_get_hidden(s_wireless) || is_connection_known_network(connection))
+        return NM_ACT_STAGE_RETURN_FAILURE;
+
+add_new:
+    /* If the user is trying to connect to an AP that NM doesn't yet know about
+     * (hidden network or something) or starting a Hotspot, create a fake AP
+     * from the security settings in the connection.  This "fake" AP gets used
+     * until the real one is found in the scan list (Ad-Hoc or Hidden), or until
+     * the device is deactivated (Ad-Hoc or Hotspot).
+     */
+    ap_fake = nm_wifi_ap_new_fake_from_connection(connection);
+    if (!ap_fake)
+        g_return_val_if_reached(NM_ACT_STAGE_RETURN_FAILURE);
+
+    if (nm_wifi_ap_is_hotspot(ap_fake))
+        nm_wifi_ap_set_address(ap_fake, nm_device_get_hw_address(device));
+
+    g_object_freeze_notify(G_OBJECT(self));
+    ap_add_remove(self, TRUE, ap_fake, FALSE);
+    g_object_thaw_notify(G_OBJECT(self));
+    set_current_ap(self, ap_fake, FALSE);
+    nm_active_connection_set_specific_object(NM_ACTIVE_CONNECTION(req),
+                                             nm_dbus_object_get_path(NM_DBUS_OBJECT(ap_fake)));
+    return NM_ACT_STAGE_RETURN_SUCCESS;
+}
+
+static NMActStageReturn
+act_stage2_config(NMDevice *device, NMDeviceStateReason *out_failure_reason)
+{
+    NMDeviceIwd *       self = NM_DEVICE_IWD(device);
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+    NMActRequest *      req;
+    NMConnection *      connection;
+    NMSettingWireless * s_wireless;
+    const char *        mode;
+
+    req        = nm_device_get_act_request(device);
+    connection = nm_act_request_get_applied_connection(req);
+    s_wireless = nm_connection_get_setting_wireless(connection);
+    g_return_val_if_fail(s_wireless, NM_ACT_STAGE_RETURN_FAILURE);
+
+    mode = nm_setting_wireless_get_mode(s_wireless);
+
+    if (NM_IN_STRSET(mode, NULL, NM_SETTING_WIRELESS_MODE_INFRA)) {
+        gs_unref_object GDBusProxy *network_proxy = NULL;
+        NMWifiAP *                  ap            = priv->current_ap;
+        NMSettingWirelessSecurity * s_wireless_sec;
+
+        if (!ap) {
+            NM_SET_OUT(out_failure_reason, NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
+            goto out_fail;
+        }
+
+        /* With priv->iwd_autoconnect, if we're assuming a connection because
+         * of a state change to "connecting", signal stage 2 is still running.
+         * If "connected" or "roaming", we can go right to the IP_CONFIG state
+         * and there's nothing left to do in CONFIG.
+         * If we're assuming the connection because of an agent request we
+         * switch to NEED_AUTH and actually send the request now that we
+         * have an activation request.
+         *
+         * This all assumes ConnectedNetwork hasn't changed.
+         */
+        if (priv->assumed_ac) {
+            gboolean result;
+
+            if (!priv->pending_agent_request) {
+                gs_unref_variant GVariant *value =
+                    g_dbus_proxy_get_cached_property(priv->dbus_station_proxy, "State");
+
+                if (nm_streq(get_variant_state(value), "connecting")) {
+                    return NM_ACT_STAGE_RETURN_POSTPONE;
+                } else {
+                    /* This basically forgets that the connection was "assumed"
+                     * as we can treat it like any connection triggered by a
+                     * Network.Connect() call from now on.
+                     */
+                    assumed_connection_progress_to_ip_config(self, FALSE);
+                    return NM_ACT_STAGE_RETURN_SUCCESS;
+                }
+            }
+
+            result = nm_device_iwd_agent_query(self, priv->pending_agent_request);
+            g_clear_object(&priv->pending_agent_request);
+            nm_assert(result);
+
+            return NM_ACT_STAGE_RETURN_POSTPONE;
+        }
+
+        /* 802.1x networks that are not IWD Known Networks will definitely
+         * fail, for other combinations we will let the Connect call fail
+         * or ask us for any missing secrets through the Agent.
+         */
+        if (nm_connection_get_setting_802_1x(connection) && !is_ap_known_network(ap)) {
+            _LOGI(LOGD_DEVICE | LOGD_WIFI,
+                  "Activation: (wifi) access point '%s' has 802.1x security but is not configured "
+                  "in IWD.",
+                  nm_connection_get_id(connection));
+
+            NM_SET_OUT(out_failure_reason, NM_DEVICE_STATE_REASON_NO_SECRETS);
+            goto out_fail;
+        }
+
+        priv->secrets_failed = FALSE;
+
+        if (nm_wifi_ap_get_fake(ap)) {
+            gs_free char *ssid = NULL;
+
+            if (!nm_setting_wireless_get_hidden(s_wireless)) {
+                _LOGW(LOGD_DEVICE | LOGD_WIFI,
+                      "Activation: (wifi) target network not known to IWD but is not "
+                      "marked hidden");
+                NM_SET_OUT(out_failure_reason, NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
+                goto out_fail;
+            }
+
+            if (!nm_wifi_connection_get_iwd_ssid_and_security(connection, &ssid, NULL)) {
+                NM_SET_OUT(out_failure_reason, NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
+                goto out_fail;
+            }
+
+            /* Use Station.ConnectHiddenNetwork method instead of Network proxy. */
+            g_dbus_proxy_call(priv->dbus_station_proxy,
+                              "ConnectHiddenNetwork",
+                              g_variant_new("(s)", ssid),
+                              G_DBUS_CALL_FLAGS_NONE,
+                              G_MAXINT,
+                              priv->cancellable,
+                              network_connect_cb,
+                              self);
+            return NM_ACT_STAGE_RETURN_POSTPONE;
+        }
+
+        network_proxy = nm_iwd_manager_get_dbus_interface(
+            nm_iwd_manager_get(),
+            nm_ref_string_get_str(nm_wifi_ap_get_supplicant_path(ap)),
+            NM_IWD_NETWORK_INTERFACE);
+        if (!network_proxy) {
+            _LOGW(LOGD_DEVICE | LOGD_WIFI,
+                  "Activation: (wifi) could not get Network interface proxy for %s",
+                  nm_ref_string_get_str(nm_wifi_ap_get_supplicant_path(ap)));
+            NM_SET_OUT(out_failure_reason, NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
+            goto out_fail;
+        }
+
+        if (!priv->cancellable)
+            priv->cancellable = g_cancellable_new();
+
+        s_wireless_sec = nm_connection_get_setting_wireless_security(connection);
+        if (s_wireless_sec
+            && nm_streq0(nm_setting_wireless_security_get_key_mgmt(s_wireless_sec), "owe")) {
+            _LOGI(LOGD_WIFI,
+                  "An OWE connection is requested but IWD may connect to either an OWE "
+                  "or unsecured network and there won't be any indication of whether "
+                  "encryption is in use -- proceed at your own risk!");
+        }
+
+        /* Call Network.Connect.  No timeout because IWD already handles
+         * timeouts.
+         */
+        g_dbus_proxy_call(network_proxy,
+                          "Connect",
+                          NULL,
+                          G_DBUS_CALL_FLAGS_NONE,
+                          G_MAXINT,
+                          priv->cancellable,
+                          network_connect_cb,
+                          self);
+
+        return NM_ACT_STAGE_RETURN_POSTPONE;
+    }
+
+    if (NM_IN_STRSET(mode, NM_SETTING_WIRELESS_MODE_AP, NM_SETTING_WIRELESS_MODE_ADHOC)) {
+        NMSettingWirelessSecurity *s_wireless_sec;
+
+        s_wireless_sec = nm_connection_get_setting_wireless_security(connection);
+        if (s_wireless_sec && !nm_setting_wireless_security_get_psk(s_wireless_sec)) {
+            /* PSK is missing from the settings, have to request it */
+
+            wifi_secrets_cancel(self);
+
+            priv->wifi_secrets_id =
+                nm_act_request_get_secrets(req,
+                                           TRUE,
+                                           NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                                           NM_SECRET_AGENT_GET_SECRETS_FLAG_ALLOW_INTERACTION,
+                                           NM_MAKE_STRV(NM_SETTING_WIRELESS_SECURITY_PSK),
+                                           act_psk_cb,
+                                           self);
+            nm_device_state_changed(device, NM_DEVICE_STATE_NEED_AUTH, NM_DEVICE_STATE_REASON_NONE);
+        } else
+            act_set_mode(self);
+
+        return NM_ACT_STAGE_RETURN_POSTPONE;
+    }
+
+    _LOGW(LOGD_DEVICE | LOGD_WIFI, "Activation: (wifi) iwd cannot handle mode %s", mode);
+    NM_SET_OUT(out_failure_reason, NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
+
+out_fail:
+    cleanup_association_attempt(self, FALSE);
+    return NM_ACT_STAGE_RETURN_FAILURE;
+}
+
+static guint32
+get_configured_mtu(NMDevice *device, NMDeviceMtuSource *out_source, gboolean *out_force)
+{
+    return nm_device_get_configured_mtu_from_connection(device,
+                                                        NM_TYPE_SETTING_WIRELESS,
+                                                        out_source);
+}
+
+static gboolean
+periodic_scan_timeout_cb(gpointer user_data)
+{
+    NMDeviceIwd *       self = user_data;
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+
+    priv->periodic_scan_id = 0;
+
+    if (priv->scanning || priv->scan_requested)
+        return FALSE;
+
+    g_dbus_proxy_call(priv->dbus_station_proxy,
+                      "Scan",
+                      NULL,
+                      G_DBUS_CALL_FLAGS_NONE,
+                      -1,
+                      priv->cancellable,
+                      scan_cb,
+                      self);
+    priv->scan_requested = TRUE;
+
+    return FALSE;
+}
+
+static void
+schedule_periodic_scan(NMDeviceIwd *self, gboolean initial_scan)
+{
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+    guint               interval;
+
+    /* Automatically start a scan after a disconnect, mode change or device UP,
+     * otherwise scan periodically every 10 seconds if needed for NM's
+     * autoconnect.  There's no need to scan When using IWD's autoconnect or
+     * when connected, we update the AP list on UI requests.
+     *
+     * (initial_scan && disconnected && !priv->iwd_autoconnect) override
+     * priv->scanning below because of an IWD quirk where a device will often
+     * be in the autoconnect state and scanning at the time of our initial_scan,
+     * but our logic will then send it a Disconnect() causing IWD to exit
+     * autoconnect and interrupt the ongoing scan, meaning that we still want
+     * a new scan ASAP.
+     */
+    if (!priv->can_scan || priv->scan_requested || priv->current_ap || priv->iwd_autoconnect)
+        interval = -1;
+    else if (initial_scan && priv->scanning)
+        interval = 0;
+    else if (priv->scanning)
+        interval = -1;
+    else if (!priv->periodic_scan_id)
+        interval = 10;
+    else
+        return;
+
+    nm_clear_g_source(&priv->periodic_scan_id);
+
+    if (interval != (guint) -1)
+        priv->periodic_scan_id = g_timeout_add_seconds(interval, periodic_scan_timeout_cb, self);
+}
+
+static void
+set_can_scan(NMDeviceIwd *self, gboolean can_scan)
+{
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+
+    if (priv->can_scan == can_scan)
+        return;
+
+    priv->can_scan = can_scan;
+
+    if (!priv->iwd_autoconnect)
+        schedule_periodic_scan(self, TRUE);
+}
+
+static void
+device_state_changed(NMDevice *          device,
+                     NMDeviceState       new_state,
+                     NMDeviceState       old_state,
+                     NMDeviceStateReason reason)
+{
+    NMDeviceIwd *       self = NM_DEVICE_IWD(device);
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+    NMSettingWireless * s_wireless;
+    const char *        mode;
+
+    switch (new_state) {
+    case NM_DEVICE_STATE_UNMANAGED:
+        break;
+    case NM_DEVICE_STATE_UNAVAILABLE:
+        /*
+         * If the device is enabled and the IWD manager is ready,
+         * transition to DISCONNECTED because the device is now
+         * ready to use.
+         */
+        if (priv->enabled && priv->dbus_station_proxy) {
+            nm_device_queue_recheck_available(device,
+                                              NM_DEVICE_STATE_REASON_SUPPLICANT_AVAILABLE,
+                                              NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
+        }
+        break;
+    case NM_DEVICE_STATE_DISCONNECTED:
+        if (old_state == NM_DEVICE_STATE_UNAVAILABLE)
+            initial_check_assume(self);
+        break;
+    case NM_DEVICE_STATE_IP_CONFIG:
+        s_wireless =
+            (NMSettingWireless *) nm_device_get_applied_setting(device, NM_TYPE_SETTING_WIRELESS);
+        mode = nm_setting_wireless_get_mode(s_wireless);
+        if (!priv->periodic_update_id
+            && NM_IN_STRSET(mode,
+                            NULL,
+                            NM_SETTING_WIRELESS_MODE_INFRA,
+                            NM_SETTING_WIRELESS_MODE_ADHOC)) {
+            priv->periodic_update_id = g_timeout_add_seconds(6, periodic_update_cb, self);
+            periodic_update(self);
+        }
+        break;
+    default:
+        break;
+    }
+}
+
+static gboolean
+get_enabled(NMDevice *device)
+{
+    return NM_DEVICE_IWD_GET_PRIVATE(device)->enabled;
+}
+
+static void
+set_enabled(NMDevice *device, gboolean enabled)
+{
+    NMDeviceIwd *       self = NM_DEVICE_IWD(device);
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+    NMDeviceState       state;
+
+    enabled = !!enabled;
+
+    if (priv->enabled == enabled)
+        return;
+
+    priv->enabled = enabled;
+
+    _LOGD(LOGD_WIFI, "device now %s", enabled ? "enabled" : "disabled");
+
+    state = nm_device_get_state(device);
+    if (state < NM_DEVICE_STATE_UNAVAILABLE) {
+        _LOGD(LOGD_WIFI, "(%s): device blocked by UNMANAGED state", enabled ? "enable" : "disable");
+        return;
+    }
+
+    if (priv->dbus_obj)
+        set_powered(self, enabled);
+
+    if (enabled) {
+        if (state != NM_DEVICE_STATE_UNAVAILABLE)
+            _LOGW(LOGD_CORE, "not in expected unavailable state!");
+
+        if (priv->dbus_station_proxy) {
+            nm_device_queue_recheck_available(device,
+                                              NM_DEVICE_STATE_REASON_SUPPLICANT_AVAILABLE,
+                                              NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
+        }
+    } else {
+        nm_device_state_changed(device, NM_DEVICE_STATE_UNAVAILABLE, NM_DEVICE_STATE_REASON_NONE);
+    }
+}
+
+static gboolean
+can_reapply_change(NMDevice *  device,
+                   const char *setting_name,
+                   NMSetting * s_old,
+                   NMSetting * s_new,
+                   GHashTable *diffs,
+                   GError **   error)
+{
+    NMDeviceClass *device_class;
+
+    /* Only handle wireless setting here, delegate other settings to parent class */
+    if (nm_streq(setting_name, NM_SETTING_WIRELESS_SETTING_NAME)) {
+        return nm_device_hash_check_invalid_keys(
+            diffs,
+            NM_SETTING_WIRELESS_SETTING_NAME,
+            error,
+            NM_SETTING_WIRELESS_SEEN_BSSIDS, /* ignored */
+            NM_SETTING_WIRELESS_MTU);        /* reapplied with IP config */
+    }
+
+    device_class = NM_DEVICE_CLASS(nm_device_iwd_parent_class);
+    return device_class->can_reapply_change(device, setting_name, s_old, s_new, diffs, error);
+}
+
+/*****************************************************************************/
+
+static void
+get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec)
+{
+    NMDeviceIwd *       self = NM_DEVICE_IWD(object);
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+    const char **       list;
+
+    switch (prop_id) {
+    case PROP_MODE:
+        if (!priv->current_ap)
+            g_value_set_uint(value, NM_802_11_MODE_UNKNOWN);
+        else if (nm_wifi_ap_is_hotspot(priv->current_ap))
+            g_value_set_uint(value, NM_802_11_MODE_AP);
+        else
+            g_value_set_uint(value, nm_wifi_ap_get_mode(priv->current_ap));
+
+        break;
+    case PROP_BITRATE:
+        g_value_set_uint(value, priv->rate);
+        break;
+    case PROP_CAPABILITIES:
+        g_value_set_uint(value, priv->capabilities);
+        break;
+    case PROP_ACCESS_POINTS:
+        list = nm_wifi_aps_get_paths(&priv->aps_lst_head, TRUE);
+        g_value_take_boxed(value, nm_utils_strv_make_deep_copied(list));
+        break;
+    case PROP_ACTIVE_ACCESS_POINT:
+        nm_dbus_utils_g_value_set_object_path(value, priv->current_ap);
+        break;
+    case PROP_SCANNING:
+        g_value_set_boolean(value, priv->scanning);
+        break;
+    case PROP_LAST_SCAN:
+        g_value_set_int64(
+            value,
+            priv->last_scan > 0
+                ? nm_utils_monotonic_timestamp_as_boottime(priv->last_scan, NM_UTILS_NSEC_PER_MSEC)
+                : (gint64) -1);
+        break;
+    default:
+        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
+        break;
+    }
+}
+
+/*****************************************************************************/
+
+static void
+state_changed(NMDeviceIwd *self, const char *new_state)
+{
+    NMDeviceIwdPrivate *priv           = NM_DEVICE_IWD_GET_PRIVATE(self);
+    NMDevice *          device         = NM_DEVICE(self);
+    NMDeviceState       dev_state      = nm_device_get_state(device);
+    gboolean            nm_connection  = priv->current_ap || priv->assumed_ac;
+    gboolean            iwd_connection = FALSE;
+    NMWifiAP *          ap             = NULL;
+    gboolean            can_connect    = priv->nm_autoconnect;
+
+    _LOGI(LOGD_DEVICE | LOGD_WIFI, "new IWD device state is %s", new_state);
+
+    if (NM_IN_STRSET(new_state, "connecting", "connected", "roaming")) {
+        gs_unref_variant GVariant *value = NULL;
+        const char *               network_path_str;
+        nm_auto_ref_string NMRefString *network_path = NULL;
+
+        value = g_dbus_proxy_get_cached_property(priv->dbus_station_proxy, "ConnectedNetwork");
+        if (!value || !g_variant_is_of_type(value, G_VARIANT_TYPE_OBJECT_PATH)) {
+            _LOGW(LOGD_DEVICE | LOGD_WIFI,
+                  "ConnectedNetwork property not cached or not an object path");
+            return;
+        }
+
+        iwd_connection   = TRUE;
+        network_path_str = g_variant_get_string(value, NULL);
+        network_path     = nm_ref_string_new(network_path_str);
+        ap               = find_ap_by_supplicant_path(self, network_path);
+
+        if (!ap) {
+            _LOGW(LOGD_DEVICE | LOGD_WIFI,
+                  "ConnectedNetwork points to an unknown Network %s",
+                  network_path_str);
+            return;
+        }
+    }
+
+    /* Don't allow scanning while connecting, disconnecting or roaming */
+    set_can_scan(self, NM_IN_STRSET(new_state, "connected", "disconnected"));
+
+    priv->nm_autoconnect = FALSE;
+
+    if (nm_connection && iwd_connection && priv->current_ap && ap != priv->current_ap) {
+        gboolean switch_ap = priv->iwd_autoconnect && priv->assumed_ac;
+
+        _LOGW(LOGD_DEVICE | LOGD_WIFI,
+              "IWD is connecting to the wrong AP, %s activation",
+              switch_ap ? "replacing" : "aborting");
+        cleanup_association_attempt(self, !switch_ap);
+        nm_device_state_changed(device,
+                                NM_DEVICE_STATE_FAILED,
+                                NM_DEVICE_STATE_REASON_SUPPLICANT_DISCONNECT);
+
+        if (switch_ap)
+            assume_connection(self, ap);
+        return;
+    }
+
+    if (priv->iwd_autoconnect && iwd_connection) {
+        if (dev_state < NM_DEVICE_STATE_DISCONNECTED)
+            return;
+
+        /* If IWD is in any state other than disconnected and the NMDevice is
+         * in DISCONNECTED then someone else, possibly IWD's autoconnect, has
+         * commanded an action and we need to update our NMDevice's state to
+         * match, including finding the NMSettingsConnection and NMWifiAP
+         * matching the network pointed to by Station.ConnectedNetwork.
+         *
+         * If IWD is in the connected state and we're in CONFIG, we only have
+         * to signal that the existing connection request has advanced to a new
+         * state.  If the connection request came from NM, we must have used
+         * Network.Connect() so that method call's callback will update the
+         * connection request, otherwise we do it here.
+         *
+         * If IWD is disconnecting or just disconnected, the common code below
+         * (independent from priv->iwd_autoconnect) will handle this case.
+         * If IWD is disconnecting but we never saw a connection request in the
+         * first place (maybe because we're only startig up) we won't be
+         * setting up an NMActiveConnection just to put the NMDevice in the
+         * DEACTIVATING state and we ignore this case.
+         *
+         * If IWD was in the disconnected state and transitioned to
+         * "connecting" but we were already in NEED_AUTH because we handled an
+         * agent query -- IWD normally stays in "disconnected" until it has all
+         * the secrets -- we record this fact and remain in NEED_AUTH.
+         */
+        if (!nm_connection) {
+            _LOGD(LOGD_DEVICE | LOGD_WIFI, "This is a new connection, 'assuming' it");
+            assume_connection(self, ap);
+            return;
+        }
+
+        if (priv->assumed_ac && dev_state >= NM_DEVICE_STATE_PREPARE
+            && dev_state < NM_DEVICE_STATE_IP_CONFIG
+            && NM_IN_STRSET(new_state, "connected", "roaming")) {
+            _LOGD(LOGD_DEVICE | LOGD_WIFI, "Updating assumed activation state");
+            assumed_connection_progress_to_ip_config(self, TRUE);
+            return;
+        }
+
+        if (priv->assumed_ac) {
+            _LOGD(LOGD_DEVICE | LOGD_WIFI, "Clearing assumed activation timeout");
+            nm_clear_g_source(&priv->assumed_ac_timeout);
+            return;
+        }
+    } else if (!priv->iwd_autoconnect && iwd_connection) {
+        /* If we were connecting, do nothing, the confirmation of
+         * a connection success is handled in the Device.Connect
+         * method return callback.  Otherwise, IWD must have connected
+         * without Network Manager's will so for simplicity force a
+         * disconnect.
+         */
+        if (nm_connection)
+            return;
+
+        _LOGW(LOGD_DEVICE | LOGD_WIFI, "Unsolicited connection, asking IWD to disconnect");
+        send_disconnect(self);
+    } else if (NM_IN_STRSET(new_state, "disconnecting", "disconnected")) {
+        /* If necessary, call Disconnect on the IWD device object to make sure
+         * it disables its autoconnect.
+         */
+        if ((!priv->iwd_autoconnect
+             || nm_device_autoconnect_blocked_get(device, NM_DEVICE_AUTOCONNECT_BLOCKED_ALL))
+            && !priv->wifi_secrets_id && !priv->pending_agent_request)
+            send_disconnect(self);
+
+        /*
+         * If IWD is still handling the Connect call, let our Connect
+         * callback for the dbus method handle the failure.  The main
+         * reason we don't want to handle the failure here is because the
+         * method callback will have more information on the specific
+         * failure reason.
+         *
+         * If IWD is handling an autoconnect agent call, let the agent's
+         * Cancel() handler take care of this.
+         */
+        if (NM_IN_SET(dev_state, NM_DEVICE_STATE_CONFIG, NM_DEVICE_STATE_NEED_AUTH)
+            && !priv->assumed_ac)
+            return;
+        if (NM_IN_SET(dev_state, NM_DEVICE_STATE_NEED_AUTH) && priv->assumed_ac)
+            return;
+
+        if (nm_connection) {
+            cleanup_association_attempt(self, FALSE);
+            nm_device_state_changed(device,
+                                    NM_DEVICE_STATE_FAILED,
+                                    NM_DEVICE_STATE_REASON_SUPPLICANT_DISCONNECT);
+        }
+    } else if (!nm_streq(new_state, "unknown")) {
+        _LOGE(LOGD_WIFI, "State %s unknown", new_state);
+        return;
+    }
+
+    /* Don't allow new connection until iwd exits disconnecting and no
+     * Connect callback is pending.
+     */
+    if (!priv->iwd_autoconnect && NM_IN_STRSET(new_state, "disconnected")) {
+        priv->nm_autoconnect = TRUE;
+        if (!can_connect)
+            nm_device_emit_recheck_auto_activate(device);
+    }
+}
+
+static void
+scanning_changed(NMDeviceIwd *self, gboolean new_scanning)
+{
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+
+    if (new_scanning == priv->scanning)
+        return;
+
+    priv->scanning = new_scanning;
+
+    _notify(self, PROP_SCANNING);
+
+    if (!priv->scanning) {
+        update_aps(self);
+
+        if (!priv->scan_requested && !priv->iwd_autoconnect)
+            schedule_periodic_scan(self, FALSE);
+    }
+}
+
+static void
+station_properties_changed(GDBusProxy *proxy,
+                           GVariant *  changed_properties,
+                           GStrv       invalidate_properties,
+                           gpointer    user_data)
+{
+    NMDeviceIwd *self = user_data;
+    const char * new_str;
+    gboolean     new_bool;
+
+    if (g_variant_lookup(changed_properties, "State", "&s", &new_str))
+        state_changed(self, new_str);
+
+    if (g_variant_lookup(changed_properties, "Scanning", "b", &new_bool))
+        scanning_changed(self, new_bool);
+}
+
+static void
+ap_adhoc_properties_changed(GDBusProxy *proxy,
+                            GVariant *  changed_properties,
+                            GStrv       invalidate_properties,
+                            gpointer    user_data)
+{
+    NMDeviceIwd *self = user_data;
+    gboolean     new_bool;
+
+    if (g_variant_lookup(changed_properties, "Started", "b", &new_bool))
+        _LOGI(LOGD_DEVICE | LOGD_WIFI,
+              "IWD AP/AdHoc state is now %s",
+              new_bool ? "Started" : "Stopped");
+}
+
+static void
+powered_changed(NMDeviceIwd *self, gboolean new_powered)
+{
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+    GDBusInterface *    interface;
+
+    nm_device_queue_recheck_available(NM_DEVICE(self),
+                                      NM_DEVICE_STATE_REASON_SUPPLICANT_AVAILABLE,
+                                      NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
+
+    interface =
+        new_powered ? g_dbus_object_get_interface(priv->dbus_obj, NM_IWD_AP_INTERFACE) : NULL;
+
+    if (priv->dbus_ap_proxy) {
+        g_signal_handlers_disconnect_by_func(priv->dbus_ap_proxy,
+                                             ap_adhoc_properties_changed,
+                                             self);
+        g_clear_object(&priv->dbus_ap_proxy);
+    }
+
+    if (interface) {
+        priv->dbus_ap_proxy = G_DBUS_PROXY(interface);
+        g_signal_connect(priv->dbus_ap_proxy,
+                         "g-properties-changed",
+                         G_CALLBACK(ap_adhoc_properties_changed),
+                         self);
+
+        if (priv->act_mode_switch)
+            act_check_interface(self);
+        else
+            reset_mode(self, NULL, NULL, NULL);
+    }
+
+    interface =
+        new_powered ? g_dbus_object_get_interface(priv->dbus_obj, NM_IWD_ADHOC_INTERFACE) : NULL;
+
+    if (priv->dbus_adhoc_proxy) {
+        g_signal_handlers_disconnect_by_func(priv->dbus_adhoc_proxy,
+                                             ap_adhoc_properties_changed,
+                                             self);
+        g_clear_object(&priv->dbus_adhoc_proxy);
+    }
+
+    if (interface) {
+        priv->dbus_adhoc_proxy = G_DBUS_PROXY(interface);
+        g_signal_connect(priv->dbus_adhoc_proxy,
+                         "g-properties-changed",
+                         G_CALLBACK(ap_adhoc_properties_changed),
+                         self);
+
+        if (priv->act_mode_switch)
+            act_check_interface(self);
+        else
+            reset_mode(self, NULL, NULL, NULL);
+    }
+
+    /* We expect one of the three interfaces to always be present when
+     * device is Powered so if AP and AdHoc are not present we should
+     * be in station mode.
+     */
+    if (new_powered && !priv->dbus_ap_proxy && !priv->dbus_adhoc_proxy) {
+        interface = g_dbus_object_get_interface(priv->dbus_obj, NM_IWD_STATION_INTERFACE);
+        if (!interface) {
+            _LOGE(LOGD_WIFI,
+                  "Interface %s not found on obj %s",
+                  NM_IWD_STATION_INTERFACE,
+                  g_dbus_object_get_object_path(priv->dbus_obj));
+            interface = NULL;
+        }
+    } else
+        interface = NULL;
+
+    if (priv->dbus_station_proxy) {
+        g_signal_handlers_disconnect_by_func(priv->dbus_station_proxy,
+                                             station_properties_changed,
+                                             self);
+        g_clear_object(&priv->dbus_station_proxy);
+    }
+
+    if (interface) {
+        GVariant *value;
+
+        priv->dbus_station_proxy = G_DBUS_PROXY(interface);
+        g_signal_connect(priv->dbus_station_proxy,
+                         "g-properties-changed",
+                         G_CALLBACK(station_properties_changed),
+                         self);
+
+        value          = g_dbus_proxy_get_cached_property(priv->dbus_station_proxy, "Scanning");
+        priv->scanning = get_variant_boolean(value, "Scanning");
+        g_variant_unref(value);
+
+        value = g_dbus_proxy_get_cached_property(priv->dbus_station_proxy, "State");
+        state_changed(self, get_variant_state(value));
+        g_variant_unref(value);
+
+        update_aps(self);
+
+        /* When a device is brought UP in station mode, including after a mode
+         * switch, IWD re-enables autoconnect.  This is unlike NM's autoconnect
+         * where a mode change doesn't interfere with the
+         * BLOCKED_MANUAL_DISCONNECT flag.
+         */
+        if (priv->iwd_autoconnect) {
+            nm_device_autoconnect_blocked_unset(NM_DEVICE(self),
+                                                NM_DEVICE_AUTOCONNECT_BLOCKED_INTERNAL);
+        }
+    } else {
+        set_can_scan(self, FALSE);
+        priv->scanning       = FALSE;
+        priv->scan_requested = FALSE;
+        priv->nm_autoconnect = FALSE;
+        cleanup_association_attempt(self, FALSE);
+        remove_all_aps(self);
+    }
+}
+
+static void
+device_properties_changed(GDBusProxy *proxy,
+                          GVariant *  changed_properties,
+                          GStrv       invalidate_properties,
+                          gpointer    user_data)
+{
+    NMDeviceIwd *self = user_data;
+    gboolean     new_bool;
+
+    if (g_variant_lookup(changed_properties, "Powered", "b", &new_bool))
+        powered_changed(self, new_bool);
+}
+
+static void
+config_changed(NMConfig *          config,
+               NMConfigData *      config_data,
+               NMConfigChangeFlags changes,
+               NMConfigData *      old_data,
+               NMDeviceIwd *       self)
+{
+    NMDeviceIwdPrivate *priv       = NM_DEVICE_IWD_GET_PRIVATE(self);
+    gboolean            old_iwd_ac = priv->iwd_autoconnect;
+
+    priv->iwd_autoconnect =
+        nm_config_data_get_device_config_boolean(config_data,
+                                                 NM_CONFIG_KEYFILE_KEY_DEVICE_WIFI_IWD_AUTOCONNECT,
+                                                 NM_DEVICE(self),
+                                                 TRUE,
+                                                 TRUE);
+
+    if (old_iwd_ac != priv->iwd_autoconnect && priv->dbus_station_proxy && !priv->current_ap) {
+        gs_unref_variant GVariant *value = NULL;
+
+        if (!priv->iwd_autoconnect
+            && !nm_device_autoconnect_blocked_get(NM_DEVICE(self),
+                                                  NM_DEVICE_AUTOCONNECT_BLOCKED_ALL))
+            send_disconnect(self);
+
+        value = g_dbus_proxy_get_cached_property(priv->dbus_station_proxy, "State");
+        state_changed(self, get_variant_state(value));
+    }
+}
+
+void
+nm_device_iwd_set_dbus_object(NMDeviceIwd *self, GDBusObject *object)
+{
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+    GDBusInterface *    interface;
+    gs_unref_variant GVariant *value          = NULL;
+    gs_unref_object GDBusProxy *adapter_proxy = NULL;
+    GVariantIter *              iter;
+    const char *                mode;
+    gboolean                    powered;
+    NMDeviceWifiCapabilities    capabilities;
+
+    if (!nm_g_object_ref_set(&priv->dbus_obj, object))
+        return;
+
+    if (priv->dbus_device_proxy) {
+        g_signal_handlers_disconnect_by_func(priv->dbus_device_proxy,
+                                             device_properties_changed,
+                                             self);
+        g_clear_object(&priv->dbus_device_proxy);
+
+        powered_changed(self, FALSE);
+
+        priv->act_mode_switch = FALSE;
+
+        g_signal_handlers_disconnect_by_func(nm_config_get(), config_changed, self);
+    }
+
+    if (!object)
+        return;
+
+    interface = g_dbus_object_get_interface(object, NM_IWD_DEVICE_INTERFACE);
+    if (!interface) {
+        _LOGE(LOGD_WIFI,
+              "Interface %s not found on obj %s",
+              NM_IWD_DEVICE_INTERFACE,
+              g_dbus_object_get_object_path(object));
+        g_clear_object(&priv->dbus_obj);
+        return;
+    }
+
+    priv->dbus_device_proxy = G_DBUS_PROXY(interface);
+
+    g_signal_connect(priv->dbus_device_proxy,
+                     "g-properties-changed",
+                     G_CALLBACK(device_properties_changed),
+                     self);
+
+    /* Parse list of interface modes supported by adapter (wiphy) */
+
+    value = g_dbus_proxy_get_cached_property(priv->dbus_device_proxy, "Adapter");
+    if (!value || !g_variant_is_of_type(value, G_VARIANT_TYPE_OBJECT_PATH)) {
+        nm_log_warn(LOGD_DEVICE | LOGD_WIFI, "Adapter property not cached or not an object path");
+        goto error;
+    }
+
+    adapter_proxy = nm_iwd_manager_get_dbus_interface(nm_iwd_manager_get(),
+                                                      g_variant_get_string(value, NULL),
+                                                      NM_IWD_WIPHY_INTERFACE);
+    if (!adapter_proxy) {
+        nm_log_warn(LOGD_DEVICE | LOGD_WIFI, "Can't get DBus proxy for IWD Adapter for IWD Device");
+        goto error;
+    }
+
+    g_variant_unref(value);
+    value = g_dbus_proxy_get_cached_property(adapter_proxy, "SupportedModes");
+    if (!value || !g_variant_is_of_type(value, G_VARIANT_TYPE_STRING_ARRAY)) {
+        nm_log_warn(LOGD_DEVICE | LOGD_WIFI,
+                    "SupportedModes property not cached or not a string array");
+        goto error;
+    }
+
+    capabilities = NM_WIFI_DEVICE_CAP_CIPHER_CCMP | NM_WIFI_DEVICE_CAP_RSN;
+
+    g_variant_get(value, "as", &iter);
+    while (g_variant_iter_next(iter, "&s", &mode)) {
+        if (nm_streq(mode, "ap"))
+            capabilities |= NM_WIFI_DEVICE_CAP_AP;
+        else if (nm_streq(mode, "ad-hoc"))
+            capabilities |= NM_WIFI_DEVICE_CAP_ADHOC;
+    }
+    g_variant_iter_free(iter);
+
+    if (priv->capabilities != capabilities) {
+        priv->capabilities = capabilities;
+        _notify(self, PROP_CAPABILITIES);
+    }
+
+    /* Update iwd_autoconnect before any state_changed call */
+    g_signal_connect(nm_config_get(),
+                     NM_CONFIG_SIGNAL_CONFIG_CHANGED,
+                     G_CALLBACK(config_changed),
+                     self);
+    config_changed(NULL, NM_CONFIG_GET_DATA, 0, NULL, self);
+
+    g_variant_unref(value);
+    value   = g_dbus_proxy_get_cached_property(priv->dbus_device_proxy, "Powered");
+    powered = get_variant_boolean(value, "Powered");
+
+    if (powered != priv->enabled)
+        set_powered(self, priv->enabled);
+    else if (powered)
+        powered_changed(self, TRUE);
+
+    return;
+
+error:
+    g_signal_handlers_disconnect_by_func(priv->dbus_device_proxy, device_properties_changed, self);
+    g_clear_object(&priv->dbus_device_proxy);
+}
+
+gboolean
+nm_device_iwd_agent_query(NMDeviceIwd *self, GDBusMethodInvocation *invocation)
+{
+    NMDevice *                   device = NM_DEVICE(self);
+    NMDeviceIwdPrivate *         priv   = NM_DEVICE_IWD_GET_PRIVATE(self);
+    NMDeviceState                state  = nm_device_get_state(device);
+    const char *                 setting_name;
+    const char *                 setting_key;
+    gboolean                     replied;
+    NMWifiAP *                   ap;
+    NMSecretAgentGetSecretsFlags get_secret_flags =
+        NM_SECRET_AGENT_GET_SECRETS_FLAG_ALLOW_INTERACTION;
+    nm_auto_ref_string NMRefString *network_path = NULL;
+
+    if (!invocation) {
+        gs_unref_variant GVariant *value =
+            g_dbus_proxy_get_cached_property(priv->dbus_station_proxy, "State");
+        gboolean disconnect;
+
+        if (!priv->wifi_secrets_id && !priv->pending_agent_request)
+            return FALSE;
+
+        _LOGI(LOGD_WIFI, "IWD agent request is being cancelled");
+        wifi_secrets_cancel(self);
+
+        if (state == NM_DEVICE_STATE_NEED_AUTH)
+            nm_device_state_changed(device, NM_DEVICE_STATE_CONFIG, NM_DEVICE_STATE_REASON_NONE);
+
+        /* The secrets request is being cancelled.  If we don't have an assumed
+         * connection than we've probably called Network.Connect and that method
+         * call's callback is going to handle the failure.  And if the state was
+         * not "disconnected" then let the state change handler process the
+         * failure.
+         */
+        if (!priv->assumed_ac)
+            return TRUE;
+
+        if (!nm_streq(get_variant_state(value), "disconnected"))
+            return TRUE;
+
+        disconnect = nm_device_autoconnect_blocked_get(device, NM_DEVICE_AUTOCONNECT_BLOCKED_ALL);
+        cleanup_association_attempt(self, disconnect);
+        nm_device_state_changed(device,
+                                NM_DEVICE_STATE_FAILED,
+                                NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
+        return TRUE;
+    }
+
+    if (state > NM_DEVICE_STATE_CONFIG && state < NM_DEVICE_STATE_DEACTIVATING) {
+        _LOGW(LOGD_WIFI, "Can't handle the IWD agent request in current device state");
+        return FALSE;
+    }
+
+    if (priv->wifi_secrets_id || priv->pending_agent_request) {
+        _LOGW(LOGD_WIFI, "There's already a pending agent request for this device");
+        return FALSE;
+    }
+
+    network_path = nm_ref_string_new(get_agent_request_network_path(invocation));
+    ap           = find_ap_by_supplicant_path(self, network_path);
+    if (!ap) {
+        _LOGW(LOGD_WIFI, "IWD Network object not found for the agent request");
+        return FALSE;
+    }
+
+    if (priv->assumed_ac) {
+        const char *ac_ap_path = nm_active_connection_get_specific_object(priv->assumed_ac);
+
+        if (!nm_streq(ac_ap_path, nm_dbus_object_get_path(NM_DBUS_OBJECT(ap)))) {
+            _LOGW(LOGD_WIFI,
+                  "Dropping an existing assumed connection to create a new one based on the IWD "
+                  "agent request network parameter");
+
+            if (priv->current_ap)
+                nm_device_state_changed(device,
+                                        NM_DEVICE_STATE_FAILED,
+                                        NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
+
+            cleanup_association_attempt(self, FALSE);
+            priv->pending_agent_request = g_object_ref(invocation);
+            assume_connection(self, ap);
+            return TRUE;
+        }
+
+        if (state != NM_DEVICE_STATE_CONFIG) {
+            _LOGI(LOGD_WIFI, "IWD agent request deferred until in CONFIG");
+            priv->pending_agent_request = g_object_ref(invocation);
+            return TRUE;
+        }
+
+        /* Otherwise handle as usual */
+    } else if (!priv->current_ap) {
+        _LOGI(LOGD_WIFI, "IWD is asking for secrets without explicit connect request");
+
+        if (priv->iwd_autoconnect) {
+            priv->pending_agent_request = g_object_ref(invocation);
+            assume_connection(self, ap);
+            return TRUE;
+        }
+
+        send_disconnect(self);
+        return FALSE;
+    } else if (priv->current_ap) {
+        if (priv->current_ap != ap) {
+            _LOGW(LOGD_WIFI, "IWD agent request for a wrong network object");
+            cleanup_association_attempt(self, TRUE);
+            nm_device_state_changed(device,
+                                    NM_DEVICE_STATE_FAILED,
+                                    NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
+            return FALSE;
+        }
+
+        /* Otherwise handle as usual */
+    }
+
+    if (!try_reply_agent_request(self,
+                                 nm_device_get_applied_connection(device),
+                                 invocation,
+                                 &setting_name,
+                                 &setting_key,
+                                 &replied)) {
+        priv->secrets_failed = TRUE;
+        return FALSE;
+    }
+
+    if (replied)
+        return TRUE;
+
+    /* Normally require new secrets every time IWD asks for them.
+     * IWD only queries us if it has not saved the secrets (e.g. by policy)
+     * or a previous attempt has failed with current secrets so it wants
+     * a fresh set.  However if this is a new connection it may include
+     * all of the needed settings already so allow using these, too.
+     * Connection timestamp is set after activation or after first
+     * activation failure (to 0).
+     */
+    if (nm_settings_connection_get_timestamp(nm_device_get_settings_connection(device), NULL))
+        get_secret_flags |= NM_SECRET_AGENT_GET_SECRETS_FLAG_REQUEST_NEW;
+
+    nm_device_state_changed(device, NM_DEVICE_STATE_NEED_AUTH, NM_DEVICE_STATE_REASON_NO_SECRETS);
+    wifi_secrets_get_one(self, setting_name, get_secret_flags, setting_key, invocation);
+
+    return TRUE;
+}
+
+void
+nm_device_iwd_network_add_remove(NMDeviceIwd *self, GDBusProxy *network, bool add)
+{
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+    NMWifiAP *          ap   = NULL;
+    bool                recheck;
+    nm_auto_ref_string NMRefString *bss_path = NULL;
+
+    bss_path = nm_ref_string_new(g_dbus_proxy_get_object_path(network));
+    ap       = find_ap_by_supplicant_path(self, bss_path);
+
+    /* We could schedule an update_aps(self) idle call here but up to IWD 1.9
+     * when a hidden network connection is attempted, that network is initially
+     * only added as a Network object but not shown in GetOrderedNetworks()
+     * return values, and for some corner case scenarios it's beneficial to
+     * have that Network reflected in our ap list so that we don't attempt
+     * calling ConnectHiddenNetwork() on it, as that will fail in 1.9.  But we
+     * can skip recheck-available if we're currently scanning or in the middle
+     * of a GetOrderedNetworks() call as that will trigger the recheck too.
+     */
+    recheck = priv->enabled && !priv->scanning && !priv->networks_requested;
+
+    if (!add) {
+        if (ap) {
+            ap_add_remove(self, FALSE, ap, recheck);
+            priv->networks_changed |= !recheck;
+        }
+
+        return;
+    }
+
+    if (!ap) {
+        ap = ap_from_network(self,
+                             network,
+                             bss_path,
+                             nm_utils_get_monotonic_timestamp_msec(),
+                             -10000);
+        if (!ap)
+            return;
+
+        ap_add_remove(self, TRUE, ap, recheck);
+        g_object_unref(ap);
+        priv->networks_changed |= !recheck;
+        return;
+    }
+}
+
+static void
+autoconnect_changed(NMDevice *device, GParamSpec *pspec, NMDeviceIwd *self)
+{
+    NMDeviceIwdPrivate *priv         = NM_DEVICE_IWD_GET_PRIVATE(self);
+    gs_unref_variant GVariant *value = NULL;
+
+    /* Note IWD normally remains in "disconnected" during a secret request
+     * and we don't want to interrupt it by calling Station.Disconnect().
+     */
+    if (!priv->dbus_station_proxy || !priv->iwd_autoconnect
+        || !nm_device_autoconnect_blocked_get(device, NM_DEVICE_AUTOCONNECT_BLOCKED_ALL)
+        || priv->wifi_secrets_id || priv->pending_agent_request)
+        return;
+
+    value = g_dbus_proxy_get_cached_property(priv->dbus_station_proxy, "State");
+    if (!nm_streq(get_variant_state(value), "disconnected"))
+        return;
+
+    send_disconnect(self);
+}
+
+/*****************************************************************************/
+
+static const char *
+get_type_description(NMDevice *device)
+{
+    nm_assert(NM_IS_DEVICE_IWD(device));
+
+    return "wifi";
+}
+
+/*****************************************************************************/
+
+static void
+nm_device_iwd_init(NMDeviceIwd *self)
+{
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+
+    c_list_init(&priv->aps_lst_head);
+
+    g_signal_connect(self, "notify::" NM_DEVICE_AUTOCONNECT, G_CALLBACK(autoconnect_changed), self);
+
+    /* Make sure the manager is running */
+    (void) nm_iwd_manager_get();
+}
+
+NMDevice *
+nm_device_iwd_new(const char *iface)
+{
+    return g_object_new(NM_TYPE_DEVICE_IWD,
+                        NM_DEVICE_IFACE,
+                        iface,
+                        NM_DEVICE_TYPE_DESC,
+                        "802.11 Wi-Fi",
+                        NM_DEVICE_DEVICE_TYPE,
+                        NM_DEVICE_TYPE_WIFI,
+                        NM_DEVICE_LINK_TYPE,
+                        NM_LINK_TYPE_WIFI,
+                        NM_DEVICE_RFKILL_TYPE,
+                        RFKILL_TYPE_WLAN,
+                        NULL);
+}
+
+static void
+dispose(GObject *object)
+{
+    NMDeviceIwd *       self = NM_DEVICE_IWD(object);
+    NMDeviceIwdPrivate *priv = NM_DEVICE_IWD_GET_PRIVATE(self);
+
+    nm_clear_g_cancellable(&priv->cancellable);
+
+    g_signal_handlers_disconnect_by_func(self, autoconnect_changed, self);
+    nm_device_iwd_set_dbus_object(self, NULL);
+
+    G_OBJECT_CLASS(nm_device_iwd_parent_class)->dispose(object);
+
+    nm_assert(c_list_is_empty(&priv->aps_lst_head));
+}
+
+static void
+nm_device_iwd_class_init(NMDeviceIwdClass *klass)
+{
+    GObjectClass *     object_class      = G_OBJECT_CLASS(klass);
+    NMDBusObjectClass *dbus_object_class = NM_DBUS_OBJECT_CLASS(klass);
+    NMDeviceClass *    device_class      = NM_DEVICE_CLASS(klass);
+
+    object_class->get_property = get_property;
+    object_class->dispose      = dispose;
+
+    dbus_object_class->interface_infos =
+        NM_DBUS_INTERFACE_INFOS(&nm_interface_info_device_wireless);
+
+    device_class->connection_type_supported        = NM_SETTING_WIRELESS_SETTING_NAME;
+    device_class->connection_type_check_compatible = NM_SETTING_WIRELESS_SETTING_NAME;
+    device_class->link_types                       = NM_DEVICE_DEFINE_LINK_TYPES(NM_LINK_TYPE_WIFI);
+
+    device_class->can_auto_connect            = can_auto_connect;
+    device_class->is_available                = is_available;
+    device_class->get_autoconnect_allowed     = get_autoconnect_allowed;
+    device_class->check_connection_compatible = check_connection_compatible;
+    device_class->check_connection_available  = check_connection_available;
+    device_class->complete_connection         = complete_connection;
+    device_class->get_enabled                 = get_enabled;
+    device_class->set_enabled                 = set_enabled;
+    device_class->get_type_description        = get_type_description;
+
+    device_class->act_stage1_prepare = act_stage1_prepare;
+    device_class->act_stage2_config  = act_stage2_config;
+    device_class->get_configured_mtu = get_configured_mtu;
+    device_class->deactivate         = deactivate;
+    device_class->deactivate_async   = deactivate_async;
+    device_class->can_reapply_change = can_reapply_change;
+
+    /* Stage 1 needed only for the set_current_ap() call.  Stage 2 is
+     * needed if we're assuming a connection still in the "connecting"
+     * state or on an agent request.
+     */
+    device_class->act_stage1_prepare_also_for_external_or_assume = TRUE;
+    device_class->act_stage2_config_also_for_external_or_assume  = TRUE;
+
+    device_class->state_changed = device_state_changed;
+
+    obj_properties[PROP_MODE] = g_param_spec_uint(NM_DEVICE_IWD_MODE,
+                                                  "",
+                                                  "",
+                                                  NM_802_11_MODE_UNKNOWN,
+                                                  NM_802_11_MODE_AP,
+                                                  NM_802_11_MODE_INFRA,
+                                                  G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_BITRATE] = g_param_spec_uint(NM_DEVICE_IWD_BITRATE,
+                                                     "",
+                                                     "",
+                                                     0,
+                                                     G_MAXUINT32,
+                                                     0,
+                                                     G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_ACCESS_POINTS] =
+        g_param_spec_boxed(NM_DEVICE_IWD_ACCESS_POINTS,
+                           "",
+                           "",
+                           G_TYPE_STRV,
+                           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_ACTIVE_ACCESS_POINT] =
+        g_param_spec_string(NM_DEVICE_IWD_ACTIVE_ACCESS_POINT,
+                            "",
+                            "",
+                            NULL,
+                            G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_CAPABILITIES] =
+        g_param_spec_uint(NM_DEVICE_IWD_CAPABILITIES,
+                          "",
+                          "",
+                          0,
+                          G_MAXUINT32,
+                          NM_WIFI_DEVICE_CAP_NONE,
+                          G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_SCANNING] = g_param_spec_boolean(NM_DEVICE_IWD_SCANNING,
+                                                         "",
+                                                         "",
+                                                         FALSE,
+                                                         G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_LAST_SCAN] = g_param_spec_int64(NM_DEVICE_IWD_LAST_SCAN,
+                                                        "",
+                                                        "",
+                                                        -1,
+                                                        G_MAXINT64,
+                                                        -1,
+                                                        G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    g_object_class_install_properties(object_class, _PROPERTY_ENUMS_LAST, obj_properties);
+}
diff --git a/src/core/devices/wifi/nm-device-iwd.h b/src/core/devices/wifi/nm-device-iwd.h
new file mode 100644
index 00000000..ce94c9ea
--- /dev/null
+++ b/src/core/devices/wifi/nm-device-iwd.h
@@ -0,0 +1,49 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+/*
+ * Copyright (C) 2017 Intel Corporation
+ */
+
+#ifndef __NETWORKMANAGER_DEVICE_IWD_H__
+#define __NETWORKMANAGER_DEVICE_IWD_H__
+
+#include "devices/nm-device.h"
+#include "nm-wifi-ap.h"
+#include "nm-device-wifi.h"
+
+#define NM_TYPE_DEVICE_IWD (nm_device_iwd_get_type())
+#define NM_DEVICE_IWD(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), NM_TYPE_DEVICE_IWD, NMDeviceIwd))
+#define NM_DEVICE_IWD_CLASS(klass) \
+    (G_TYPE_CHECK_CLASS_CAST((klass), NM_TYPE_DEVICE_IWD, NMDeviceIwdClass))
+#define NM_IS_DEVICE_IWD(obj)         (G_TYPE_CHECK_INSTANCE_TYPE((obj), NM_TYPE_DEVICE_IWD))
+#define NM_IS_DEVICE_IWD_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), NM_TYPE_DEVICE_IWD))
+#define NM_DEVICE_IWD_GET_CLASS(obj) \
+    (G_TYPE_INSTANCE_GET_CLASS((obj), NM_TYPE_DEVICE_IWD, NMDeviceIwdClass))
+
+#define NM_DEVICE_IWD_MODE                NM_DEVICE_WIFI_MODE
+#define NM_DEVICE_IWD_BITRATE             NM_DEVICE_WIFI_BITRATE
+#define NM_DEVICE_IWD_ACCESS_POINTS       NM_DEVICE_WIFI_ACCESS_POINTS
+#define NM_DEVICE_IWD_ACTIVE_ACCESS_POINT NM_DEVICE_WIFI_ACTIVE_ACCESS_POINT
+#define NM_DEVICE_IWD_CAPABILITIES        NM_DEVICE_WIFI_CAPABILITIES
+#define NM_DEVICE_IWD_SCANNING            NM_DEVICE_WIFI_SCANNING
+#define NM_DEVICE_IWD_LAST_SCAN           NM_DEVICE_WIFI_LAST_SCAN
+
+typedef struct _NMDeviceIwd      NMDeviceIwd;
+typedef struct _NMDeviceIwdClass NMDeviceIwdClass;
+
+GType nm_device_iwd_get_type(void);
+
+NMDevice *nm_device_iwd_new(const char *iface);
+
+void nm_device_iwd_set_dbus_object(NMDeviceIwd *device, GDBusObject *object);
+
+gboolean nm_device_iwd_agent_query(NMDeviceIwd *device, GDBusMethodInvocation *invocation);
+
+const CList *_nm_device_iwd_get_aps(NMDeviceIwd *self);
+
+void _nm_device_iwd_request_scan(NMDeviceIwd *          self,
+                                 GVariant *             options,
+                                 GDBusMethodInvocation *invocation);
+
+void nm_device_iwd_network_add_remove(NMDeviceIwd *device, GDBusProxy *network, bool add);
+
+#endif /* __NETWORKMANAGER_DEVICE_IWD_H__ */
diff --git a/src/core/devices/wifi/nm-device-olpc-mesh.c b/src/core/devices/wifi/nm-device-olpc-mesh.c
new file mode 100644
index 00000000..af83c4a3
--- /dev/null
+++ b/src/core/devices/wifi/nm-device-olpc-mesh.c
@@ -0,0 +1,551 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+/*
+ * Dan Williams <dcbw@redhat.com>
+ * Sjoerd Simons <sjoerd.simons@collabora.co.uk>
+ * Daniel Drake <dsd@laptop.org>
+ * Copyright (C) 2005 - 2014 Red Hat, Inc.
+ * Copyright (C) 2008 Collabora Ltd.
+ * Copyright (C) 2009 One Laptop per Child
+ */
+
+#include "src/core/nm-default-daemon.h"
+
+#include "nm-device-olpc-mesh.h"
+
+#include <netinet/in.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include <signal.h>
+#include <unistd.h>
+#include <sys/ioctl.h>
+
+#include "devices/nm-device.h"
+#include "nm-device-wifi.h"
+#include "devices/nm-device-private.h"
+#include "nm-utils.h"
+#include "NetworkManagerUtils.h"
+#include "nm-act-request.h"
+#include "nm-setting-connection.h"
+#include "nm-setting-olpc-mesh.h"
+#include "nm-manager.h"
+#include "platform/nm-platform.h"
+
+#define _NMLOG_DEVICE_TYPE NMDeviceOlpcMesh
+#include "devices/nm-device-logging.h"
+
+/*****************************************************************************/
+
+NM_GOBJECT_PROPERTIES_DEFINE(NMDeviceOlpcMesh, PROP_COMPANION, PROP_ACTIVE_CHANNEL, );
+
+typedef struct {
+    NMDevice * companion;
+    NMManager *manager;
+    bool       stage1_waiting : 1;
+} NMDeviceOlpcMeshPrivate;
+
+struct _NMDeviceOlpcMesh {
+    NMDevice                parent;
+    NMDeviceOlpcMeshPrivate _priv;
+};
+
+struct _NMDeviceOlpcMeshClass {
+    NMDeviceClass parent;
+};
+
+G_DEFINE_TYPE(NMDeviceOlpcMesh, nm_device_olpc_mesh, NM_TYPE_DEVICE)
+
+#define NM_DEVICE_OLPC_MESH_GET_PRIVATE(self) \
+    _NM_GET_PRIVATE(self, NMDeviceOlpcMesh, NM_IS_DEVICE_OLPC_MESH, NMDevice)
+
+/*****************************************************************************/
+
+static gboolean
+get_autoconnect_allowed(NMDevice *device)
+{
+    NMDeviceOlpcMesh *       self = NM_DEVICE_OLPC_MESH(device);
+    NMDeviceOlpcMeshPrivate *priv = NM_DEVICE_OLPC_MESH_GET_PRIVATE(self);
+
+    /* We can't even connect if we don't have a companion yet. */
+    if (!priv->companion)
+        return FALSE;
+
+    /* We must not attempt to autoconnect when the companion is connected or
+     * connecting, * because we'd tear down its connection. */
+    if (nm_device_get_state(priv->companion) > NM_DEVICE_STATE_DISCONNECTED)
+        return FALSE;
+
+    return TRUE;
+}
+
+#define DEFAULT_SSID "olpc-mesh"
+
+static gboolean
+complete_connection(NMDevice *           device,
+                    NMConnection *       connection,
+                    const char *         specific_object,
+                    NMConnection *const *existing_connections,
+                    GError **            error)
+{
+    NMSettingOlpcMesh *s_mesh;
+
+    s_mesh = nm_connection_get_setting_olpc_mesh(connection);
+    if (!s_mesh) {
+        s_mesh = (NMSettingOlpcMesh *) nm_setting_olpc_mesh_new();
+        nm_connection_add_setting(connection, NM_SETTING(s_mesh));
+    }
+
+    if (!nm_setting_olpc_mesh_get_ssid(s_mesh)) {
+        gs_unref_bytes GBytes *ssid = NULL;
+
+        ssid = g_bytes_new_static(DEFAULT_SSID, NM_STRLEN(DEFAULT_SSID));
+        g_object_set(G_OBJECT(s_mesh), NM_SETTING_OLPC_MESH_SSID, ssid, NULL);
+    }
+
+    if (!nm_setting_olpc_mesh_get_dhcp_anycast_address(s_mesh)) {
+        const char *anycast = "c0:27:c0:27:c0:27";
+
+        g_object_set(G_OBJECT(s_mesh), NM_SETTING_OLPC_MESH_DHCP_ANYCAST_ADDRESS, anycast, NULL);
+    }
+
+    nm_utils_complete_generic(nm_device_get_platform(device),
+                              connection,
+                              NM_SETTING_OLPC_MESH_SETTING_NAME,
+                              existing_connections,
+                              NULL,
+                              _("Mesh"),
+                              NULL,
+                              NULL,
+                              FALSE); /* No IPv6 by default */
+
+    return TRUE;
+}
+
+/*****************************************************************************/
+
+static NMActStageReturn
+act_stage1_prepare(NMDevice *device, NMDeviceStateReason *out_failure_reason)
+{
+    NMDeviceOlpcMesh *       self = NM_DEVICE_OLPC_MESH(device);
+    NMDeviceOlpcMeshPrivate *priv = NM_DEVICE_OLPC_MESH_GET_PRIVATE(self);
+
+    /* disconnect companion device, if it is connected */
+    if (nm_device_get_act_request(NM_DEVICE(priv->companion))) {
+        _LOGI(LOGD_OLPC, "disconnecting companion device %s", nm_device_get_iface(priv->companion));
+        /* FIXME: VPN stuff here is a bug; but we can't really change API now... */
+        nm_device_state_changed(NM_DEVICE(priv->companion),
+                                NM_DEVICE_STATE_DISCONNECTED,
+                                NM_DEVICE_STATE_REASON_USER_REQUESTED);
+        _LOGI(LOGD_OLPC, "companion %s disconnected", nm_device_get_iface(priv->companion));
+    }
+
+    /* wait with continuing configuration until the companion device is done scanning */
+    if (nm_device_wifi_get_scanning(NM_DEVICE_WIFI(priv->companion))) {
+        priv->stage1_waiting = TRUE;
+        return NM_ACT_STAGE_RETURN_POSTPONE;
+    }
+
+    priv->stage1_waiting = FALSE;
+    return NM_ACT_STAGE_RETURN_SUCCESS;
+}
+
+static gboolean
+_mesh_set_channel(NMDeviceOlpcMesh *self, guint32 channel)
+{
+    NMPlatform *platform;
+    int         ifindex = nm_device_get_ifindex(NM_DEVICE(self));
+    guint32     old_channel;
+
+    platform    = nm_device_get_platform(NM_DEVICE(self));
+    old_channel = nm_platform_mesh_get_channel(platform, ifindex);
+
+    if (channel == 0)
+        channel = old_channel;
+
+    /* We want to call this even if the channel number is the same,
+     * because that actually starts the mesh with the configured mesh ID. */
+    if (!nm_platform_mesh_set_channel(platform, ifindex, channel))
+        return FALSE;
+
+    if (old_channel != channel)
+        _notify(self, PROP_ACTIVE_CHANNEL);
+
+    return TRUE;
+}
+
+static NMActStageReturn
+act_stage2_config(NMDevice *device, NMDeviceStateReason *out_failure_reason)
+{
+    NMDeviceOlpcMesh * self = NM_DEVICE_OLPC_MESH(device);
+    NMSettingOlpcMesh *s_mesh;
+    GBytes *           ssid;
+    const char *       anycast_addr;
+    gboolean           success;
+
+    s_mesh = nm_device_get_applied_setting(device, NM_TYPE_SETTING_OLPC_MESH);
+    g_return_val_if_fail(s_mesh, NM_ACT_STAGE_RETURN_FAILURE);
+
+    ssid = nm_setting_olpc_mesh_get_ssid(s_mesh);
+
+    nm_device_take_down(NM_DEVICE(self), TRUE);
+    success = nm_platform_mesh_set_ssid(nm_device_get_platform(device),
+                                        nm_device_get_ifindex(device),
+                                        g_bytes_get_data(ssid, NULL),
+                                        g_bytes_get_size(ssid));
+    nm_device_bring_up(NM_DEVICE(self), TRUE, NULL);
+    if (!success) {
+        _LOGW(LOGD_WIFI, "Unable to set the mesh ID");
+        return NM_ACT_STAGE_RETURN_FAILURE;
+    }
+
+    anycast_addr = nm_setting_olpc_mesh_get_dhcp_anycast_address(s_mesh);
+    nm_device_set_dhcp_anycast_address(device, anycast_addr);
+
+    if (!_mesh_set_channel(self, nm_setting_olpc_mesh_get_channel(s_mesh))) {
+        _LOGW(LOGD_WIFI, "Unable to set the mesh channel");
+        return NM_ACT_STAGE_RETURN_FAILURE;
+    }
+
+    return NM_ACT_STAGE_RETURN_SUCCESS;
+}
+
+static gboolean
+is_available(NMDevice *device, NMDeviceCheckDevAvailableFlags flags)
+{
+    NMDeviceOlpcMesh *self = NM_DEVICE_OLPC_MESH(device);
+
+    if (!NM_DEVICE_OLPC_MESH_GET_PRIVATE(self)->companion) {
+        _LOGD(LOGD_WIFI, "not available because companion not found");
+        return FALSE;
+    }
+
+    return TRUE;
+}
+
+/*****************************************************************************/
+
+static void
+companion_cleanup(NMDeviceOlpcMesh *self)
+{
+    NMDeviceOlpcMeshPrivate *priv = NM_DEVICE_OLPC_MESH_GET_PRIVATE(self);
+
+    if (priv->companion) {
+        nm_device_wifi_scanning_prohibited_track(NM_DEVICE_WIFI(priv->companion), self, FALSE);
+        g_signal_handlers_disconnect_by_data(priv->companion, self);
+        g_clear_object(&priv->companion);
+    }
+    _notify(self, PROP_COMPANION);
+}
+
+static void
+companion_notify_cb(NMDeviceWifi *companion, GParamSpec *pspec, gpointer user_data)
+{
+    NMDeviceOlpcMesh *       self = NM_DEVICE_OLPC_MESH(user_data);
+    NMDeviceOlpcMeshPrivate *priv = NM_DEVICE_OLPC_MESH_GET_PRIVATE(self);
+
+    nm_assert(NM_IS_DEVICE_WIFI(companion));
+    nm_assert(priv->companion == (gpointer) companion);
+
+    if (!priv->stage1_waiting)
+        return;
+
+    if (!nm_device_wifi_get_scanning(NM_DEVICE_WIFI(companion))) {
+        priv->stage1_waiting = FALSE;
+        nm_device_activate_schedule_stage1_device_prepare(NM_DEVICE(self), FALSE);
+    }
+}
+
+/* disconnect from mesh if someone starts using the companion */
+static void
+companion_state_changed_cb(NMDeviceWifi *      companion,
+                           NMDeviceState       state,
+                           NMDeviceState       old_state,
+                           NMDeviceStateReason reason,
+                           gpointer            user_data)
+{
+    NMDeviceOlpcMesh *self       = NM_DEVICE_OLPC_MESH(user_data);
+    NMDeviceState     self_state = nm_device_get_state(NM_DEVICE(self));
+
+    if (old_state > NM_DEVICE_STATE_DISCONNECTED && state <= NM_DEVICE_STATE_DISCONNECTED) {
+        nm_device_emit_recheck_auto_activate(NM_DEVICE(self));
+    }
+
+    if (self_state < NM_DEVICE_STATE_PREPARE || self_state > NM_DEVICE_STATE_ACTIVATED
+        || state < NM_DEVICE_STATE_PREPARE || state > NM_DEVICE_STATE_ACTIVATED)
+        return;
+
+    _LOGD(LOGD_OLPC, "disconnecting mesh due to companion connectivity");
+    /* FIXME: VPN stuff here is a bug; but we can't really change API now... */
+    nm_device_state_changed(NM_DEVICE(self),
+                            NM_DEVICE_STATE_DISCONNECTED,
+                            NM_DEVICE_STATE_REASON_USER_REQUESTED);
+}
+
+static gboolean
+companion_autoconnect_allowed_cb(NMDeviceWifi *companion, gpointer user_data)
+{
+    NMDeviceOlpcMesh *self  = NM_DEVICE_OLPC_MESH(user_data);
+    NMDeviceState     state = nm_device_get_state(NM_DEVICE(self));
+
+    /* Don't allow the companion to autoconnect while a mesh connection is
+     * active */
+    return (state < NM_DEVICE_STATE_PREPARE) || (state > NM_DEVICE_STATE_ACTIVATED);
+}
+
+static gboolean
+check_companion(NMDeviceOlpcMesh *self, NMDevice *other)
+{
+    NMDeviceOlpcMeshPrivate *priv = NM_DEVICE_OLPC_MESH_GET_PRIVATE(self);
+    const char *             my_addr, *their_addr;
+
+    if (!NM_IS_DEVICE_WIFI(other))
+        return FALSE;
+
+    my_addr    = nm_device_get_hw_address(NM_DEVICE(self));
+    their_addr = nm_device_get_hw_address(other);
+    if (!nm_utils_hwaddr_matches(my_addr, -1, their_addr, -1))
+        return FALSE;
+
+    nm_assert(priv->companion == NULL);
+    priv->companion = g_object_ref(other);
+
+    _LOGI(LOGD_OLPC, "found companion Wi-Fi device %s", nm_device_get_iface(other));
+
+    g_signal_connect(G_OBJECT(other),
+                     NM_DEVICE_STATE_CHANGED,
+                     G_CALLBACK(companion_state_changed_cb),
+                     self);
+
+    g_signal_connect(G_OBJECT(other),
+                     "notify::" NM_DEVICE_WIFI_SCANNING,
+                     G_CALLBACK(companion_notify_cb),
+                     self);
+
+    g_signal_connect(G_OBJECT(other),
+                     NM_DEVICE_AUTOCONNECT_ALLOWED,
+                     G_CALLBACK(companion_autoconnect_allowed_cb),
+                     self);
+
+    _notify(self, PROP_COMPANION);
+
+    return TRUE;
+}
+
+static void
+device_added_cb(NMManager *manager, NMDevice *other, gpointer user_data)
+{
+    NMDeviceOlpcMesh *       self = NM_DEVICE_OLPC_MESH(user_data);
+    NMDeviceOlpcMeshPrivate *priv = NM_DEVICE_OLPC_MESH_GET_PRIVATE(self);
+
+    if (!priv->companion && check_companion(self, other)) {
+        nm_device_queue_recheck_available(NM_DEVICE(self),
+                                          NM_DEVICE_STATE_REASON_NONE,
+                                          NM_DEVICE_STATE_REASON_NONE);
+        nm_device_remove_pending_action(NM_DEVICE(self),
+                                        NM_PENDING_ACTION_WAITING_FOR_COMPANION,
+                                        FALSE);
+    }
+}
+
+static void
+device_removed_cb(NMManager *manager, NMDevice *other, gpointer user_data)
+{
+    NMDeviceOlpcMesh *self = NM_DEVICE_OLPC_MESH(user_data);
+
+    if (other == NM_DEVICE_OLPC_MESH_GET_PRIVATE(self)->companion)
+        companion_cleanup(self);
+}
+
+static void
+find_companion(NMDeviceOlpcMesh *self)
+{
+    NMDeviceOlpcMeshPrivate *priv = NM_DEVICE_OLPC_MESH_GET_PRIVATE(self);
+    const CList *            tmp_lst;
+    NMDevice *               candidate;
+
+    if (priv->companion)
+        return;
+
+    nm_device_add_pending_action(NM_DEVICE(self), NM_PENDING_ACTION_WAITING_FOR_COMPANION, TRUE);
+
+    /* Try to find the companion if it's already known to the NMManager */
+    nm_manager_for_each_device (priv->manager, candidate, tmp_lst) {
+        if (check_companion(self, candidate)) {
+            nm_device_queue_recheck_available(NM_DEVICE(self),
+                                              NM_DEVICE_STATE_REASON_NONE,
+                                              NM_DEVICE_STATE_REASON_NONE);
+            nm_device_remove_pending_action(NM_DEVICE(self),
+                                            NM_PENDING_ACTION_WAITING_FOR_COMPANION,
+                                            TRUE);
+            break;
+        }
+    }
+}
+
+static void
+state_changed(NMDevice *          device,
+              NMDeviceState       new_state,
+              NMDeviceState       old_state,
+              NMDeviceStateReason reason)
+{
+    NMDeviceOlpcMesh *       self = NM_DEVICE_OLPC_MESH(device);
+    NMDeviceOlpcMeshPrivate *priv = NM_DEVICE_OLPC_MESH_GET_PRIVATE(self);
+
+    if (new_state == NM_DEVICE_STATE_UNAVAILABLE)
+        find_companion(self);
+
+    if (priv->companion) {
+        gboolean temporarily_prohibited = FALSE;
+
+        if (new_state >= NM_DEVICE_STATE_PREPARE && new_state <= NM_DEVICE_STATE_IP_CONFIG) {
+            /* Don't allow the companion to scan while configuring the mesh interface */
+            temporarily_prohibited = TRUE;
+        }
+        nm_device_wifi_scanning_prohibited_track(NM_DEVICE_WIFI(priv->companion),
+                                                 self,
+                                                 temporarily_prohibited);
+    }
+}
+
+static guint32
+get_dhcp_timeout_for_device(NMDevice *device, int addr_family)
+{
+    /* shorter timeout for mesh connectivity */
+    return 20;
+}
+
+/*****************************************************************************/
+
+static void
+get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec)
+{
+    NMDeviceOlpcMesh *       self   = NM_DEVICE_OLPC_MESH(object);
+    NMDevice *               device = NM_DEVICE(self);
+    NMDeviceOlpcMeshPrivate *priv   = NM_DEVICE_OLPC_MESH_GET_PRIVATE(self);
+
+    switch (prop_id) {
+    case PROP_COMPANION:
+        nm_dbus_utils_g_value_set_object_path(value, priv->companion);
+        break;
+    case PROP_ACTIVE_CHANNEL:
+        g_value_set_uint(value,
+                         nm_platform_mesh_get_channel(nm_device_get_platform(device),
+                                                      nm_device_get_ifindex(device)));
+        break;
+    default:
+        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
+        break;
+    }
+}
+
+/*****************************************************************************/
+
+static void
+nm_device_olpc_mesh_init(NMDeviceOlpcMesh *self)
+{}
+
+static void
+constructed(GObject *object)
+{
+    NMDeviceOlpcMesh *       self = NM_DEVICE_OLPC_MESH(object);
+    NMDeviceOlpcMeshPrivate *priv = NM_DEVICE_OLPC_MESH_GET_PRIVATE(self);
+
+    G_OBJECT_CLASS(nm_device_olpc_mesh_parent_class)->constructed(object);
+
+    priv->manager = g_object_ref(NM_MANAGER_GET);
+
+    g_signal_connect(priv->manager, NM_MANAGER_DEVICE_ADDED, G_CALLBACK(device_added_cb), self);
+    g_signal_connect(priv->manager, NM_MANAGER_DEVICE_REMOVED, G_CALLBACK(device_removed_cb), self);
+}
+
+NMDevice *
+nm_device_olpc_mesh_new(const char *iface)
+{
+    return g_object_new(NM_TYPE_DEVICE_OLPC_MESH,
+                        NM_DEVICE_IFACE,
+                        iface,
+                        NM_DEVICE_TYPE_DESC,
+                        "802.11 OLPC Mesh",
+                        NM_DEVICE_DEVICE_TYPE,
+                        NM_DEVICE_TYPE_OLPC_MESH,
+                        NM_DEVICE_LINK_TYPE,
+                        NM_LINK_TYPE_OLPC_MESH,
+                        NULL);
+}
+
+static void
+dispose(GObject *object)
+{
+    NMDeviceOlpcMesh *       self = NM_DEVICE_OLPC_MESH(object);
+    NMDeviceOlpcMeshPrivate *priv = NM_DEVICE_OLPC_MESH_GET_PRIVATE(self);
+
+    companion_cleanup(self);
+
+    if (priv->manager) {
+        g_signal_handlers_disconnect_by_func(priv->manager, G_CALLBACK(device_added_cb), self);
+        g_signal_handlers_disconnect_by_func(priv->manager, G_CALLBACK(device_removed_cb), self);
+        g_clear_object(&priv->manager);
+    }
+
+    G_OBJECT_CLASS(nm_device_olpc_mesh_parent_class)->dispose(object);
+}
+
+static const NMDBusInterfaceInfoExtended interface_info_device_olpc_mesh = {
+    .parent = NM_DEFINE_GDBUS_INTERFACE_INFO_INIT(
+        NM_DBUS_INTERFACE_DEVICE_OLPC_MESH,
+        .signals    = NM_DEFINE_GDBUS_SIGNAL_INFOS(&nm_signal_info_property_changed_legacy, ),
+        .properties = NM_DEFINE_GDBUS_PROPERTY_INFOS(
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("HwAddress",
+                                                             "s",
+                                                             NM_DEVICE_HW_ADDRESS),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("Companion",
+                                                             "o",
+                                                             NM_DEVICE_OLPC_MESH_COMPANION),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L(
+                "ActiveChannel",
+                "u",
+                NM_DEVICE_OLPC_MESH_ACTIVE_CHANNEL), ), ),
+    .legacy_property_changed = TRUE,
+};
+
+static void
+nm_device_olpc_mesh_class_init(NMDeviceOlpcMeshClass *klass)
+{
+    GObjectClass *     object_class      = G_OBJECT_CLASS(klass);
+    NMDBusObjectClass *dbus_object_class = NM_DBUS_OBJECT_CLASS(klass);
+    NMDeviceClass *    device_class      = NM_DEVICE_CLASS(klass);
+
+    object_class->constructed  = constructed;
+    object_class->get_property = get_property;
+    object_class->dispose      = dispose;
+
+    dbus_object_class->interface_infos = NM_DBUS_INTERFACE_INFOS(&interface_info_device_olpc_mesh);
+
+    device_class->connection_type_supported        = NM_SETTING_OLPC_MESH_SETTING_NAME;
+    device_class->connection_type_check_compatible = NM_SETTING_OLPC_MESH_SETTING_NAME;
+    device_class->link_types = NM_DEVICE_DEFINE_LINK_TYPES(NM_LINK_TYPE_OLPC_MESH);
+
+    device_class->get_autoconnect_allowed     = get_autoconnect_allowed;
+    device_class->complete_connection         = complete_connection;
+    device_class->is_available                = is_available;
+    device_class->act_stage1_prepare          = act_stage1_prepare;
+    device_class->act_stage2_config           = act_stage2_config;
+    device_class->state_changed               = state_changed;
+    device_class->get_dhcp_timeout_for_device = get_dhcp_timeout_for_device;
+
+    obj_properties[PROP_COMPANION] = g_param_spec_string(NM_DEVICE_OLPC_MESH_COMPANION,
+                                                         "",
+                                                         "",
+                                                         NULL,
+                                                         G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_ACTIVE_CHANNEL] =
+        g_param_spec_uint(NM_DEVICE_OLPC_MESH_ACTIVE_CHANNEL,
+                          "",
+                          "",
+                          0,
+                          G_MAXUINT32,
+                          0,
+                          G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    g_object_class_install_properties(object_class, _PROPERTY_ENUMS_LAST, obj_properties);
+}
diff --git a/src/core/devices/wifi/nm-device-olpc-mesh.h b/src/core/devices/wifi/nm-device-olpc-mesh.h
new file mode 100644
index 00000000..79b7fd5d
--- /dev/null
+++ b/src/core/devices/wifi/nm-device-olpc-mesh.h
@@ -0,0 +1,38 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+/*
+ * Dan Williams <dcbw@redhat.com>
+ * Sjoerd Simons <sjoerd.simons@collabora.co.uk>
+ * Daniel Drake <dsd@laptop.org>
+ * Copyright (C) 2005 Red Hat, Inc.
+ * Copyright (C) 2008 Collabora Ltd.
+ * Copyright (C) 2009 One Laptop per Child
+ */
+
+#ifndef __NETWORKMANAGER_DEVICE_OLPC_MESH_H__
+#define __NETWORKMANAGER_DEVICE_OLPC_MESH_H__
+
+#include "devices/nm-device.h"
+
+#define NM_TYPE_DEVICE_OLPC_MESH (nm_device_olpc_mesh_get_type())
+#define NM_DEVICE_OLPC_MESH(obj) \
+    (G_TYPE_CHECK_INSTANCE_CAST((obj), NM_TYPE_DEVICE_OLPC_MESH, NMDeviceOlpcMesh))
+#define NM_DEVICE_OLPC_MESH_CLASS(klass) \
+    (G_TYPE_CHECK_CLASS_CAST((klass), NM_TYPE_DEVICE_OLPC_MESH, NMDeviceOlpcMeshClass))
+#define NM_IS_DEVICE_OLPC_MESH(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), NM_TYPE_DEVICE_OLPC_MESH))
+#define NM_IS_DEVICE_OLPC_MESH_CLASS(klass) \
+    (G_TYPE_CHECK_CLASS_TYPE((klass), NM_TYPE_DEVICE_OLPC_MESH))
+#define NM_DEVICE_OLPC_MESH_GET_CLASS(obj) \
+    (G_TYPE_INSTANCE_GET_CLASS((obj), NM_TYPE_DEVICE_OLPC_MESH, NMDeviceOlpcMeshClass))
+
+#define NM_DEVICE_OLPC_MESH_COMPANION      "companion"
+#define NM_DEVICE_OLPC_MESH_BITRATE        "bitrate"
+#define NM_DEVICE_OLPC_MESH_ACTIVE_CHANNEL "active-channel"
+
+typedef struct _NMDeviceOlpcMesh      NMDeviceOlpcMesh;
+typedef struct _NMDeviceOlpcMeshClass NMDeviceOlpcMeshClass;
+
+GType nm_device_olpc_mesh_get_type(void);
+
+NMDevice *nm_device_olpc_mesh_new(const char *iface);
+
+#endif /* __NETWORKMANAGER_DEVICE_OLPC_MESH_H__ */
diff --git a/src/core/devices/wifi/nm-device-wifi-p2p.c b/src/core/devices/wifi/nm-device-wifi-p2p.c
new file mode 100644
index 00000000..fb987600
--- /dev/null
+++ b/src/core/devices/wifi/nm-device-wifi-p2p.c
@@ -0,0 +1,1280 @@
+/* SPDX-License-Identifier: LGPL-2.1-or-later */
+/*
+ * Copyright (C) 2018 Red Hat, Inc.
+ */
+
+#include "src/core/nm-default-daemon.h"
+
+#include "nm-device-wifi-p2p.h"
+
+#include <sys/socket.h>
+
+#include "supplicant/nm-supplicant-manager.h"
+#include "supplicant/nm-supplicant-interface.h"
+
+#include "NetworkManagerUtils.h"
+#include "devices/nm-device-private.h"
+#include "nm-act-request.h"
+#include "nm-core-internal.h"
+#include "nm-glib-aux/nm-ref-string.h"
+#include "nm-ip4-config.h"
+#include "nm-manager.h"
+#include "nm-manager.h"
+#include "nm-setting-wifi-p2p.h"
+#include "nm-utils.h"
+#include "nm-wifi-p2p-peer.h"
+#include "platform/nm-platform.h"
+#include "platform/nmp-object.h"
+#include "settings/nm-settings.h"
+
+#define _NMLOG_DEVICE_TYPE NMDeviceWifiP2P
+#include "devices/nm-device-logging.h"
+
+/*****************************************************************************/
+
+NM_GOBJECT_PROPERTIES_DEFINE(NMDeviceWifiP2P, PROP_PEERS, );
+
+typedef struct {
+    NMSupplicantManager *sup_mgr;
+
+    /* NOTE: In theory management and group ifaces could be identical. However,
+     * in practice, this cannot happen currently as NMDeviceWifiP2P is only
+     * created for existing non-P2P interfaces.
+     * (i.e. a single standalone P2P interface is not supported at this point)
+     */
+    NMSupplicantInterface *mgmt_iface;
+    NMSupplicantInterface *group_iface;
+
+    CList peers_lst_head;
+
+    guint find_peer_timeout_id;
+    guint sup_timeout_id;
+    guint peer_dump_id;
+    guint peer_missing_id;
+
+    bool is_waiting_for_supplicant : 1;
+} NMDeviceWifiP2PPrivate;
+
+struct _NMDeviceWifiP2P {
+    NMDevice               parent;
+    NMDeviceWifiP2PPrivate _priv;
+};
+
+struct _NMDeviceWifiP2PClass {
+    NMDeviceClass parent;
+};
+
+G_DEFINE_TYPE(NMDeviceWifiP2P, nm_device_wifi_p2p, NM_TYPE_DEVICE)
+
+#define NM_DEVICE_WIFI_P2P_GET_PRIVATE(self) \
+    _NM_GET_PRIVATE(self, NMDeviceWifiP2P, NM_IS_DEVICE_WIFI_P2P, NMDevice)
+
+/*****************************************************************************/
+
+static const NMDBusInterfaceInfoExtended interface_info_device_wifi_p2p;
+static const GDBusSignalInfo             nm_signal_info_wifi_p2p_peer_added;
+static const GDBusSignalInfo             nm_signal_info_wifi_p2p_peer_removed;
+
+static void supplicant_group_interface_release(NMDeviceWifiP2P *self);
+static void supplicant_interfaces_release(NMDeviceWifiP2P *self, gboolean set_is_waiting);
+
+/*****************************************************************************/
+
+static void
+_peer_dump(NMDeviceWifiP2P *    self,
+           NMLogLevel           log_level,
+           const NMWifiP2PPeer *peer,
+           const char *         prefix,
+           gint32               now_s)
+{
+    char buf[1024];
+
+    _NMLOG(log_level,
+           LOGD_WIFI_SCAN,
+           "wifi-peer: %-7s %s",
+           prefix,
+           nm_wifi_p2p_peer_to_string(peer, buf, sizeof(buf), now_s));
+}
+
+static gboolean
+peer_list_dump(gpointer user_data)
+{
+    NMDeviceWifiP2P *       self = NM_DEVICE_WIFI_P2P(user_data);
+    NMDeviceWifiP2PPrivate *priv = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+
+    priv->peer_dump_id = 0;
+
+    if (_LOGD_ENABLED(LOGD_WIFI_SCAN)) {
+        NMWifiP2PPeer *peer;
+        gint32         now_s = nm_utils_get_monotonic_timestamp_sec();
+
+        _LOGD(LOGD_WIFI_SCAN, "P2P Peers: [now:%u]", now_s);
+        c_list_for_each_entry (peer, &priv->peers_lst_head, peers_lst)
+            _peer_dump(self, LOGL_DEBUG, peer, "dump", now_s);
+    }
+    return G_SOURCE_REMOVE;
+}
+
+static void
+schedule_peer_list_dump(NMDeviceWifiP2P *self)
+{
+    NMDeviceWifiP2PPrivate *priv = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+
+    if (!priv->peer_dump_id && _LOGD_ENABLED(LOGD_WIFI_SCAN))
+        priv->peer_dump_id = g_timeout_add_seconds(1, peer_list_dump, self);
+}
+
+/*****************************************************************************/
+
+static void
+_set_is_waiting_for_supplicant(NMDeviceWifiP2P *self, gboolean is_waiting)
+{
+    NMDeviceWifiP2PPrivate *priv = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+
+    if (priv->is_waiting_for_supplicant == (!!is_waiting))
+        return;
+
+    priv->is_waiting_for_supplicant = is_waiting;
+
+    if (is_waiting)
+        nm_device_add_pending_action(NM_DEVICE(self),
+                                     NM_PENDING_ACTION_WAITING_FOR_SUPPLICANT,
+                                     TRUE);
+    else
+        nm_device_remove_pending_action(NM_DEVICE(self),
+                                        NM_PENDING_ACTION_WAITING_FOR_SUPPLICANT,
+                                        TRUE);
+}
+
+/*****************************************************************************/
+
+static gboolean
+check_connection_peer_joined(NMDeviceWifiP2P *device)
+{
+    NMDeviceWifiP2PPrivate *priv = NM_DEVICE_WIFI_P2P_GET_PRIVATE(device);
+    NMConnection *          conn = nm_device_get_applied_connection(NM_DEVICE(device));
+    NMWifiP2PPeer *         peer;
+    const char *            group;
+    const char *const *     groups;
+
+    if (!conn || !priv->group_iface)
+        return FALSE;
+
+    /* Comparing the object path found on the group_iface with the peers
+     * found on the mgmt_iface is legal. */
+    group = nm_supplicant_interface_get_p2p_group_path(priv->group_iface);
+    if (!group)
+        return FALSE;
+
+    /* NOTE: We currently only support connections to a specific peer */
+    peer = nm_wifi_p2p_peers_find_first_compatible(&priv->peers_lst_head, conn);
+    if (!peer)
+        return FALSE;
+
+    groups = nm_wifi_p2p_peer_get_groups(peer);
+    if (!groups || !g_strv_contains(groups, group))
+        return FALSE;
+
+    return TRUE;
+}
+
+static gboolean
+disconnect_on_connection_peer_missing_cb(gpointer user_data)
+{
+    NMDevice *              device = NM_DEVICE(user_data);
+    NMDeviceWifiP2P *       self   = NM_DEVICE_WIFI_P2P(device);
+    NMDeviceWifiP2PPrivate *priv   = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+
+    _LOGW(LOGD_WIFI, "Peer requested in connection is missing for too long, failing connection.");
+
+    priv->peer_missing_id = 0;
+
+    nm_device_state_changed(device, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_PEER_NOT_FOUND);
+    return FALSE;
+}
+
+static void
+update_disconnect_on_connection_peer_missing(NMDeviceWifiP2P *self)
+{
+    NMDeviceWifiP2PPrivate *priv = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+    NMDeviceState           state;
+
+    state = nm_device_get_state(NM_DEVICE(self));
+    if (state < NM_DEVICE_STATE_IP_CONFIG || state > NM_DEVICE_STATE_ACTIVATED) {
+        nm_clear_g_source(&priv->peer_missing_id);
+        return;
+    }
+
+    if (check_connection_peer_joined(self)) {
+        if (nm_clear_g_source(&priv->peer_missing_id))
+            _LOGD(LOGD_WIFI, "Peer requested in connection is joined, removing timeout");
+        return;
+    }
+
+    if (priv->peer_missing_id == 0) {
+        _LOGD(LOGD_WIFI, "Peer requested in connection is missing, adding timeout");
+        priv->peer_missing_id =
+            g_timeout_add_seconds(5, disconnect_on_connection_peer_missing_cb, self);
+    }
+}
+
+static gboolean
+is_available(NMDevice *device, NMDeviceCheckDevAvailableFlags flags)
+{
+    NMDeviceWifiP2P *          self = NM_DEVICE_WIFI_P2P(device);
+    NMDeviceWifiP2PPrivate *   priv = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+    NMSupplicantInterfaceState supplicant_state;
+
+    if (!priv->mgmt_iface)
+        return FALSE;
+
+    supplicant_state = nm_supplicant_interface_get_state(priv->mgmt_iface);
+    return nm_supplicant_interface_state_is_operational(supplicant_state);
+}
+
+static gboolean
+check_connection_compatible(NMDevice *device, NMConnection *connection, GError **error)
+{
+    if (!NM_DEVICE_CLASS(nm_device_wifi_p2p_parent_class)
+             ->check_connection_compatible(device, connection, error))
+        return FALSE;
+
+    /* TODO: Allow limitting the interface using the HW-address? */
+
+    /* We don't need to check anything else here. The P2P device will only
+     * exists if we are able to establish a P2P connection, and there should
+     * be no further restrictions necessary.
+     */
+
+    return TRUE;
+}
+
+static gboolean
+complete_connection(NMDevice *           device,
+                    NMConnection *       connection,
+                    const char *         specific_object,
+                    NMConnection *const *existing_connections,
+                    GError **            error)
+{
+    NMDeviceWifiP2P * self         = NM_DEVICE_WIFI_P2P(device);
+    gs_free char *    setting_name = NULL;
+    NMSettingWifiP2P *s_wifi_p2p;
+    NMWifiP2PPeer *   peer;
+    const char *      setting_peer;
+
+    s_wifi_p2p =
+        NM_SETTING_WIFI_P2P(nm_connection_get_setting(connection, NM_TYPE_SETTING_WIFI_P2P));
+
+    if (!specific_object) {
+        /* If not given a specific object, we need at minimum a peer address */
+        if (!s_wifi_p2p) {
+            g_set_error(error,
+                        NM_DEVICE_ERROR,
+                        NM_DEVICE_ERROR_INVALID_CONNECTION,
+                        "A '%s' setting is required if no Peer path was given",
+                        NM_SETTING_WIFI_P2P_SETTING_NAME);
+            return FALSE;
+        }
+
+        setting_peer = nm_setting_wifi_p2p_get_peer(s_wifi_p2p);
+        if (!setting_peer) {
+            g_set_error(error,
+                        NM_DEVICE_ERROR,
+                        NM_DEVICE_ERROR_INVALID_CONNECTION,
+                        "A '%s' setting with a valid Peer is required if no Peer path was given",
+                        NM_SETTING_WIFI_P2P_SETTING_NAME);
+            return FALSE;
+        }
+
+    } else {
+        peer = nm_wifi_p2p_peer_lookup_for_device(NM_DEVICE(self), specific_object);
+        if (!peer) {
+            g_set_error(error,
+                        NM_DEVICE_ERROR,
+                        NM_DEVICE_ERROR_SPECIFIC_OBJECT_NOT_FOUND,
+                        "The P2P peer %s is unknown",
+                        specific_object);
+            return FALSE;
+        }
+
+        setting_peer = nm_wifi_p2p_peer_get_address(peer);
+        g_return_val_if_fail(setting_peer, FALSE);
+    }
+
+    /* Add a Wi-Fi P2P setting if one doesn't exist yet */
+    if (!s_wifi_p2p) {
+        s_wifi_p2p = NM_SETTING_WIFI_P2P(nm_setting_wifi_p2p_new());
+        nm_connection_add_setting(connection, NM_SETTING(s_wifi_p2p));
+    }
+
+    g_object_set(G_OBJECT(s_wifi_p2p), NM_SETTING_WIFI_P2P_PEER, setting_peer, NULL);
+
+    setting_name = g_strdup_printf("Wi-Fi P2P Peer %s", setting_peer);
+    nm_utils_complete_generic(nm_device_get_platform(device),
+                              connection,
+                              NM_SETTING_WIFI_P2P_SETTING_NAME,
+                              existing_connections,
+                              setting_name,
+                              setting_name,
+                              NULL,
+                              NULL,
+                              TRUE);
+
+    return TRUE;
+}
+
+/*
+ * supplicant_find_timeout_cb
+ *
+ * Called when the supplicant has been unable to find the peer we want to connect to.
+ */
+static gboolean
+supplicant_find_timeout_cb(gpointer user_data)
+{
+    NMDevice *              device = NM_DEVICE(user_data);
+    NMDeviceWifiP2P *       self   = NM_DEVICE_WIFI_P2P(user_data);
+    NMDeviceWifiP2PPrivate *priv   = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+
+    priv->find_peer_timeout_id = 0;
+
+    nm_supplicant_interface_p2p_cancel_connect(priv->mgmt_iface);
+
+    if (nm_device_is_activating(device)) {
+        _LOGW(LOGD_DEVICE | LOGD_WIFI,
+              "Activation: (wifi-p2p) could not find peer, failing activation");
+        nm_device_state_changed(device,
+                                NM_DEVICE_STATE_FAILED,
+                                NM_DEVICE_STATE_REASON_PEER_NOT_FOUND);
+    }
+
+    return G_SOURCE_REMOVE;
+}
+
+static NMActStageReturn
+act_stage1_prepare(NMDevice *device, NMDeviceStateReason *out_failure_reason)
+{
+    NMDeviceWifiP2P *       self = NM_DEVICE_WIFI_P2P(device);
+    NMDeviceWifiP2PPrivate *priv = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+    NMConnection *          connection;
+    NMSettingWifiP2P *      s_wifi_p2p;
+    NMWifiP2PPeer *         peer;
+
+    if (!priv->mgmt_iface) {
+        NM_SET_OUT(out_failure_reason, NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
+        return NM_ACT_STAGE_RETURN_FAILURE;
+    }
+
+    connection = nm_device_get_applied_connection(NM_DEVICE(self));
+    g_return_val_if_fail(connection, NM_ACT_STAGE_RETURN_FAILURE);
+
+    s_wifi_p2p =
+        NM_SETTING_WIFI_P2P(nm_connection_get_setting(connection, NM_TYPE_SETTING_WIFI_P2P));
+    g_return_val_if_fail(s_wifi_p2p, NM_ACT_STAGE_RETURN_FAILURE);
+
+    peer = nm_wifi_p2p_peers_find_first_compatible(&priv->peers_lst_head, connection);
+    if (!peer) {
+        /* Set up a timeout on the find attempt and run a find for the same period of time */
+        if (priv->find_peer_timeout_id == 0) {
+            priv->find_peer_timeout_id =
+                g_timeout_add_seconds(10, supplicant_find_timeout_cb, self);
+
+            nm_supplicant_interface_p2p_start_find(priv->mgmt_iface, 10);
+        }
+        return NM_ACT_STAGE_RETURN_POSTPONE;
+    }
+
+    return NM_ACT_STAGE_RETURN_SUCCESS;
+}
+
+/*
+ * supplicant_connection_timeout_cb
+ *
+ * Called when the supplicant has been unable to connect to a peer
+ * within a specified period of time.
+ */
+static gboolean
+supplicant_connection_timeout_cb(gpointer user_data)
+{
+    NMDevice *              device = NM_DEVICE(user_data);
+    NMDeviceWifiP2P *       self   = NM_DEVICE_WIFI_P2P(user_data);
+    NMDeviceWifiP2PPrivate *priv   = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+
+    priv->sup_timeout_id = 0;
+
+    nm_supplicant_interface_p2p_cancel_connect(priv->mgmt_iface);
+
+    if (nm_device_is_activating(device)) {
+        _LOGW(LOGD_DEVICE | LOGD_WIFI,
+              "Activation: (wifi-p2p) connecting took too long, failing activation");
+        nm_device_state_changed(device,
+                                NM_DEVICE_STATE_FAILED,
+                                NM_DEVICE_STATE_REASON_SUPPLICANT_TIMEOUT);
+    }
+
+    return G_SOURCE_REMOVE;
+}
+
+static NMActStageReturn
+act_stage2_config(NMDevice *device, NMDeviceStateReason *out_failure_reason)
+{
+    NMDeviceWifiP2P *       self = NM_DEVICE_WIFI_P2P(device);
+    NMDeviceWifiP2PPrivate *priv = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+    NMConnection *          connection;
+    NMSettingWifiP2P *      s_wifi_p2p;
+    NMWifiP2PPeer *         peer;
+    GBytes *                wfd_ies;
+
+    if (nm_clear_g_source(&priv->find_peer_timeout_id))
+        nm_assert_not_reached();
+
+    if (!priv->mgmt_iface) {
+        NM_SET_OUT(out_failure_reason, NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
+        return NM_ACT_STAGE_RETURN_FAILURE;
+    }
+
+    connection = nm_device_get_applied_connection(device);
+    g_return_val_if_fail(connection, NM_ACT_STAGE_RETURN_FAILURE);
+    nm_assert(
+        NM_IS_SETTING_WIFI_P2P(nm_connection_get_setting(connection, NM_TYPE_SETTING_WIFI_P2P)));
+
+    /* The prepare stage ensures that the peer has been found */
+    peer = nm_wifi_p2p_peers_find_first_compatible(&priv->peers_lst_head, connection);
+    if (!peer) {
+        NM_SET_OUT(out_failure_reason, NM_DEVICE_STATE_REASON_PEER_NOT_FOUND);
+        return NM_ACT_STAGE_RETURN_FAILURE;
+    }
+
+    /* Set the WFD IEs before trying to establish the connection. */
+    s_wifi_p2p =
+        NM_SETTING_WIFI_P2P(nm_connection_get_setting(connection, NM_TYPE_SETTING_WIFI_P2P));
+    wfd_ies = nm_setting_wifi_p2p_get_wfd_ies(s_wifi_p2p);
+    nm_supplicant_manager_set_wfd_ies(priv->sup_mgr, wfd_ies);
+
+    /* TODO: Grab secrets if we don't have them yet! */
+
+    /* TODO: Fix "pbc" being hardcoded here! */
+    nm_supplicant_interface_p2p_connect(priv->mgmt_iface,
+                                        nm_wifi_p2p_peer_get_supplicant_path(peer),
+                                        "pbc",
+                                        NULL);
+
+    /* Set up a timeout on the connect attempt */
+    if (priv->sup_timeout_id == 0) {
+        priv->sup_timeout_id = g_timeout_add_seconds(45, supplicant_connection_timeout_cb, self);
+    }
+
+    /* We'll get stage3 started when the P2P group has been started */
+    return NM_ACT_STAGE_RETURN_POSTPONE;
+}
+
+/*****************************************************************************/
+
+static void
+emit_signal_p2p_peer_add_remove(NMDeviceWifiP2P *device,
+                                NMWifiP2PPeer *  peer,
+                                gboolean         is_added /* or else is_removed */)
+{
+    nm_dbus_object_emit_signal(NM_DBUS_OBJECT(device),
+                               &interface_info_device_wifi_p2p,
+                               is_added ? &nm_signal_info_wifi_p2p_peer_added
+                                        : &nm_signal_info_wifi_p2p_peer_removed,
+                               "(o)",
+                               nm_dbus_object_get_path(NM_DBUS_OBJECT(peer)));
+}
+
+static void
+peer_add_remove(NMDeviceWifiP2P *self,
+                gboolean         is_adding, /* or else removing */
+                NMWifiP2PPeer *  peer,
+                gboolean         recheck_available_connections)
+{
+    NMDevice *              device = NM_DEVICE(self);
+    NMDeviceWifiP2PPrivate *priv   = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+
+    if (is_adding) {
+        g_object_ref(peer);
+        peer->wifi_device = device;
+        c_list_link_tail(&priv->peers_lst_head, &peer->peers_lst);
+        nm_dbus_object_export(NM_DBUS_OBJECT(peer));
+        _peer_dump(self, LOGL_DEBUG, peer, "added", 0);
+
+        emit_signal_p2p_peer_add_remove(self, peer, TRUE);
+    } else {
+        peer->wifi_device = NULL;
+        c_list_unlink(&peer->peers_lst);
+        _peer_dump(self, LOGL_DEBUG, peer, "removed", 0);
+    }
+
+    _notify(self, PROP_PEERS);
+
+    if (!is_adding) {
+        emit_signal_p2p_peer_add_remove(self, peer, FALSE);
+        nm_dbus_object_clear_and_unexport(&peer);
+    }
+
+    if (is_adding) {
+        /* If we are in prepare state, then we are currently runnign a find
+         * to search for the requested peer. */
+        if (priv->find_peer_timeout_id != 0) {
+            NMConnection *connection;
+
+            nm_assert(nm_device_get_state(device) == NM_DEVICE_STATE_PREPARE);
+
+            connection = nm_device_get_applied_connection(device);
+            nm_assert(NM_IS_CONNECTION(connection));
+
+            peer = nm_wifi_p2p_peers_find_first_compatible(&priv->peers_lst_head, connection);
+            if (peer) {
+                /* A peer for the connection was found, cancel the timeout and go to configure state. */
+                nm_clear_g_source(&priv->find_peer_timeout_id);
+                nm_device_activate_schedule_stage1_device_prepare(device, FALSE);
+            }
+        }
+
+        /* TODO: We may want to re-check auto-activation here, otherwise it will never work. */
+    }
+
+    update_disconnect_on_connection_peer_missing(self);
+}
+
+static void
+remove_all_peers(NMDeviceWifiP2P *self)
+{
+    NMDeviceWifiP2PPrivate *priv = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+    NMWifiP2PPeer *         peer;
+
+    if (c_list_is_empty(&priv->peers_lst_head))
+        return;
+
+    while ((peer = c_list_first_entry(&priv->peers_lst_head, NMWifiP2PPeer, peers_lst)))
+        peer_add_remove(self, FALSE, peer, FALSE);
+
+    nm_device_recheck_available_connections(NM_DEVICE(self));
+}
+
+/*****************************************************************************/
+
+static NMActStageReturn
+act_stage3_ip_config_start(NMDevice *           device,
+                           int                  addr_family,
+                           gpointer *           out_config,
+                           NMDeviceStateReason *out_failure_reason)
+{
+    gboolean      indicate_addressing_running;
+    NMConnection *connection;
+    const char *  method;
+
+    connection = nm_device_get_applied_connection(device);
+
+    method = nm_utils_get_ip_config_method(connection, addr_family);
+
+    if (addr_family == AF_INET)
+        indicate_addressing_running = NM_IN_STRSET(method, NM_SETTING_IP4_CONFIG_METHOD_AUTO);
+    else {
+        indicate_addressing_running = NM_IN_STRSET(method,
+                                                   NM_SETTING_IP6_CONFIG_METHOD_AUTO,
+                                                   NM_SETTING_IP6_CONFIG_METHOD_DHCP);
+    }
+
+    if (indicate_addressing_running)
+        nm_platform_wifi_indicate_addressing_running(nm_device_get_platform(device),
+                                                     nm_device_get_ip_ifindex(device),
+                                                     TRUE);
+
+    return NM_DEVICE_CLASS(nm_device_wifi_p2p_parent_class)
+        ->act_stage3_ip_config_start(device, addr_family, out_config, out_failure_reason);
+}
+
+static void
+deactivate(NMDevice *device)
+{
+    NMDeviceWifiP2P *       self    = NM_DEVICE_WIFI_P2P(device);
+    int                     ifindex = nm_device_get_ip_ifindex(device);
+    NMDeviceWifiP2PPrivate *priv    = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+
+    nm_clear_g_source(&priv->find_peer_timeout_id);
+    nm_clear_g_source(&priv->sup_timeout_id);
+    nm_clear_g_source(&priv->peer_missing_id);
+
+    if (priv->mgmt_iface)
+        nm_supplicant_interface_p2p_cancel_connect(priv->mgmt_iface);
+
+    if (priv->group_iface)
+        nm_supplicant_interface_p2p_disconnect(priv->group_iface);
+
+    /* Clear any critical protocol notification in the Wi-Fi stack */
+    if (ifindex > 0)
+        nm_platform_wifi_indicate_addressing_running(nm_device_get_platform(device),
+                                                     ifindex,
+                                                     FALSE);
+}
+
+static guint32
+get_configured_mtu(NMDevice *device, NMDeviceMtuSource *out_source, gboolean *out_force)
+{
+    *out_source = NM_DEVICE_MTU_SOURCE_NONE;
+    return 0;
+}
+
+static const char *
+get_auto_ip_config_method(NMDevice *device, int addr_family)
+{
+    NMDeviceWifiP2P *       self = NM_DEVICE_WIFI_P2P(device);
+    NMDeviceWifiP2PPrivate *priv = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+
+    /* Override the AUTO method to mean shared if we are group owner. */
+    if (priv->group_iface && nm_supplicant_interface_get_p2p_group_owner(priv->group_iface)) {
+        if (addr_family == AF_INET)
+            return NM_SETTING_IP4_CONFIG_METHOD_SHARED;
+
+        if (addr_family == AF_INET6)
+            return NM_SETTING_IP6_CONFIG_METHOD_SHARED;
+    }
+
+    return NULL;
+}
+
+static gboolean
+unmanaged_on_quit(NMDevice *self)
+{
+    return TRUE;
+}
+
+static void
+supplicant_iface_state_cb(NMSupplicantInterface *iface,
+                          int                    new_state_i,
+                          int                    old_state_i,
+                          int                    disconnect_reason,
+                          gpointer               user_data)
+{
+    NMDeviceWifiP2P *          self      = NM_DEVICE_WIFI_P2P(user_data);
+    NMDevice *                 device    = NM_DEVICE(self);
+    NMSupplicantInterfaceState new_state = new_state_i;
+    NMSupplicantInterfaceState old_state = old_state_i;
+
+    _LOGI(LOGD_DEVICE | LOGD_WIFI,
+          "supplicant management interface state: %s -> %s",
+          nm_supplicant_interface_state_to_string(old_state),
+          nm_supplicant_interface_state_to_string(new_state));
+
+    if (new_state == NM_SUPPLICANT_INTERFACE_STATE_DOWN) {
+        supplicant_interfaces_release(self, TRUE);
+        nm_device_queue_recheck_available(device,
+                                          NM_DEVICE_STATE_REASON_SUPPLICANT_AVAILABLE,
+                                          NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
+        return;
+    }
+
+    if (old_state == NM_SUPPLICANT_INTERFACE_STATE_STARTING) {
+        _LOGD(LOGD_WIFI, "supplicant ready");
+        nm_device_queue_recheck_available(device,
+                                          NM_DEVICE_STATE_REASON_SUPPLICANT_AVAILABLE,
+                                          NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
+        _set_is_waiting_for_supplicant(self, FALSE);
+    }
+}
+
+static void
+supplicant_iface_peer_changed_cb(NMSupplicantInterface *iface,
+                                 NMSupplicantPeerInfo * peer_info,
+                                 gboolean               is_present,
+                                 NMDeviceWifiP2P *      self)
+{
+    NMDeviceWifiP2PPrivate *priv = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+    NMWifiP2PPeer *         found_peer;
+
+    found_peer =
+        nm_wifi_p2p_peers_find_by_supplicant_path(&priv->peers_lst_head, peer_info->peer_path->str);
+
+    if (!is_present) {
+        if (!found_peer)
+            return;
+
+        peer_add_remove(self, FALSE, found_peer, TRUE);
+        goto out;
+    }
+
+    if (found_peer) {
+        if (!nm_wifi_p2p_peer_update_from_properties(found_peer, peer_info))
+            return;
+
+        update_disconnect_on_connection_peer_missing(self);
+        _peer_dump(self, LOGL_DEBUG, found_peer, "updated", 0);
+    } else {
+        gs_unref_object NMWifiP2PPeer *peer = NULL;
+
+        peer = nm_wifi_p2p_peer_new_from_properties(peer_info);
+        peer_add_remove(self, TRUE, peer, TRUE);
+    }
+
+out:
+    schedule_peer_list_dump(self);
+}
+
+static void
+check_group_iface_ready(NMDeviceWifiP2P *self)
+{
+    NMDeviceWifiP2PPrivate *priv = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+
+    if (!priv->group_iface)
+        return;
+
+    if (!nm_supplicant_interface_state_is_operational(
+            nm_supplicant_interface_get_state(priv->group_iface)))
+        return;
+
+    if (!nm_supplicant_interface_get_p2p_group_joined(priv->group_iface))
+        return;
+
+    nm_clear_g_source(&priv->sup_timeout_id);
+    update_disconnect_on_connection_peer_missing(self);
+
+    nm_device_activate_schedule_stage3_ip_config_start(NM_DEVICE(self));
+}
+
+static void
+supplicant_group_iface_is_ready(NMDeviceWifiP2P *self)
+{
+    NMDeviceWifiP2PPrivate *priv = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+
+    _LOGD(LOGD_WIFI, "P2P Group supplicant ready");
+
+    if (!nm_device_set_ip_iface(NM_DEVICE(self),
+                                nm_supplicant_interface_get_ifname(priv->group_iface))) {
+        nm_device_state_changed(NM_DEVICE(self),
+                                NM_DEVICE_STATE_FAILED,
+                                NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
+        return;
+    }
+
+    _set_is_waiting_for_supplicant(self, FALSE);
+    check_group_iface_ready(self);
+}
+
+static void
+supplicant_group_iface_state_cb(NMSupplicantInterface *iface,
+                                int                    new_state_i,
+                                int                    old_state_i,
+                                int                    disconnect_reason,
+                                gpointer               user_data)
+{
+    NMDeviceWifiP2P *          self      = NM_DEVICE_WIFI_P2P(user_data);
+    NMSupplicantInterfaceState new_state = new_state_i;
+    NMSupplicantInterfaceState old_state = old_state_i;
+
+    _LOGI(LOGD_DEVICE | LOGD_WIFI,
+          "P2P Group supplicant interface state: %s -> %s",
+          nm_supplicant_interface_state_to_string(old_state),
+          nm_supplicant_interface_state_to_string(new_state));
+
+    if (new_state == NM_SUPPLICANT_INTERFACE_STATE_DOWN) {
+        supplicant_group_interface_release(self);
+
+        nm_device_state_changed(NM_DEVICE(self),
+                                NM_DEVICE_STATE_DISCONNECTED,
+                                NM_DEVICE_STATE_REASON_SUPPLICANT_DISCONNECT);
+        return;
+    }
+
+    if (old_state == NM_SUPPLICANT_INTERFACE_STATE_STARTING) {
+        supplicant_group_iface_is_ready(self);
+        return;
+    }
+}
+
+static void
+supplicant_group_iface_group_finished_cb(NMSupplicantInterface *iface,
+                                         const char *           iface_path,
+                                         void *                 user_data)
+{
+    NMDeviceWifiP2P *self = NM_DEVICE_WIFI_P2P(user_data);
+
+    supplicant_group_interface_release(self);
+
+    nm_device_state_changed(NM_DEVICE(self),
+                            NM_DEVICE_STATE_DISCONNECTED,
+                            NM_DEVICE_STATE_REASON_SUPPLICANT_DISCONNECT);
+}
+
+static void
+supplicant_iface_group_joined_updated_cb(NMSupplicantInterface *iface,
+                                         GParamSpec *           pspec,
+                                         void *                 user_data)
+{
+    NMDeviceWifiP2P *self = NM_DEVICE_WIFI_P2P(user_data);
+
+    check_group_iface_ready(self);
+}
+
+static void
+supplicant_iface_group_started_cb(NMSupplicantInterface *iface,
+                                  NMSupplicantInterface *group_iface,
+                                  NMDeviceWifiP2P *      self)
+{
+    NMDeviceWifiP2PPrivate *   priv;
+    NMSupplicantInterfaceState state;
+
+    g_return_if_fail(self);
+
+    if (!nm_device_is_activating(NM_DEVICE(self))) {
+        _LOGW(LOGD_DEVICE | LOGD_WIFI,
+              "P2P: WPA supplicant notified a group start but we are not trying to connect! "
+              "Ignoring the event.");
+        return;
+    }
+
+    priv = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+
+    supplicant_group_interface_release(self);
+
+    priv->group_iface = g_object_ref(group_iface);
+
+    /* We need to wait for the interface to be ready and the group
+     * information to be resolved. */
+    g_signal_connect(priv->group_iface,
+                     "notify::" NM_SUPPLICANT_INTERFACE_P2P_GROUP_JOINED,
+                     G_CALLBACK(supplicant_iface_group_joined_updated_cb),
+                     self);
+
+    g_signal_connect(priv->group_iface,
+                     NM_SUPPLICANT_INTERFACE_STATE,
+                     G_CALLBACK(supplicant_group_iface_state_cb),
+                     self);
+
+    g_signal_connect(priv->group_iface,
+                     NM_SUPPLICANT_INTERFACE_GROUP_FINISHED,
+                     G_CALLBACK(supplicant_group_iface_group_finished_cb),
+                     self);
+
+    state = nm_supplicant_interface_get_state(priv->group_iface);
+    if (state == NM_SUPPLICANT_INTERFACE_STATE_STARTING) {
+        _set_is_waiting_for_supplicant(self, TRUE);
+        return;
+    }
+
+    supplicant_group_iface_is_ready(self);
+}
+
+static void
+supplicant_group_interface_release(NMDeviceWifiP2P *self)
+{
+    NMDeviceWifiP2PPrivate *priv = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+
+    if (!priv->group_iface)
+        return;
+
+    g_signal_handlers_disconnect_by_data(priv->group_iface, self);
+
+    nm_supplicant_interface_p2p_disconnect(priv->group_iface);
+
+    g_clear_object(&priv->group_iface);
+}
+
+static void
+supplicant_interfaces_release(NMDeviceWifiP2P *self, gboolean set_is_waiting)
+{
+    NMDeviceWifiP2PPrivate *priv = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+
+    nm_clear_g_source(&priv->peer_dump_id);
+
+    remove_all_peers(self);
+
+    if (priv->mgmt_iface) {
+        _LOGD(LOGD_DEVICE | LOGD_WIFI, "P2P: Releasing WPA supplicant interface.");
+        nm_supplicant_manager_set_wfd_ies(priv->sup_mgr, NULL);
+        g_signal_handlers_disconnect_by_data(priv->mgmt_iface, self);
+        g_clear_object(&priv->mgmt_iface);
+        nm_clear_g_source(&priv->find_peer_timeout_id);
+        nm_clear_g_source(&priv->sup_timeout_id);
+    }
+
+    supplicant_group_interface_release(self);
+
+    if (set_is_waiting)
+        _set_is_waiting_for_supplicant(self, TRUE);
+}
+
+static void
+device_state_changed(NMDevice *          device,
+                     NMDeviceState       new_state,
+                     NMDeviceState       old_state,
+                     NMDeviceStateReason reason)
+{
+    NMDeviceWifiP2P *       self = NM_DEVICE_WIFI_P2P(device);
+    NMDeviceWifiP2PPrivate *priv = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+
+    update_disconnect_on_connection_peer_missing(self);
+
+    if (new_state <= NM_DEVICE_STATE_UNAVAILABLE) {
+        /* Clean up the supplicant interface because in these states the
+         * device cannot be used.
+         * Do not clean up for the UNMANAGED to UNAVAILABLE transition which
+         * will happen during initialization.
+         */
+        if (priv->mgmt_iface && old_state > new_state)
+            supplicant_interfaces_release(self, TRUE);
+
+        /* TODO: More cleanup needed? */
+    }
+
+    switch (new_state) {
+    case NM_DEVICE_STATE_UNMANAGED:
+        break;
+    case NM_DEVICE_STATE_UNAVAILABLE:
+        if (!priv->mgmt_iface
+            || !nm_supplicant_interface_state_is_operational(
+                nm_supplicant_interface_get_state(priv->mgmt_iface)))
+            _set_is_waiting_for_supplicant(self, TRUE);
+        break;
+    case NM_DEVICE_STATE_NEED_AUTH:
+        /* Disconnect? */
+        break;
+    case NM_DEVICE_STATE_IP_CHECK:
+        /* Clear any critical protocol notification in the wifi stack */
+        nm_platform_wifi_indicate_addressing_running(nm_device_get_platform(device),
+                                                     nm_device_get_ip_ifindex(device),
+                                                     FALSE);
+        break;
+    case NM_DEVICE_STATE_ACTIVATED:
+        //activation_success_handler (device);
+        break;
+    case NM_DEVICE_STATE_FAILED:
+        /* Clear any critical protocol notification in the wifi stack.
+         * At this point the IP device may have been removed already. */
+        nm_supplicant_manager_set_wfd_ies(priv->sup_mgr, NULL);
+        if (nm_device_get_ip_ifindex(device) > 0)
+            nm_platform_wifi_indicate_addressing_running(nm_device_get_platform(device),
+                                                         nm_device_get_ip_ifindex(device),
+                                                         FALSE);
+        break;
+    case NM_DEVICE_STATE_DISCONNECTED:
+        nm_supplicant_manager_set_wfd_ies(priv->sup_mgr, NULL);
+        break;
+    default:
+        break;
+    }
+}
+
+static void
+impl_device_wifi_p2p_start_find(NMDBusObject *                     obj,
+                                const NMDBusInterfaceInfoExtended *interface_info,
+                                const NMDBusMethodInfoExtended *   method_info,
+                                GDBusConnection *                  connection,
+                                const char *                       sender,
+                                GDBusMethodInvocation *            invocation,
+                                GVariant *                         parameters)
+{
+    NMDeviceWifiP2P *       self       = NM_DEVICE_WIFI_P2P(obj);
+    NMDeviceWifiP2PPrivate *priv       = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+    gs_unref_variant GVariant *options = NULL;
+    const char *               opts_key;
+    GVariant *                 opts_val;
+    GVariantIter               iter;
+    gint32                     timeout = 30;
+
+    g_variant_get(parameters, "(@a{sv})", &options);
+
+    g_variant_iter_init(&iter, options);
+    while (g_variant_iter_next(&iter, "{&sv}", &opts_key, &opts_val)) {
+        _nm_unused gs_unref_variant GVariant *opts_val_free = opts_val;
+
+        if (nm_streq(opts_key, "timeout")) {
+            if (!g_variant_is_of_type(opts_val, G_VARIANT_TYPE_INT32)) {
+                g_dbus_method_invocation_return_error_literal(
+                    invocation,
+                    NM_DEVICE_ERROR,
+                    NM_DEVICE_ERROR_INVALID_ARGUMENT,
+                    "\"timeout\" must be an integer \"i\"");
+                return;
+            }
+
+            timeout = g_variant_get_int32(opts_val);
+            if (timeout <= 0 || timeout > 600) {
+                g_dbus_method_invocation_return_error_literal(
+                    invocation,
+                    NM_DEVICE_ERROR,
+                    NM_DEVICE_ERROR_NOT_ALLOWED,
+                    "The timeout for a find operation needs to be in the range of 1-600s.");
+                return;
+            }
+
+            continue;
+        }
+
+        g_dbus_method_invocation_return_error(invocation,
+                                              NM_DEVICE_ERROR,
+                                              NM_DEVICE_ERROR_INVALID_ARGUMENT,
+                                              "Unsupported options key \"%s\"",
+                                              opts_key);
+        return;
+    }
+
+    if (!priv->mgmt_iface) {
+        g_dbus_method_invocation_return_error_literal(
+            invocation,
+            NM_DEVICE_ERROR,
+            NM_DEVICE_ERROR_NOT_ACTIVE,
+            "WPA Supplicant management interface is currently unavailable.");
+        return;
+    }
+
+    nm_supplicant_interface_p2p_start_find(priv->mgmt_iface, timeout);
+
+    g_dbus_method_invocation_return_value(invocation, NULL);
+}
+
+static void
+impl_device_wifi_p2p_stop_find(NMDBusObject *                     obj,
+                               const NMDBusInterfaceInfoExtended *interface_info,
+                               const NMDBusMethodInfoExtended *   method_info,
+                               GDBusConnection *                  connection,
+                               const char *                       sender,
+                               GDBusMethodInvocation *            invocation,
+                               GVariant *                         parameters)
+{
+    NMDeviceWifiP2P *       self = NM_DEVICE_WIFI_P2P(obj);
+    NMDeviceWifiP2PPrivate *priv = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+
+    if (!priv->mgmt_iface) {
+        g_dbus_method_invocation_return_error_literal(
+            invocation,
+            NM_DEVICE_ERROR,
+            NM_DEVICE_ERROR_NOT_ACTIVE,
+            "WPA Supplicant management interface is currently unavailable.");
+        return;
+    }
+
+    nm_supplicant_interface_p2p_stop_find(priv->mgmt_iface);
+
+    g_dbus_method_invocation_return_value(invocation, NULL);
+}
+
+/*****************************************************************************/
+
+NMSupplicantInterface *
+nm_device_wifi_p2p_get_mgmt_iface(NMDeviceWifiP2P *self)
+{
+    g_return_val_if_fail(NM_IS_DEVICE_WIFI_P2P(self), NULL);
+
+    return NM_DEVICE_WIFI_P2P_GET_PRIVATE(self)->mgmt_iface;
+}
+
+void
+nm_device_wifi_p2p_set_mgmt_iface(NMDeviceWifiP2P *self, NMSupplicantInterface *iface)
+{
+    NMDeviceWifiP2PPrivate *priv;
+
+    g_return_if_fail(NM_IS_DEVICE_WIFI_P2P(self));
+    g_return_if_fail(!iface || NM_IS_SUPPLICANT_INTERFACE(iface));
+
+    priv = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+
+    if (priv->mgmt_iface == iface)
+        goto done;
+
+    supplicant_interfaces_release(self, FALSE);
+
+    if (!iface)
+        goto done;
+
+    _LOGD(LOGD_DEVICE | LOGD_WIFI,
+          "P2P: WPA supplicant management interface changed to %s.",
+          nm_ref_string_get_str(nm_supplicant_interface_get_object_path(iface)));
+
+    priv->mgmt_iface = g_object_ref(iface);
+
+    g_signal_connect(priv->mgmt_iface,
+                     NM_SUPPLICANT_INTERFACE_STATE,
+                     G_CALLBACK(supplicant_iface_state_cb),
+                     self);
+    g_signal_connect(priv->mgmt_iface,
+                     NM_SUPPLICANT_INTERFACE_PEER_CHANGED,
+                     G_CALLBACK(supplicant_iface_peer_changed_cb),
+                     self);
+    g_signal_connect(priv->mgmt_iface,
+                     NM_SUPPLICANT_INTERFACE_GROUP_STARTED,
+                     G_CALLBACK(supplicant_iface_group_started_cb),
+                     self);
+done:
+    nm_device_queue_recheck_available(NM_DEVICE(self),
+                                      NM_DEVICE_STATE_REASON_SUPPLICANT_AVAILABLE,
+                                      NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
+    _set_is_waiting_for_supplicant(self,
+                                   !priv->mgmt_iface
+                                       || !nm_supplicant_interface_state_is_operational(
+                                           nm_supplicant_interface_get_state(priv->mgmt_iface)));
+}
+
+void
+nm_device_wifi_p2p_remove(NMDeviceWifiP2P *self)
+{
+    g_signal_emit_by_name(self, NM_DEVICE_REMOVED);
+}
+
+/*****************************************************************************/
+
+static const char *
+get_type_description(NMDevice *device)
+{
+    return "wifi-p2p";
+}
+
+/*****************************************************************************/
+
+static const GDBusSignalInfo nm_signal_info_wifi_p2p_peer_added = NM_DEFINE_GDBUS_SIGNAL_INFO_INIT(
+    "PeerAdded",
+    .args = NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("peer", "o"), ), );
+
+static const GDBusSignalInfo nm_signal_info_wifi_p2p_peer_removed =
+    NM_DEFINE_GDBUS_SIGNAL_INFO_INIT(
+        "PeerRemoved",
+        .args = NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("peer", "o"), ), );
+
+static const NMDBusInterfaceInfoExtended interface_info_device_wifi_p2p = {
+    .parent = NM_DEFINE_GDBUS_INTERFACE_INFO_INIT(
+        NM_DBUS_INTERFACE_DEVICE_WIFI_P2P,
+        .methods = NM_DEFINE_GDBUS_METHOD_INFOS(
+            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(
+                NM_DEFINE_GDBUS_METHOD_INFO_INIT(
+                    "StartFind",
+                    .in_args = NM_DEFINE_GDBUS_ARG_INFOS(
+                        NM_DEFINE_GDBUS_ARG_INFO("options", "a{sv}"), ), ),
+                .handle = impl_device_wifi_p2p_start_find, ),
+            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(NM_DEFINE_GDBUS_METHOD_INFO_INIT("StopFind", ),
+                                                .handle = impl_device_wifi_p2p_stop_find, ), ),
+        .signals    = NM_DEFINE_GDBUS_SIGNAL_INFOS(&nm_signal_info_wifi_p2p_peer_added,
+                                                &nm_signal_info_wifi_p2p_peer_removed, ),
+        .properties = NM_DEFINE_GDBUS_PROPERTY_INFOS(
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE("HwAddress", "s", NM_DEVICE_HW_ADDRESS),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE("Peers",
+                                                           "ao",
+                                                           NM_DEVICE_WIFI_P2P_PEERS), ), ),
+    .legacy_property_changed = FALSE,
+};
+
+/*****************************************************************************/
+
+static void
+get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec)
+{
+    NMDeviceWifiP2P *       self = NM_DEVICE_WIFI_P2P(object);
+    NMDeviceWifiP2PPrivate *priv = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+    const char **           list;
+
+    switch (prop_id) {
+    case PROP_PEERS:
+        list = nm_wifi_p2p_peers_get_paths(&priv->peers_lst_head);
+        g_value_take_boxed(value, nm_utils_strv_make_deep_copied(list));
+        break;
+    default:
+        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
+        break;
+    }
+}
+
+/*****************************************************************************/
+
+static void
+nm_device_wifi_p2p_init(NMDeviceWifiP2P *self)
+{
+    NMDeviceWifiP2PPrivate *priv = NM_DEVICE_WIFI_P2P_GET_PRIVATE(self);
+
+    c_list_init(&priv->peers_lst_head);
+
+    priv->sup_mgr = g_object_ref(nm_supplicant_manager_get());
+}
+
+static void
+constructed(GObject *object)
+{
+    NMDeviceWifiP2P *self = NM_DEVICE_WIFI_P2P(object);
+
+    G_OBJECT_CLASS(nm_device_wifi_p2p_parent_class)->constructed(object);
+
+    _set_is_waiting_for_supplicant(self, TRUE);
+}
+
+NMDeviceWifiP2P *
+nm_device_wifi_p2p_new(const char *iface)
+{
+    return g_object_new(NM_TYPE_DEVICE_WIFI_P2P,
+                        NM_DEVICE_IFACE,
+                        iface,
+                        NM_DEVICE_TYPE_DESC,
+                        "802.11 Wi-Fi P2P",
+                        NM_DEVICE_DEVICE_TYPE,
+                        NM_DEVICE_TYPE_WIFI_P2P,
+                        NM_DEVICE_LINK_TYPE,
+                        NM_LINK_TYPE_WIFI,
+                        NM_DEVICE_RFKILL_TYPE,
+                        RFKILL_TYPE_WLAN,
+                        NULL);
+}
+
+static void
+dispose(GObject *object)
+{
+    NMDeviceWifiP2P *       self = NM_DEVICE_WIFI_P2P(object);
+    NMDeviceWifiP2PPrivate *priv = NM_DEVICE_WIFI_P2P_GET_PRIVATE(object);
+
+    g_clear_object(&priv->sup_mgr);
+
+    supplicant_interfaces_release(self, FALSE);
+
+    G_OBJECT_CLASS(nm_device_wifi_p2p_parent_class)->dispose(object);
+}
+
+static void
+finalize(GObject *object)
+{
+    NMDeviceWifiP2P *       peer = NM_DEVICE_WIFI_P2P(object);
+    NMDeviceWifiP2PPrivate *priv = NM_DEVICE_WIFI_P2P_GET_PRIVATE(peer);
+
+    nm_assert(c_list_is_empty(&priv->peers_lst_head));
+
+    G_OBJECT_CLASS(nm_device_wifi_p2p_parent_class)->finalize(object);
+}
+
+static void
+nm_device_wifi_p2p_class_init(NMDeviceWifiP2PClass *klass)
+{
+    GObjectClass *     object_class      = G_OBJECT_CLASS(klass);
+    NMDBusObjectClass *dbus_object_class = NM_DBUS_OBJECT_CLASS(klass);
+    NMDeviceClass *    device_class      = NM_DEVICE_CLASS(klass);
+
+    object_class->constructed  = constructed;
+    object_class->get_property = get_property;
+    object_class->dispose      = dispose;
+    object_class->finalize     = finalize;
+
+    dbus_object_class->interface_infos = NM_DBUS_INTERFACE_INFOS(&interface_info_device_wifi_p2p);
+
+    device_class->connection_type_supported        = NM_SETTING_WIFI_P2P_SETTING_NAME;
+    device_class->connection_type_check_compatible = NM_SETTING_WIFI_P2P_SETTING_NAME;
+    device_class->link_types           = NM_DEVICE_DEFINE_LINK_TYPES(NM_LINK_TYPE_WIFI_P2P);
+    device_class->get_type_description = get_type_description;
+
+    /* Do we need compatibility checking or is the default good enough? */
+    device_class->is_available                = is_available;
+    device_class->check_connection_compatible = check_connection_compatible;
+    device_class->complete_connection         = complete_connection;
+
+    device_class->act_stage1_prepare         = act_stage1_prepare;
+    device_class->act_stage2_config          = act_stage2_config;
+    device_class->get_configured_mtu         = get_configured_mtu;
+    device_class->get_auto_ip_config_method  = get_auto_ip_config_method;
+    device_class->act_stage3_ip_config_start = act_stage3_ip_config_start;
+
+    device_class->deactivate        = deactivate;
+    device_class->unmanaged_on_quit = unmanaged_on_quit;
+
+    device_class->state_changed = device_state_changed;
+
+    obj_properties[PROP_PEERS] = g_param_spec_boxed(NM_DEVICE_WIFI_P2P_PEERS,
+                                                    "",
+                                                    "",
+                                                    G_TYPE_STRV,
+                                                    G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    g_object_class_install_properties(object_class, _PROPERTY_ENUMS_LAST, obj_properties);
+}
diff --git a/src/core/devices/wifi/nm-device-wifi-p2p.h b/src/core/devices/wifi/nm-device-wifi-p2p.h
new file mode 100644
index 00000000..d1aadd8e
--- /dev/null
+++ b/src/core/devices/wifi/nm-device-wifi-p2p.h
@@ -0,0 +1,38 @@
+/* SPDX-License-Identifier: LGPL-2.1-or-later */
+/*
+ * Copyright (C) 2018 Red Hat, Inc.
+ */
+
+#ifndef __NM_DEVICE_WIFI_P2P_H__
+#define __NM_DEVICE_WIFI_P2P_H__
+
+#include "devices/nm-device.h"
+#include "supplicant/nm-supplicant-interface.h"
+
+#define NM_TYPE_DEVICE_WIFI_P2P (nm_device_wifi_p2p_get_type())
+#define NM_DEVICE_WIFI_P2P(obj) \
+    (G_TYPE_CHECK_INSTANCE_CAST((obj), NM_TYPE_DEVICE_WIFI_P2P, NMDeviceWifiP2P))
+#define NM_DEVICE_WIFI_P2P_CLASS(klass) \
+    (G_TYPE_CHECK_CLASS_CAST((klass), NM_TYPE_DEVICE_WIFI_P2P, NMDeviceWifiP2PClass))
+#define NM_IS_DEVICE_WIFI_P2P(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), NM_TYPE_DEVICE_WIFI_P2P))
+#define NM_IS_DEVICE_WIFI_P2P_CLASS(klass) \
+    (G_TYPE_CHECK_CLASS_TYPE((klass), NM_TYPE_DEVICE_WIFI_P2P))
+#define NM_DEVICE_WIFI_P2P_GET_CLASS(obj) \
+    (G_TYPE_INSTANCE_GET_CLASS((obj), NM_TYPE_DEVICE_WIFI_P2P, NMDeviceWifiP2PClass))
+
+#define NM_DEVICE_WIFI_P2P_PEERS  "peers"
+#define NM_DEVICE_WIFI_P2P_GROUPS "groups"
+
+typedef struct _NMDeviceWifiP2P      NMDeviceWifiP2P;
+typedef struct _NMDeviceWifiP2PClass NMDeviceWifiP2PClass;
+
+GType nm_device_wifi_p2p_get_type(void);
+
+NMDeviceWifiP2P *nm_device_wifi_p2p_new(const char *iface);
+
+NMSupplicantInterface *nm_device_wifi_p2p_get_mgmt_iface(NMDeviceWifiP2P *self);
+void nm_device_wifi_p2p_set_mgmt_iface(NMDeviceWifiP2P *self, NMSupplicantInterface *iface);
+
+void nm_device_wifi_p2p_remove(NMDeviceWifiP2P *self);
+
+#endif /* __NM_DEVICE_WIFI_P2P_H__ */
diff --git a/src/core/devices/wifi/nm-device-wifi.c b/src/core/devices/wifi/nm-device-wifi.c
new file mode 100644
index 00000000..042d4887
--- /dev/null
+++ b/src/core/devices/wifi/nm-device-wifi.c
@@ -0,0 +1,3879 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+/*
+ * Copyright (C) 2005 - 2017 Red Hat, Inc.
+ * Copyright (C) 2006 - 2008 Novell, Inc.
+ */
+
+#include "src/core/nm-default-daemon.h"
+
+#include "nm-device-wifi.h"
+
+#include <netinet/in.h>
+#include <unistd.h>
+#include <linux/if_ether.h>
+
+#include "nm-glib-aux/nm-ref-string.h"
+#include "nm-glib-aux/nm-c-list.h"
+#include "nm-device-wifi-p2p.h"
+#include "nm-wifi-ap.h"
+#include "nm-libnm-core-intern/nm-common-macros.h"
+#include "devices/nm-device.h"
+#include "devices/nm-device-private.h"
+#include "nm-dbus-manager.h"
+#include "nm-utils.h"
+#include "NetworkManagerUtils.h"
+#include "nm-act-request.h"
+#include "supplicant/nm-supplicant-manager.h"
+#include "supplicant/nm-supplicant-interface.h"
+#include "supplicant/nm-supplicant-config.h"
+#include "nm-setting-connection.h"
+#include "nm-setting-wireless.h"
+#include "nm-setting-wireless-security.h"
+#include "nm-setting-8021x.h"
+#include "nm-setting-ip4-config.h"
+#include "nm-ip4-config.h"
+#include "nm-setting-ip6-config.h"
+#include "platform/nm-platform.h"
+#include "nm-auth-utils.h"
+#include "settings/nm-settings-connection.h"
+#include "settings/nm-settings.h"
+#include "nm-wifi-utils.h"
+#include "nm-wifi-common.h"
+#include "nm-core-internal.h"
+#include "nm-config.h"
+
+#define _NMLOG_DEVICE_TYPE NMDeviceWifi
+#include "devices/nm-device-logging.h"
+
+#define SCAN_INTERVAL_SEC_MIN  3
+#define SCAN_INTERVAL_SEC_STEP 20
+#define SCAN_INTERVAL_SEC_MAX  120
+
+#define SCAN_EXTRA_DELAY_MSEC 500
+
+#define SCAN_RAND_MAC_ADDRESS_EXPIRE_SEC (5 * 60)
+
+#define SCAN_REQUEST_SSIDS_MAX_NUM      32u
+#define SCAN_REQUEST_SSIDS_MAX_AGE_MSEC (3 * 60 * NM_UTILS_MSEC_PER_SEC)
+
+#define _LOGT_scan(...) _LOGT(LOGD_WIFI_SCAN, "wifi-scan: " __VA_ARGS__)
+
+/*****************************************************************************/
+
+NM_GOBJECT_PROPERTIES_DEFINE(NMDeviceWifi,
+                             PROP_MODE,
+                             PROP_BITRATE,
+                             PROP_ACCESS_POINTS,
+                             PROP_ACTIVE_ACCESS_POINT,
+                             PROP_CAPABILITIES,
+                             PROP_SCANNING,
+                             PROP_LAST_SCAN, );
+
+enum {
+    P2P_DEVICE_CREATED,
+
+    LAST_SIGNAL
+};
+
+static guint signals[LAST_SIGNAL] = {0};
+
+typedef struct {
+    CList       aps_lst_head;
+    GHashTable *aps_idx_by_supplicant_path;
+
+    CList scanning_prohibited_lst_head;
+
+    GCancellable *scan_request_cancellable;
+
+    GSource *scan_request_delay_source;
+
+    NMWifiAP *current_ap;
+
+    GHashTable *scan_request_ssids_hash;
+    CList       scan_request_ssids_lst_head;
+
+    NMActRequestGetSecretsCallId *wifi_secrets_id;
+
+    NMSupplicantManager *        sup_mgr;
+    NMSupplMgrCreateIfaceHandle *sup_create_handle;
+    NMSupplicantInterface *      sup_iface;
+
+    gint64 scan_last_complete_msec;
+    gint64 scan_periodic_next_msec;
+
+    gint64 scan_last_request_started_at_msec;
+
+    guint scan_kickoff_timeout_id;
+
+    guint ap_dump_id;
+
+    guint periodic_update_id;
+
+    guint link_timeout_id;
+    guint reacquire_iface_id;
+    guint wps_timeout_id;
+    guint sup_timeout_id; /* supplicant association timeout */
+
+    NMDeviceWifiCapabilities    capabilities;
+    NMSettingWirelessWakeOnWLan wowlan_restore;
+
+    NMDeviceWifiP2P *p2p_device;
+    NM80211Mode      mode;
+
+    guint32 failed_iface_count;
+    gint32  hw_addr_scan_expire;
+
+    guint32 rate;
+
+    guint8 scan_periodic_interval_sec;
+
+    bool enabled : 1; /* rfkilled or not */
+    bool scan_is_scanning : 1;
+    bool scan_periodic_allowed : 1;
+    bool scan_explicit_allowed : 1;
+    bool scan_explicit_requested : 1;
+    bool ssid_found : 1;
+    bool hidden_probe_scan_warn : 1;
+
+} NMDeviceWifiPrivate;
+
+struct _NMDeviceWifi {
+    NMDevice            parent;
+    NMDeviceWifiPrivate _priv;
+};
+
+struct _NMDeviceWifiClass {
+    NMDeviceClass parent;
+};
+
+/*****************************************************************************/
+
+G_DEFINE_TYPE(NMDeviceWifi, nm_device_wifi, NM_TYPE_DEVICE)
+
+#define NM_DEVICE_WIFI_GET_PRIVATE(self) \
+    _NM_GET_PRIVATE(self, NMDeviceWifi, NM_IS_DEVICE_WIFI, NMDevice)
+
+/*****************************************************************************/
+
+static void supplicant_iface_state_down(NMDeviceWifi *self);
+
+static void cleanup_association_attempt(NMDeviceWifi *self, gboolean disconnect);
+
+static void supplicant_iface_state(NMDeviceWifi *             self,
+                                   NMSupplicantInterfaceState new_state,
+                                   NMSupplicantInterfaceState old_state,
+                                   int                        disconnect_reason,
+                                   gboolean                   is_real_signal);
+
+static void supplicant_iface_state_cb(NMSupplicantInterface *iface,
+                                      int                    new_state_i,
+                                      int                    old_state_i,
+                                      int                    disconnect_reason,
+                                      gpointer               user_data);
+
+static void supplicant_iface_bss_changed_cb(NMSupplicantInterface *iface,
+                                            NMSupplicantBssInfo *  bss_info,
+                                            gboolean               is_present,
+                                            NMDeviceWifi *         self);
+
+static void supplicant_iface_wps_credentials_cb(NMSupplicantInterface *iface,
+                                                GVariant *             credentials,
+                                                NMDeviceWifi *         self);
+
+static void supplicant_iface_notify_current_bss(NMSupplicantInterface *iface,
+                                                GParamSpec *           pspec,
+                                                NMDeviceWifi *         self);
+
+static void supplicant_iface_notify_p2p_available(NMSupplicantInterface *iface,
+                                                  GParamSpec *           pspec,
+                                                  NMDeviceWifi *         self);
+
+static void periodic_update(NMDeviceWifi *self);
+
+static void ap_add_remove(NMDeviceWifi *self,
+                          gboolean      is_adding,
+                          NMWifiAP *    ap,
+                          gboolean      recheck_available_connections);
+
+static void _hw_addr_set_scanning(NMDeviceWifi *self, gboolean do_reset);
+
+static void recheck_p2p_availability(NMDeviceWifi *self);
+
+static void _scan_kickoff(NMDeviceWifi *self);
+
+static gboolean _scan_notify_allowed(NMDeviceWifi *self, NMTernary do_kickoff);
+
+/*****************************************************************************/
+
+typedef struct {
+    GBytes *ssid;
+    CList   lst;
+    gint64  timestamp_msec;
+} ScanRequestSsidData;
+
+static void
+_scan_request_ssids_remove(ScanRequestSsidData *srs_data)
+{
+    c_list_unlink_stale(&srs_data->lst);
+    g_bytes_unref(srs_data->ssid);
+    nm_g_slice_free(srs_data);
+}
+
+static void
+_scan_request_ssids_remove_with_hash(NMDeviceWifiPrivate *priv, ScanRequestSsidData *srs_data)
+{
+    nm_assert(srs_data);
+    nm_assert(nm_g_hash_table_lookup(priv->scan_request_ssids_hash, srs_data) == srs_data);
+    if (!g_hash_table_remove(priv->scan_request_ssids_hash, srs_data))
+        nm_assert_not_reached();
+    _scan_request_ssids_remove(srs_data);
+}
+
+static void
+_scan_request_ssids_remove_all(NMDeviceWifiPrivate *priv,
+                               gint64               cutoff_with_now_msec,
+                               guint                cutoff_at_len)
+{
+    ScanRequestSsidData *srs_data;
+
+    nm_assert((!priv->scan_request_ssids_hash)
+              == c_list_is_empty(&priv->scan_request_ssids_lst_head));
+    if (!priv->scan_request_ssids_hash)
+        return;
+
+    if (cutoff_at_len == 0) {
+        nm_clear_pointer(&priv->scan_request_ssids_hash, g_hash_table_destroy);
+        while (
+            (srs_data =
+                 c_list_first_entry(&priv->scan_request_ssids_lst_head, ScanRequestSsidData, lst)))
+            _scan_request_ssids_remove(srs_data);
+        return;
+    }
+
+    if (cutoff_with_now_msec != 0) {
+        gint64 cutoff_time_msec;
+
+        /* remove all entries that are older than a max-age. */
+        nm_assert(cutoff_with_now_msec > 0);
+        cutoff_time_msec = cutoff_with_now_msec - SCAN_REQUEST_SSIDS_MAX_AGE_MSEC;
+        while (
+            (srs_data =
+                 c_list_last_entry(&priv->scan_request_ssids_lst_head, ScanRequestSsidData, lst))) {
+            if (srs_data->timestamp_msec > cutoff_time_msec)
+                break;
+            _scan_request_ssids_remove_with_hash(priv, srs_data);
+        }
+    }
+
+    if (cutoff_at_len != G_MAXUINT) {
+        guint i;
+
+        /* trim the list to cutoff_at_len elements. */
+        i = nm_g_hash_table_size(priv->scan_request_ssids_hash);
+        for (; i > cutoff_at_len; i--) {
+            ScanRequestSsidData *d;
+
+            d = c_list_last_entry(&priv->scan_request_ssids_lst_head, ScanRequestSsidData, lst);
+            _scan_request_ssids_remove_with_hash(priv, d);
+        }
+    }
+
+    nm_assert(nm_g_hash_table_size(priv->scan_request_ssids_hash) <= SCAN_REQUEST_SSIDS_MAX_NUM);
+    nm_assert(nm_g_hash_table_size(priv->scan_request_ssids_hash)
+              == c_list_length(&priv->scan_request_ssids_lst_head));
+    if (c_list_is_empty(&priv->scan_request_ssids_lst_head))
+        nm_clear_pointer(&priv->scan_request_ssids_hash, g_hash_table_destroy);
+}
+
+static GPtrArray *
+_scan_request_ssids_fetch(NMDeviceWifiPrivate *priv, gint64 now_msec)
+{
+    ScanRequestSsidData *srs_data;
+    GPtrArray *          ssids;
+    guint                len;
+
+    _scan_request_ssids_remove_all(priv, now_msec, G_MAXUINT);
+
+    len = nm_g_hash_table_size(priv->scan_request_ssids_hash);
+    if (len == 0)
+        return NULL;
+
+    ssids = g_ptr_array_new_full(len, (GDestroyNotify) g_bytes_unref);
+    nm_clear_pointer(&priv->scan_request_ssids_hash, g_hash_table_destroy);
+    while ((srs_data =
+                c_list_first_entry(&priv->scan_request_ssids_lst_head, ScanRequestSsidData, lst))) {
+        g_ptr_array_add(ssids, g_steal_pointer(&srs_data->ssid));
+        _scan_request_ssids_remove(srs_data);
+    }
+    return ssids;
+}
+
+static void
+_scan_request_ssids_track(NMDeviceWifiPrivate *priv, const GPtrArray *ssids)
+{
+    CList  old_lst_head;
+    gint64 now_msec;
+    guint  i;
+
+    if (!ssids || ssids->len == 0)
+        return;
+
+    now_msec = nm_utils_get_monotonic_timestamp_msec();
+
+    if (!priv->scan_request_ssids_hash)
+        priv->scan_request_ssids_hash = g_hash_table_new(nm_pgbytes_hash, nm_pgbytes_equal);
+
+    /* Do a little dance. New elements shall keep their order as in @ssids, but all
+     * new elements should be sorted in the list preexisting elements of the list.
+     * First move the old elements away, and splice them back afterwards. */
+    c_list_init(&old_lst_head);
+    c_list_splice(&old_lst_head, &priv->scan_request_ssids_lst_head);
+
+    for (i = 0; i < ssids->len; i++) {
+        GBytes *             ssid = ssids->pdata[i];
+        ScanRequestSsidData *d;
+
+        G_STATIC_ASSERT_EXPR(G_STRUCT_OFFSET(ScanRequestSsidData, ssid) == 0);
+        d = g_hash_table_lookup(priv->scan_request_ssids_hash, &ssid);
+        if (!d) {
+            d  = g_slice_new(ScanRequestSsidData);
+            *d = (ScanRequestSsidData){
+                .lst            = C_LIST_INIT(d->lst),
+                .timestamp_msec = now_msec,
+                .ssid           = g_bytes_ref(ssid),
+            };
+            g_hash_table_add(priv->scan_request_ssids_hash, d);
+        } else
+            d->timestamp_msec = now_msec;
+        c_list_link_tail(&priv->scan_request_ssids_lst_head, &d->lst);
+    }
+
+    c_list_splice(&priv->scan_request_ssids_lst_head, &old_lst_head);
+
+    /* Trim the excess. After our splice with old_lst_head, the list contains the new
+     * elements (from @ssids) at the front (in there original order), followed by older elements. */
+    _scan_request_ssids_remove_all(priv, now_msec, SCAN_REQUEST_SSIDS_MAX_NUM);
+}
+
+/*****************************************************************************/
+
+void
+nm_device_wifi_scanning_prohibited_track(NMDeviceWifi *self,
+                                         gpointer      tag,
+                                         gboolean      temporarily_prohibited)
+{
+    NMDeviceWifiPrivate *priv;
+    NMCListElem *        elem;
+
+    g_return_if_fail(NM_IS_DEVICE_WIFI(self));
+    nm_assert(tag);
+
+    priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    /* We track these with a simple CList. This would be not efficient, if
+     * there would be many users that need to be tracked at the same time (there
+     * aren't). In fact, most of the time there is no NMDeviceOlpcMesh and
+     * nobody tracks itself here. Optimize for that and simplicity. */
+
+    elem = nm_c_list_elem_find_first(&priv->scanning_prohibited_lst_head, iter, iter == tag);
+
+    if (!temporarily_prohibited) {
+        if (!elem)
+            return;
+        nm_c_list_elem_free(elem);
+    } else {
+        if (elem)
+            return;
+        c_list_link_tail(&priv->scanning_prohibited_lst_head, &nm_c_list_elem_new_stale(tag)->lst);
+    }
+
+    _scan_notify_allowed(self, NM_TERNARY_DEFAULT);
+}
+
+/*****************************************************************************/
+
+static void
+_ap_dump(NMDeviceWifi *  self,
+         NMLogLevel      log_level,
+         const NMWifiAP *ap,
+         const char *    prefix,
+         gint64          now_msec)
+{
+    char buf[1024];
+
+    buf[0] = '\0';
+    _NMLOG(log_level,
+           LOGD_WIFI_SCAN,
+           "wifi-ap: %-7s %s",
+           prefix,
+           nm_wifi_ap_to_string(ap, buf, sizeof(buf), now_msec));
+}
+
+gboolean
+nm_device_wifi_get_scanning(NMDeviceWifi *self)
+{
+    g_return_val_if_fail(NM_IS_DEVICE_WIFI(self), FALSE);
+
+    return NM_DEVICE_WIFI_GET_PRIVATE(self)->scan_is_scanning;
+}
+
+static gboolean
+_scan_is_scanning_eval(NMDeviceWifiPrivate *priv)
+{
+    return priv->scan_request_cancellable || priv->scan_request_delay_source
+           || (priv->sup_iface && nm_supplicant_interface_get_scanning(priv->sup_iface));
+}
+
+static gboolean
+_scan_notify_is_scanning(NMDeviceWifi *self)
+{
+    NMDeviceWifiPrivate *priv              = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    gboolean             last_scan_changed = FALSE;
+    NMDeviceState        state;
+    gboolean             scanning;
+
+    scanning = _scan_is_scanning_eval(priv);
+    if (scanning == priv->scan_is_scanning)
+        return FALSE;
+
+    priv->scan_is_scanning = scanning;
+
+    if (!scanning || priv->scan_last_complete_msec == 0) {
+        last_scan_changed             = TRUE;
+        priv->scan_last_complete_msec = nm_utils_get_monotonic_timestamp_msec();
+    }
+
+    _LOGD(LOGD_WIFI,
+          "wifi-scan: scanning-state: %s%s",
+          scanning ? "scanning" : "idle",
+          last_scan_changed ? " (notify last-scan)" : "");
+
+    state = nm_device_get_state(NM_DEVICE(self));
+
+    if (scanning) {
+        /* while the device is activating/activated, we don't need the pending
+         * action. The pending action exists to delay startup complete, while
+         * activating that is already achieved via other means. */
+        if (state <= NM_DEVICE_STATE_DISCONNECTED || state > NM_DEVICE_STATE_ACTIVATED)
+            nm_device_add_pending_action(NM_DEVICE(self), NM_PENDING_ACTION_WIFI_SCAN, FALSE);
+    }
+
+    nm_gobject_notify_together(self, PROP_SCANNING, last_scan_changed ? PROP_LAST_SCAN : PROP_0);
+
+    _scan_kickoff(self);
+
+    if (!_scan_is_scanning_eval(priv)) {
+        if (state <= NM_DEVICE_STATE_DISCONNECTED || state > NM_DEVICE_STATE_ACTIVATED)
+            nm_device_emit_recheck_auto_activate(NM_DEVICE(self));
+        nm_device_remove_pending_action(NM_DEVICE(self), NM_PENDING_ACTION_WIFI_SCAN, FALSE);
+    }
+
+    return TRUE;
+}
+
+static gboolean
+_scan_notify_allowed(NMDeviceWifi *self, NMTernary do_kickoff)
+{
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    gboolean             explicit_allowed;
+    gboolean             periodic_allowed;
+    NMDeviceState        state;
+    gboolean             changed = FALSE;
+
+    state = nm_device_get_state(NM_DEVICE(self));
+
+    explicit_allowed = FALSE;
+    periodic_allowed = FALSE;
+
+    if (!c_list_is_empty(&priv->scanning_prohibited_lst_head)) {
+        /* something prohibits scanning. */
+    } else if (NM_IN_SET(priv->mode, NM_802_11_MODE_ADHOC, NM_802_11_MODE_AP)) {
+        /* Don't scan when a an AP or Ad-Hoc connection is active as it will
+         * disrupt connected clients or peers. */
+    } else if (NM_IN_SET(state, NM_DEVICE_STATE_DISCONNECTED, NM_DEVICE_STATE_FAILED)) {
+        /* Can always scan when disconnected */
+        explicit_allowed = TRUE;
+        periodic_allowed = TRUE;
+    } else if (NM_IN_SET(state, NM_DEVICE_STATE_ACTIVATED)) {
+        /* Prohibit periodic scans when connected; we ask the supplicant to
+         * background scan for us, unless the connection is locked to a specific
+         * BSSID (in which case scanning is effectively disabled). */
+        periodic_allowed = FALSE;
+
+        /* Prohibit scans if the supplicant is busy */
+        if (priv->sup_iface) {
+            explicit_allowed = !NM_IN_SET(nm_supplicant_interface_get_state(priv->sup_iface),
+                                          NM_SUPPLICANT_INTERFACE_STATE_ASSOCIATING,
+                                          NM_SUPPLICANT_INTERFACE_STATE_ASSOCIATED,
+                                          NM_SUPPLICANT_INTERFACE_STATE_4WAY_HANDSHAKE,
+                                          NM_SUPPLICANT_INTERFACE_STATE_GROUP_HANDSHAKE);
+        } else
+            explicit_allowed = FALSE;
+    }
+
+    if (explicit_allowed != priv->scan_explicit_allowed
+        || periodic_allowed != priv->scan_periodic_allowed) {
+        priv->scan_periodic_allowed = periodic_allowed;
+        priv->scan_explicit_allowed = explicit_allowed;
+        _LOGT_scan("scan-periodic-allowed=%d, scan-explicit-allowed=%d",
+                   periodic_allowed,
+                   explicit_allowed);
+        changed = TRUE;
+    }
+
+    if (do_kickoff == NM_TERNARY_TRUE || (do_kickoff == NM_TERNARY_DEFAULT && changed))
+        _scan_kickoff(self);
+
+    return changed;
+}
+
+static void
+supplicant_iface_notify_scanning_cb(NMSupplicantInterface *iface,
+                                    GParamSpec *           pspec,
+                                    NMDeviceWifi *         self)
+{
+    _scan_notify_is_scanning(self);
+}
+
+static gboolean
+unmanaged_on_quit(NMDevice *self)
+{
+    /* Wi-Fi devices cannot be assumed and are always taken down.
+     * However, also when being disconnected, we scan and thus
+     * set the MAC address to a random value.
+     *
+     * We must restore the original MAC address when quitting, thus
+     * signal to unmanage the device. */
+    return TRUE;
+}
+
+static void
+supplicant_interface_acquire_cb(NMSupplicantManager *        supplicant_manager,
+                                NMSupplMgrCreateIfaceHandle *handle,
+                                NMSupplicantInterface *      iface,
+                                GError *                     error,
+                                gpointer                     user_data)
+{
+    NMDeviceWifi *       self = user_data;
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    if (nm_utils_error_is_cancelled(error))
+        return;
+
+    nm_assert(priv->sup_create_handle == handle);
+
+    priv->sup_create_handle = NULL;
+
+    if (error) {
+        _LOGE(LOGD_WIFI, "Couldn't initialize supplicant interface: %s", error->message);
+        supplicant_iface_state_down(self);
+        nm_device_remove_pending_action(NM_DEVICE(self),
+                                        NM_PENDING_ACTION_WAITING_FOR_SUPPLICANT,
+                                        TRUE);
+        return;
+    }
+
+    priv->sup_iface = g_object_ref(iface);
+
+    g_signal_connect(priv->sup_iface,
+                     NM_SUPPLICANT_INTERFACE_STATE,
+                     G_CALLBACK(supplicant_iface_state_cb),
+                     self);
+    g_signal_connect(priv->sup_iface,
+                     NM_SUPPLICANT_INTERFACE_BSS_CHANGED,
+                     G_CALLBACK(supplicant_iface_bss_changed_cb),
+                     self);
+    g_signal_connect(priv->sup_iface,
+                     NM_SUPPLICANT_INTERFACE_WPS_CREDENTIALS,
+                     G_CALLBACK(supplicant_iface_wps_credentials_cb),
+                     self);
+    g_signal_connect(priv->sup_iface,
+                     "notify::" NM_SUPPLICANT_INTERFACE_SCANNING,
+                     G_CALLBACK(supplicant_iface_notify_scanning_cb),
+                     self);
+    g_signal_connect(priv->sup_iface,
+                     "notify::" NM_SUPPLICANT_INTERFACE_CURRENT_BSS,
+                     G_CALLBACK(supplicant_iface_notify_current_bss),
+                     self);
+    g_signal_connect(priv->sup_iface,
+                     "notify::" NM_SUPPLICANT_INTERFACE_P2P_AVAILABLE,
+                     G_CALLBACK(supplicant_iface_notify_p2p_available),
+                     self);
+
+    _scan_notify_is_scanning(self);
+
+    if (nm_supplicant_interface_get_state(priv->sup_iface)
+        != NM_SUPPLICANT_INTERFACE_STATE_STARTING) {
+        /* fake an initial state change. */
+        supplicant_iface_state(user_data,
+                               NM_SUPPLICANT_INTERFACE_STATE_STARTING,
+                               nm_supplicant_interface_get_state(priv->sup_iface),
+                               0,
+                               FALSE);
+    }
+}
+
+static void
+supplicant_interface_acquire(NMDeviceWifi *self)
+{
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    nm_assert(!priv->sup_iface);
+    nm_assert(!priv->sup_create_handle);
+
+    priv->sup_create_handle =
+        nm_supplicant_manager_create_interface(priv->sup_mgr,
+                                               nm_device_get_ifindex(NM_DEVICE(self)),
+                                               NM_SUPPLICANT_DRIVER_WIRELESS,
+                                               supplicant_interface_acquire_cb,
+                                               self);
+    nm_device_add_pending_action(NM_DEVICE(self), NM_PENDING_ACTION_WAITING_FOR_SUPPLICANT, TRUE);
+}
+
+static void
+supplicant_interface_release(NMDeviceWifi *self)
+{
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    if (nm_clear_pointer(&priv->sup_create_handle, nm_supplicant_manager_create_interface_cancel))
+        nm_device_remove_pending_action(NM_DEVICE(self),
+                                        NM_PENDING_ACTION_WAITING_FOR_SUPPLICANT,
+                                        TRUE);
+
+    nm_clear_g_source(&priv->scan_kickoff_timeout_id);
+    nm_clear_g_source_inst(&priv->scan_request_delay_source);
+    nm_clear_g_cancellable(&priv->scan_request_cancellable);
+
+    _scan_request_ssids_remove_all(priv, 0, 0);
+
+    priv->scan_periodic_interval_sec = 0;
+    priv->scan_periodic_next_msec    = 0;
+
+    nm_clear_g_source(&priv->ap_dump_id);
+
+    if (priv->sup_iface) {
+        /* Clear supplicant interface signal handlers */
+        g_signal_handlers_disconnect_by_data(priv->sup_iface, self);
+
+        /* Tell the supplicant to disconnect from the current AP */
+        nm_supplicant_interface_disconnect(priv->sup_iface);
+
+        g_clear_object(&priv->sup_iface);
+    }
+
+    if (priv->p2p_device) {
+        /* Signal to P2P device to also release its reference */
+        nm_device_wifi_p2p_set_mgmt_iface(priv->p2p_device, NULL);
+    }
+
+    _scan_notify_is_scanning(self);
+}
+
+static void
+update_seen_bssids_cache(NMDeviceWifi *self, NMWifiAP *ap)
+{
+    g_return_if_fail(NM_IS_DEVICE_WIFI(self));
+
+    if (ap == NULL)
+        return;
+
+    /* Don't cache the BSSID for Ad-Hoc APs */
+    if (nm_wifi_ap_get_mode(ap) != NM_802_11_MODE_INFRA)
+        return;
+
+    if (nm_device_get_state(NM_DEVICE(self)) == NM_DEVICE_STATE_ACTIVATED
+        && nm_device_has_unmodified_applied_connection(NM_DEVICE(self),
+                                                       NM_SETTING_COMPARE_FLAG_NONE)) {
+        nm_settings_connection_add_seen_bssid(nm_device_get_settings_connection(NM_DEVICE(self)),
+                                              nm_wifi_ap_get_address(ap));
+    }
+}
+
+static void
+set_current_ap(NMDeviceWifi *self, NMWifiAP *new_ap, gboolean recheck_available_connections)
+{
+    NMDeviceWifiPrivate *priv;
+    NMWifiAP *           old_ap;
+
+    g_return_if_fail(NM_IS_DEVICE_WIFI(self));
+
+    priv   = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    old_ap = priv->current_ap;
+
+    if (old_ap == new_ap)
+        return;
+
+    if (new_ap) {
+        priv->current_ap = g_object_ref(new_ap);
+
+        /* Update seen BSSIDs cache */
+        update_seen_bssids_cache(self, priv->current_ap);
+    } else
+        priv->current_ap = NULL;
+
+    if (old_ap) {
+        NM80211Mode mode = nm_wifi_ap_get_mode(old_ap);
+
+        /* Remove any AP from the internal list if it was created by NM or isn't known to the supplicant */
+        if (NM_IN_SET(mode, NM_802_11_MODE_ADHOC, NM_802_11_MODE_AP) || nm_wifi_ap_get_fake(old_ap))
+            ap_add_remove(self, FALSE, old_ap, recheck_available_connections);
+        g_object_unref(old_ap);
+    }
+
+    _notify(self, PROP_ACTIVE_ACCESS_POINT);
+}
+
+static void
+periodic_update(NMDeviceWifi *self)
+{
+    NMDeviceWifiPrivate *priv;
+    int                  ifindex;
+    guint32              new_rate;
+    int                  percent;
+
+    if (nm_device_get_state(NM_DEVICE(self)) != NM_DEVICE_STATE_ACTIVATED) {
+        /* BSSID and signal strength have meaningful values only if the device
+         * is activated and not scanning.
+         */
+        return;
+    }
+
+    priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    if (!nm_supplicant_interface_state_is_associated(
+            nm_supplicant_interface_get_state(priv->sup_iface))
+        || nm_supplicant_interface_get_scanning(priv->sup_iface)) {
+        /* Only update current AP if we're actually talking to something, otherwise
+         * assume the old one (if any) is still valid until we're told otherwise or
+         * the connection fails.
+         */
+        return;
+    }
+
+    if (priv->mode == NM_802_11_MODE_AP) {
+        /* In AP mode we currently have nothing to do. */
+        return;
+    }
+
+    ifindex = nm_device_get_ifindex(NM_DEVICE(self));
+    if (ifindex <= 0)
+        g_return_if_reached();
+
+    if (priv->current_ap
+        && nm_platform_wifi_get_station(nm_device_get_platform(NM_DEVICE(self)),
+                                        ifindex,
+                                        NULL,
+                                        &percent,
+                                        &new_rate)) {
+        if (nm_wifi_ap_set_strength(priv->current_ap, (gint8) percent)) {
+#if NM_MORE_LOGGING
+            _ap_dump(self, LOGL_TRACE, priv->current_ap, "updated", 0);
+#endif
+        }
+
+        if (new_rate != priv->rate) {
+            priv->rate = new_rate;
+            _notify(self, PROP_BITRATE);
+        }
+    }
+}
+
+static gboolean
+periodic_update_cb(gpointer user_data)
+{
+    periodic_update(user_data);
+    return TRUE;
+}
+
+static void
+ap_add_remove(NMDeviceWifi *self,
+              gboolean      is_adding, /* or else removing */
+              NMWifiAP *    ap,
+              gboolean      recheck_available_connections)
+{
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    if (is_adding) {
+        g_object_ref(ap);
+        ap->wifi_device = NM_DEVICE(self);
+        c_list_link_tail(&priv->aps_lst_head, &ap->aps_lst);
+        if (!g_hash_table_insert(priv->aps_idx_by_supplicant_path,
+                                 nm_wifi_ap_get_supplicant_path(ap),
+                                 ap))
+            nm_assert_not_reached();
+        nm_dbus_object_export(NM_DBUS_OBJECT(ap));
+        _ap_dump(self, LOGL_DEBUG, ap, "added", 0);
+        nm_device_wifi_emit_signal_access_point(NM_DEVICE(self), ap, TRUE);
+    } else {
+        ap->wifi_device = NULL;
+        c_list_unlink(&ap->aps_lst);
+        if (!g_hash_table_remove(priv->aps_idx_by_supplicant_path,
+                                 nm_wifi_ap_get_supplicant_path(ap)))
+            nm_assert_not_reached();
+        _ap_dump(self, LOGL_DEBUG, ap, "removed", 0);
+    }
+
+    _notify(self, PROP_ACCESS_POINTS);
+
+    if (!is_adding) {
+        nm_device_wifi_emit_signal_access_point(NM_DEVICE(self), ap, FALSE);
+        nm_dbus_object_clear_and_unexport(&ap);
+    }
+
+    nm_device_emit_recheck_auto_activate(NM_DEVICE(self));
+    if (recheck_available_connections)
+        nm_device_recheck_available_connections(NM_DEVICE(self));
+}
+
+static void
+remove_all_aps(NMDeviceWifi *self)
+{
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    NMWifiAP *           ap;
+
+    if (c_list_is_empty(&priv->aps_lst_head))
+        return;
+
+    set_current_ap(self, NULL, FALSE);
+
+    while ((ap = c_list_first_entry(&priv->aps_lst_head, NMWifiAP, aps_lst)))
+        ap_add_remove(self, FALSE, ap, FALSE);
+
+    nm_device_recheck_available_connections(NM_DEVICE(self));
+}
+
+static gboolean
+wake_on_wlan_restore(NMDeviceWifi *self)
+{
+    NMDeviceWifiPrivate *       priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    NMSettingWirelessWakeOnWLan w;
+
+    w = priv->wowlan_restore;
+    if (w == NM_SETTING_WIRELESS_WAKE_ON_WLAN_IGNORE)
+        return TRUE;
+
+    priv->wowlan_restore = NM_SETTING_WIRELESS_WAKE_ON_WLAN_IGNORE;
+    return nm_platform_wifi_set_wake_on_wlan(NM_PLATFORM_GET,
+                                             nm_device_get_ifindex(NM_DEVICE(self)),
+                                             w);
+}
+
+static void
+disconnect_cb(NMSupplicantInterface *iface, GError *error, gpointer user_data)
+{
+    gs_unref_object NMDeviceWifi *self = NULL;
+    NMDeviceDeactivateCallback    callback;
+    gpointer                      callback_user_data;
+
+    nm_utils_user_data_unpack(user_data, &self, &callback, &callback_user_data);
+
+    /* error will be freed by sup_iface */
+    callback(NM_DEVICE(self), error, callback_user_data);
+}
+
+static void
+disconnect_cb_on_idle(gpointer user_data, GCancellable *cancellable)
+{
+    gs_unref_object NMDeviceWifi *self = NULL;
+    NMDeviceDeactivateCallback    callback;
+    gpointer                      callback_user_data;
+    gs_free_error GError *cancelled_error = NULL;
+
+    nm_utils_user_data_unpack(user_data, &self, &callback, &callback_user_data);
+
+    g_cancellable_set_error_if_cancelled(cancellable, &cancelled_error);
+    callback(NM_DEVICE(self), cancelled_error, callback_user_data);
+}
+
+static void
+deactivate_async(NMDevice *                 device,
+                 GCancellable *             cancellable,
+                 NMDeviceDeactivateCallback callback,
+                 gpointer                   callback_user_data)
+{
+    NMDeviceWifi *       self = NM_DEVICE_WIFI(device);
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    gpointer             user_data;
+
+    nm_assert(G_IS_CANCELLABLE(cancellable));
+    nm_assert(callback);
+
+    user_data = nm_utils_user_data_pack(g_object_ref(self), callback, callback_user_data);
+    if (!priv->sup_iface) {
+        nm_utils_invoke_on_idle(cancellable, disconnect_cb_on_idle, user_data);
+        return;
+    }
+
+    cleanup_association_attempt(self, FALSE);
+
+    nm_supplicant_interface_disconnect_async(priv->sup_iface,
+                                             cancellable,
+                                             disconnect_cb,
+                                             user_data);
+}
+
+static void
+deactivate(NMDevice *device)
+{
+    NMDeviceWifi *       self    = NM_DEVICE_WIFI(device);
+    NMDeviceWifiPrivate *priv    = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    int                  ifindex = nm_device_get_ifindex(device);
+
+    nm_clear_g_source(&priv->periodic_update_id);
+
+    cleanup_association_attempt(self, TRUE);
+
+    priv->rate = 0;
+
+    set_current_ap(self, NULL, TRUE);
+
+    if (!wake_on_wlan_restore(self))
+        _LOGW(LOGD_DEVICE | LOGD_WIFI, "Cannot unconfigure WoWLAN.");
+
+    /* Clear any critical protocol notification in the Wi-Fi stack */
+    nm_platform_wifi_indicate_addressing_running(nm_device_get_platform(device), ifindex, FALSE);
+
+    /* Ensure we're in infrastructure mode after deactivation; some devices
+     * (usually older ones) don't scan well in adhoc mode.
+     */
+    if (nm_platform_wifi_get_mode(nm_device_get_platform(device), ifindex)
+        != NM_802_11_MODE_INFRA) {
+        nm_device_take_down(NM_DEVICE(self), TRUE);
+        nm_platform_wifi_set_mode(nm_device_get_platform(device), ifindex, NM_802_11_MODE_INFRA);
+        nm_device_bring_up(NM_DEVICE(self), TRUE, NULL);
+    }
+
+    if (priv->mode != NM_802_11_MODE_INFRA) {
+        priv->mode = NM_802_11_MODE_INFRA;
+        _notify(self, PROP_MODE);
+    }
+
+    _scan_notify_allowed(self, NM_TERNARY_TRUE);
+}
+
+static void
+deactivate_reset_hw_addr(NMDevice *device)
+{
+    _hw_addr_set_scanning((NMDeviceWifi *) device, TRUE);
+}
+
+static gboolean
+check_connection_compatible(NMDevice *device, NMConnection *connection, GError **error)
+{
+    NMDeviceWifi *       self = NM_DEVICE_WIFI(device);
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    NMSettingWireless *  s_wireless;
+    const char *         mac;
+    const char *const *  mac_blacklist;
+    int                  i;
+    const char *         mode;
+    const char *         perm_hw_addr;
+
+    if (!NM_DEVICE_CLASS(nm_device_wifi_parent_class)
+             ->check_connection_compatible(device, connection, error))
+        return FALSE;
+
+    s_wireless = nm_connection_get_setting_wireless(connection);
+
+    perm_hw_addr = nm_device_get_permanent_hw_address(device);
+    mac          = nm_setting_wireless_get_mac_address(s_wireless);
+    if (perm_hw_addr) {
+        if (mac && !nm_utils_hwaddr_matches(mac, -1, perm_hw_addr, -1)) {
+            nm_utils_error_set_literal(error,
+                                       NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
+                                       "device MAC address does not match the profile");
+            return FALSE;
+        }
+
+        /* Check for MAC address blacklist */
+        mac_blacklist = nm_setting_wireless_get_mac_address_blacklist(s_wireless);
+        for (i = 0; mac_blacklist[i]; i++) {
+            if (!nm_utils_hwaddr_valid(mac_blacklist[i], ETH_ALEN)) {
+                g_warn_if_reached();
+                return FALSE;
+            }
+
+            if (nm_utils_hwaddr_matches(mac_blacklist[i], -1, perm_hw_addr, -1)) {
+                nm_utils_error_set_literal(error,
+                                           NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
+                                           "MAC address blacklisted");
+                return FALSE;
+            }
+        }
+    } else if (mac) {
+        nm_utils_error_set_literal(error,
+                                   NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
+                                   "device has no valid MAC address as required by profile");
+        return FALSE;
+    }
+
+    /* Early exit if supplicant or device doesn't support requested mode */
+    mode = nm_setting_wireless_get_mode(s_wireless);
+    if (g_strcmp0(mode, NM_SETTING_WIRELESS_MODE_ADHOC) == 0) {
+        if (!(priv->capabilities & NM_WIFI_DEVICE_CAP_ADHOC)) {
+            nm_utils_error_set_literal(error,
+                                       NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
+                                       "the device does not support Ad-Hoc networks");
+            return FALSE;
+        }
+    } else if (g_strcmp0(mode, NM_SETTING_WIRELESS_MODE_AP) == 0) {
+        if (!(priv->capabilities & NM_WIFI_DEVICE_CAP_AP)) {
+            nm_utils_error_set_literal(error,
+                                       NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
+                                       "the device does not support Access Point mode");
+            return FALSE;
+        }
+
+        if (priv->sup_iface) {
+            if (nm_supplicant_interface_get_capability(priv->sup_iface, NM_SUPPL_CAP_TYPE_AP)
+                == NM_TERNARY_FALSE) {
+                nm_utils_error_set_literal(error,
+                                           NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
+                                           "wpa_supplicant does not support Access Point mode");
+                return FALSE;
+            }
+        }
+    } else if (g_strcmp0(mode, NM_SETTING_WIRELESS_MODE_MESH) == 0) {
+        if (!(priv->capabilities & NM_WIFI_DEVICE_CAP_MESH)) {
+            nm_utils_error_set_literal(error,
+                                       NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
+                                       "the device does not support Mesh mode");
+            return FALSE;
+        }
+
+        if (priv->sup_iface) {
+            if (nm_supplicant_interface_get_capability(priv->sup_iface, NM_SUPPL_CAP_TYPE_MESH)
+                == NM_TERNARY_FALSE) {
+                nm_utils_error_set_literal(error,
+                                           NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
+                                           "wpa_supplicant does not support Mesh mode");
+                return FALSE;
+            }
+        }
+    }
+
+    // FIXME: check channel/freq/band against bands the hardware supports
+    // FIXME: check encryption against device capabilities
+    // FIXME: check bitrate against device capabilities
+
+    return TRUE;
+}
+
+static gboolean
+check_connection_available(NMDevice *                     device,
+                           NMConnection *                 connection,
+                           NMDeviceCheckConAvailableFlags flags,
+                           const char *                   specific_object,
+                           GError **                      error)
+{
+    NMDeviceWifi *       self = NM_DEVICE_WIFI(device);
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    NMSettingWireless *  s_wifi;
+    const char *         mode;
+
+    s_wifi = nm_connection_get_setting_wireless(connection);
+    g_return_val_if_fail(s_wifi, FALSE);
+
+    /* a connection that is available for a certain @specific_object, MUST
+     * also be available in general (without @specific_object). */
+
+    if (specific_object) {
+        NMWifiAP *ap;
+
+        ap = nm_wifi_ap_lookup_for_device(NM_DEVICE(self), specific_object);
+        if (!ap) {
+            nm_utils_error_set_literal(error,
+                                       NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
+                                       "requested access point not found");
+            return FALSE;
+        }
+        if (!nm_wifi_ap_check_compatible(ap, connection)) {
+            nm_utils_error_set_literal(error,
+                                       NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
+                                       "requested access point is not compatible with profile");
+            return FALSE;
+        }
+        return TRUE;
+    }
+
+    /* Ad-Hoc, AP and Mesh connections are always available because they may be
+     * started at any time.
+     */
+    mode = nm_setting_wireless_get_mode(s_wifi);
+    if (g_strcmp0(mode, NM_SETTING_WIRELESS_MODE_ADHOC) == 0
+        || g_strcmp0(mode, NM_SETTING_WIRELESS_MODE_AP) == 0
+        || g_strcmp0(mode, NM_SETTING_WIRELESS_MODE_MESH) == 0)
+        return TRUE;
+
+    /* Hidden SSIDs obviously don't always appear in the scan list either.
+     *
+     * For an explicit user-activation-request, a connection is considered
+     * available because for hidden Wi-Fi, clients didn't consistently
+     * set the 'hidden' property to indicate hidden SSID networks.  If
+     * activating but the network isn't available let the device recheck
+     * availability.
+     */
+    if (nm_setting_wireless_get_hidden(s_wifi)
+        || NM_FLAGS_HAS(flags, _NM_DEVICE_CHECK_CON_AVAILABLE_FOR_USER_REQUEST_IGNORE_AP))
+        return TRUE;
+
+    if (!nm_wifi_aps_find_first_compatible(&priv->aps_lst_head, connection)) {
+        nm_utils_error_set_literal(error,
+                                   NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
+                                   "no compatible access point found");
+        return FALSE;
+    }
+
+    return TRUE;
+}
+
+static gboolean
+complete_connection(NMDevice *           device,
+                    NMConnection *       connection,
+                    const char *         specific_object,
+                    NMConnection *const *existing_connections,
+                    GError **            error)
+{
+    NMDeviceWifi *       self = NM_DEVICE_WIFI(device);
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    NMSettingWireless *  s_wifi;
+    gs_free char *       ssid_utf8 = NULL;
+    NMWifiAP *           ap;
+    GBytes *             ssid         = NULL;
+    GBytes *             setting_ssid = NULL;
+    gboolean             hidden       = FALSE;
+    const char *         mode;
+
+    s_wifi = nm_connection_get_setting_wireless(connection);
+
+    mode = s_wifi ? nm_setting_wireless_get_mode(s_wifi) : NULL;
+
+    if (!specific_object) {
+        /* If not given a specific object, we need at minimum an SSID */
+        if (!s_wifi) {
+            g_set_error_literal(error,
+                                NM_DEVICE_ERROR,
+                                NM_DEVICE_ERROR_INVALID_CONNECTION,
+                                "A 'wireless' setting is required if no AP path was given.");
+            return FALSE;
+        }
+
+        setting_ssid = nm_setting_wireless_get_ssid(s_wifi);
+        if (!setting_ssid || g_bytes_get_size(setting_ssid) == 0) {
+            g_set_error_literal(
+                error,
+                NM_DEVICE_ERROR,
+                NM_DEVICE_ERROR_INVALID_CONNECTION,
+                "A 'wireless' setting with a valid SSID is required if no AP path was given.");
+            return FALSE;
+        }
+
+        if (!nm_streq0(mode, NM_SETTING_WIRELESS_MODE_AP)) {
+            /* Find a compatible AP in the scan list */
+            ap = nm_wifi_aps_find_first_compatible(&priv->aps_lst_head, connection);
+
+            /* If we still don't have an AP, then the WiFI settings needs to be
+             * fully specified by the client.  Might not be able to find an AP
+             * if the network isn't broadcasting the SSID for example.
+             */
+            if (!ap) {
+                if (!nm_setting_verify(NM_SETTING(s_wifi), connection, error))
+                    return FALSE;
+
+                hidden = TRUE;
+            }
+        } else {
+            if (!nm_setting_verify(NM_SETTING(s_wifi), connection, error))
+                return FALSE;
+            ap = NULL;
+        }
+    } else if (nm_streq0(mode, NM_SETTING_WIRELESS_MODE_AP)) {
+        if (!nm_setting_verify(NM_SETTING(s_wifi), connection, error))
+            return FALSE;
+        ap = NULL;
+    } else {
+        ap = nm_wifi_ap_lookup_for_device(NM_DEVICE(self), specific_object);
+        if (!ap) {
+            g_set_error(error,
+                        NM_DEVICE_ERROR,
+                        NM_DEVICE_ERROR_SPECIFIC_OBJECT_NOT_FOUND,
+                        "The access point %s was not in the scan list.",
+                        specific_object);
+            return FALSE;
+        }
+    }
+
+    /* Add a wifi setting if one doesn't exist yet */
+    if (!s_wifi) {
+        s_wifi = (NMSettingWireless *) nm_setting_wireless_new();
+        nm_connection_add_setting(connection, NM_SETTING(s_wifi));
+    }
+
+    if (ap)
+        ssid = nm_wifi_ap_get_ssid(ap);
+
+    if (ssid == NULL) {
+        /* The AP must be hidden.  Connecting to a Wi-Fi AP requires the SSID
+         * as part of the initial handshake, so check the connection details
+         * for the SSID.  The AP object will still be used for encryption
+         * settings and such.
+         */
+        ssid = nm_setting_wireless_get_ssid(s_wifi);
+    }
+
+    if (ssid == NULL) {
+        /* If there's no SSID on the AP itself, and no SSID in the
+         * connection data, then we cannot connect at all.  Return an error.
+         */
+        g_set_error_literal(
+            error,
+            NM_DEVICE_ERROR,
+            NM_DEVICE_ERROR_INVALID_CONNECTION,
+            ap ? "A 'wireless' setting with a valid SSID is required for hidden access points."
+               : "Cannot create 'wireless' setting due to missing SSID.");
+        return FALSE;
+    }
+
+    if (ap) {
+        /* If the SSID is a well-known SSID, lock the connection to the AP's
+         * specific BSSID so NM doesn't autoconnect to some random wifi net.
+         */
+        if (!nm_wifi_ap_complete_connection(ap,
+                                            connection,
+                                            nm_wifi_utils_is_manf_default_ssid(ssid),
+                                            error))
+            return FALSE;
+    }
+
+    ssid_utf8 = _nm_utils_ssid_to_utf8(ssid);
+    nm_utils_complete_generic(
+        nm_device_get_platform(device),
+        connection,
+        NM_SETTING_WIRELESS_SETTING_NAME,
+        existing_connections,
+        ssid_utf8,
+        ssid_utf8,
+        NULL,
+        nm_setting_wireless_get_mac_address(s_wifi) ? NULL : nm_device_get_iface(device),
+        TRUE);
+
+    if (hidden)
+        g_object_set(s_wifi, NM_SETTING_WIRELESS_HIDDEN, TRUE, NULL);
+
+    return TRUE;
+}
+
+static gboolean
+is_available(NMDevice *device, NMDeviceCheckDevAvailableFlags flags)
+{
+    NMDeviceWifi *             self = NM_DEVICE_WIFI(device);
+    NMDeviceWifiPrivate *      priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    NMSupplicantInterfaceState supplicant_state;
+
+    if (!priv->enabled)
+        return FALSE;
+
+    if (!priv->sup_iface)
+        return FALSE;
+
+    supplicant_state = nm_supplicant_interface_get_state(priv->sup_iface);
+    if (supplicant_state <= NM_SUPPLICANT_INTERFACE_STATE_STARTING
+        || supplicant_state > NM_SUPPLICANT_INTERFACE_STATE_COMPLETED)
+        return FALSE;
+
+    return TRUE;
+}
+
+static gboolean
+get_autoconnect_allowed(NMDevice *device)
+{
+    return !NM_DEVICE_WIFI_GET_PRIVATE(NM_DEVICE_WIFI(device))->scan_is_scanning;
+}
+
+static gboolean
+can_auto_connect(NMDevice *device, NMSettingsConnection *sett_conn, char **specific_object)
+{
+    NMDeviceWifi *       self = NM_DEVICE_WIFI(device);
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    NMConnection *       connection;
+    NMSettingWireless *  s_wifi;
+    NMWifiAP *           ap;
+    const char *         method6, *mode;
+    gboolean             auto4, auto6;
+
+    nm_assert(!specific_object || !*specific_object);
+
+    if (!NM_DEVICE_CLASS(nm_device_wifi_parent_class)->can_auto_connect(device, sett_conn, NULL))
+        return FALSE;
+
+    connection = nm_settings_connection_get_connection(sett_conn);
+
+    s_wifi = nm_connection_get_setting_wireless(connection);
+    g_return_val_if_fail(s_wifi, FALSE);
+
+    /* Always allow autoconnect for AP and non-autoconf Ad-Hoc or Mesh */
+    auto4   = nm_streq0(nm_utils_get_ip_config_method(connection, AF_INET),
+                      NM_SETTING_IP4_CONFIG_METHOD_AUTO);
+    method6 = nm_utils_get_ip_config_method(connection, AF_INET6);
+    auto6   = nm_streq0(method6, NM_SETTING_IP6_CONFIG_METHOD_AUTO)
+            || nm_streq0(method6, NM_SETTING_IP6_CONFIG_METHOD_DHCP);
+
+    mode = nm_setting_wireless_get_mode(s_wifi);
+
+    if (nm_streq0(mode, NM_SETTING_WIRELESS_MODE_AP))
+        return TRUE;
+    else if (!auto4 && nm_streq0(mode, NM_SETTING_WIRELESS_MODE_ADHOC))
+        return TRUE;
+    else if (!auto4 && !auto6 && nm_streq0(mode, NM_SETTING_WIRELESS_MODE_MESH))
+        return TRUE;
+
+    ap = nm_wifi_aps_find_first_compatible(&priv->aps_lst_head, connection);
+    if (ap) {
+        /* All good; connection is usable */
+        NM_SET_OUT(specific_object, g_strdup(nm_dbus_object_get_path(NM_DBUS_OBJECT(ap))));
+        return TRUE;
+    }
+
+    return FALSE;
+}
+
+const CList *
+_nm_device_wifi_get_aps(NMDeviceWifi *self)
+{
+    return &NM_DEVICE_WIFI_GET_PRIVATE(self)->aps_lst_head;
+}
+
+static void
+_hw_addr_set_scanning(NMDeviceWifi *self, gboolean do_reset)
+{
+    NMDevice *           device = (NMDevice *) self;
+    NMDeviceWifiPrivate *priv;
+    guint32              now;
+    gboolean             randomize;
+
+    g_return_if_fail(NM_IS_DEVICE_WIFI(self));
+
+    if (nm_device_is_activating(device) || nm_device_get_state(device) == NM_DEVICE_STATE_ACTIVATED)
+        return;
+
+    priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    randomize = nm_config_data_get_device_config_boolean(
+        NM_CONFIG_GET_DATA,
+        NM_CONFIG_KEYFILE_KEY_DEVICE_WIFI_SCAN_RAND_MAC_ADDRESS,
+        device,
+        TRUE,
+        TRUE);
+
+    if (!randomize) {
+        /* expire the temporary MAC address used during scanning */
+        priv->hw_addr_scan_expire = 0;
+
+        if (do_reset) {
+            priv->scan_last_request_started_at_msec = G_MININT64;
+            priv->scan_periodic_next_msec           = 0;
+            priv->scan_periodic_interval_sec        = 0;
+            nm_device_hw_addr_reset(device, "scanning");
+        }
+        return;
+    }
+
+    now = nm_utils_get_monotonic_timestamp_sec();
+
+    if (now >= priv->hw_addr_scan_expire) {
+        gs_free char *generate_mac_address_mask = NULL;
+        gs_free char *hw_addr_scan              = NULL;
+
+        /* the random MAC address for scanning expires after a while.
+         *
+         * We don't bother with to update the MAC address exactly when
+         * it expires, instead on the next scan request, we will generate
+         * a new one.*/
+        priv->hw_addr_scan_expire = now + SCAN_RAND_MAC_ADDRESS_EXPIRE_SEC;
+
+        generate_mac_address_mask = nm_config_data_get_device_config(
+            NM_CONFIG_GET_DATA,
+            NM_CONFIG_KEYFILE_KEY_DEVICE_WIFI_SCAN_GENERATE_MAC_ADDRESS_MASK,
+            device,
+            NULL);
+
+        priv->scan_last_request_started_at_msec = G_MININT64;
+        priv->scan_periodic_next_msec           = 0;
+        priv->scan_periodic_interval_sec        = 0;
+        hw_addr_scan = nm_utils_hw_addr_gen_random_eth(nm_device_get_initial_hw_address(device),
+                                                       generate_mac_address_mask);
+        nm_device_hw_addr_set(device, hw_addr_scan, "scanning", TRUE);
+    }
+}
+
+static GPtrArray *
+ssids_options_to_ptrarray(GVariant *value, GError **error)
+{
+    gs_unref_ptrarray GPtrArray *ssids = NULL;
+    gsize                        num_ssids;
+    gsize                        i;
+
+    nm_assert(g_variant_is_of_type(value, G_VARIANT_TYPE("aay")));
+
+    num_ssids = g_variant_n_children(value);
+    if (num_ssids > 32) {
+        g_set_error_literal(error,
+                            NM_DEVICE_ERROR,
+                            NM_DEVICE_ERROR_INVALID_ARGUMENT,
+                            "too many SSIDs requested to scan");
+        return NULL;
+    }
+
+    if (num_ssids) {
+        ssids = g_ptr_array_new_full(num_ssids, (GDestroyNotify) g_bytes_unref);
+        for (i = 0; i < num_ssids; i++) {
+            gs_unref_variant GVariant *v = NULL;
+            gsize                      len;
+            const guint8 *             bytes;
+
+            v     = g_variant_get_child_value(value, i);
+            bytes = g_variant_get_fixed_array(v, &len, sizeof(guint8));
+            if (len > 32) {
+                g_set_error(error,
+                            NM_DEVICE_ERROR,
+                            NM_DEVICE_ERROR_INVALID_ARGUMENT,
+                            "SSID at index %d more than 32 bytes",
+                            (int) i);
+                return NULL;
+            }
+
+            g_ptr_array_add(ssids, g_bytes_new(bytes, len));
+        }
+    }
+
+    return g_steal_pointer(&ssids);
+}
+
+GPtrArray *
+nmtst_ssids_options_to_ptrarray(GVariant *value, GError **error)
+{
+    return ssids_options_to_ptrarray(value, error);
+}
+
+static void
+dbus_request_scan_cb(NMDevice *             device,
+                     GDBusMethodInvocation *context,
+                     NMAuthSubject *        subject,
+                     GError *               error,
+                     gpointer               user_data)
+{
+    NMDeviceWifi *       self          = NM_DEVICE_WIFI(device);
+    NMDeviceWifiPrivate *priv          = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    gs_unref_ptrarray GPtrArray *ssids = user_data;
+
+    if (error) {
+        g_dbus_method_invocation_return_gerror(context, error);
+        return;
+    }
+
+    _scan_request_ssids_track(priv, ssids);
+    priv->scan_explicit_requested = TRUE;
+    _scan_kickoff(self);
+    g_dbus_method_invocation_return_value(context, NULL);
+}
+
+void
+_nm_device_wifi_request_scan(NMDeviceWifi *         self,
+                             GVariant *             options,
+                             GDBusMethodInvocation *invocation)
+{
+    NMDeviceWifiPrivate *priv          = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    NMDevice *           device        = NM_DEVICE(self);
+    gs_unref_ptrarray GPtrArray *ssids = NULL;
+
+    if (options) {
+        gs_unref_variant GVariant *val = g_variant_lookup_value(options, "ssids", NULL);
+
+        if (val) {
+            gs_free_error GError *ssid_error = NULL;
+
+            if (!g_variant_is_of_type(val, G_VARIANT_TYPE("aay"))) {
+                g_dbus_method_invocation_return_error_literal(invocation,
+                                                              NM_DEVICE_ERROR,
+                                                              NM_DEVICE_ERROR_INVALID_ARGUMENT,
+                                                              "Invalid 'ssid' scan option");
+                return;
+            }
+
+            ssids = ssids_options_to_ptrarray(val, &ssid_error);
+            if (ssid_error) {
+                g_dbus_method_invocation_return_gerror(invocation, ssid_error);
+                return;
+            }
+        }
+    }
+
+    if (!priv->enabled || !priv->sup_iface
+        || nm_device_get_state(device) < NM_DEVICE_STATE_DISCONNECTED) {
+        g_dbus_method_invocation_return_error_literal(invocation,
+                                                      NM_DEVICE_ERROR,
+                                                      NM_DEVICE_ERROR_NOT_ALLOWED,
+                                                      "Scanning not allowed while unavailable");
+        return;
+    }
+
+    nm_device_auth_request(device,
+                           invocation,
+                           NULL,
+                           NM_AUTH_PERMISSION_WIFI_SCAN,
+                           TRUE,
+                           NULL,
+                           dbus_request_scan_cb,
+                           g_steal_pointer(&ssids));
+}
+
+static gboolean
+hidden_filter_func(NMSettings *settings, NMSettingsConnection *set_con, gpointer user_data)
+{
+    NMConnection *     connection = nm_settings_connection_get_connection(set_con);
+    NMSettingWireless *s_wifi;
+
+    if (!nm_connection_is_type(connection, NM_SETTING_WIRELESS_SETTING_NAME))
+        return FALSE;
+    s_wifi = nm_connection_get_setting_wireless(connection);
+    if (!s_wifi)
+        return FALSE;
+    if (nm_streq0(nm_setting_wireless_get_mode(s_wifi), NM_SETTING_WIRELESS_MODE_AP))
+        return FALSE;
+    return nm_setting_wireless_get_hidden(s_wifi);
+}
+
+static GPtrArray *
+_scan_request_ssids_build_hidden(NMDeviceWifi *self,
+                                 gint64        now_msec,
+                                 gboolean *    out_has_hidden_profiles)
+{
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    guint   max_scan_ssids    = nm_supplicant_interface_get_max_scan_ssids(priv->sup_iface);
+    gs_free NMSettingsConnection **connections  = NULL;
+    gs_unref_ptrarray GPtrArray *ssids          = NULL;
+    gs_unref_hashtable GHashTable *unique_ssids = NULL;
+    guint                          connections_len;
+    guint                          n_hidden;
+    guint                          i;
+
+    NM_SET_OUT(out_has_hidden_profiles, FALSE);
+
+    /* collect all pending explicit SSIDs. */
+    ssids = _scan_request_ssids_fetch(priv, now_msec);
+
+    if (max_scan_ssids == 0) {
+        /* no space. @ssids will be ignored. */
+        return NULL;
+    }
+
+    if (ssids) {
+        if (ssids->len < max_scan_ssids) {
+            /* Add wildcard SSID using a static wildcard SSID used for every scan */
+            g_ptr_array_insert(ssids, 0, g_bytes_ref(nm_gbytes_get_empty()));
+        }
+        if (ssids->len >= max_scan_ssids) {
+            /* there is no more space. Use what we have. */
+            g_ptr_array_set_size(ssids, max_scan_ssids);
+            return g_steal_pointer(&ssids);
+        }
+    }
+
+    connections = nm_settings_get_connections_clone(nm_device_get_settings((NMDevice *) self),
+                                                    &connections_len,
+                                                    hidden_filter_func,
+                                                    NULL,
+                                                    NULL,
+                                                    NULL);
+    if (!connections[0])
+        return g_steal_pointer(&ssids);
+
+    if (!ssids) {
+        ssids = g_ptr_array_new_full(max_scan_ssids, (GDestroyNotify) g_bytes_unref);
+        /* Add wildcard SSID using a static wildcard SSID used for every scan */
+        g_ptr_array_insert(ssids, 0, g_bytes_ref(nm_gbytes_get_empty()));
+    }
+
+    unique_ssids = g_hash_table_new(nm_gbytes_hash, nm_gbytes_equal);
+    for (i = 1; i < ssids->len; i++) {
+        if (!g_hash_table_add(unique_ssids, ssids->pdata[i]))
+            nm_assert_not_reached();
+    }
+
+    g_qsort_with_data(connections,
+                      connections_len,
+                      sizeof(NMSettingsConnection *),
+                      nm_settings_connection_cmp_timestamp_p_with_data,
+                      NULL);
+
+    n_hidden = 0;
+    for (i = 0; i < connections_len; i++) {
+        NMSettingWireless *s_wifi;
+        GBytes *           ssid;
+
+        if (ssids->len >= max_scan_ssids)
+            break;
+
+        if (n_hidden > 4) {
+            /* we allow at most 4 hidden profiles to be actively scanned. The
+             * reason is speed and to not disclose too many SSIDs. */
+            break;
+        }
+
+        s_wifi = nm_connection_get_setting_wireless(
+            nm_settings_connection_get_connection(connections[i]));
+        ssid = nm_setting_wireless_get_ssid(s_wifi);
+
+        if (!g_hash_table_add(unique_ssids, ssid))
+            continue;
+
+        g_ptr_array_add(ssids, g_bytes_ref(ssid));
+        n_hidden++;
+    }
+
+    NM_SET_OUT(out_has_hidden_profiles, n_hidden > 0);
+    return g_steal_pointer(&ssids);
+}
+
+static gboolean
+_scan_request_delay_cb(gpointer user_data)
+{
+    NMDeviceWifi *       self = user_data;
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    nm_clear_g_source_inst(&priv->scan_request_delay_source);
+
+    _LOGT_scan("scan request completed (after extra delay)");
+
+    _scan_notify_is_scanning(self);
+    return G_SOURCE_REMOVE;
+}
+
+static void
+_scan_supplicant_request_scan_cb(NMSupplicantInterface *supp_iface,
+                                 GCancellable *         cancellable,
+                                 gpointer               user_data)
+{
+    NMDeviceWifi *       self;
+    NMDeviceWifiPrivate *priv;
+
+    if (g_cancellable_is_cancelled(cancellable))
+        return;
+
+    self = user_data;
+    priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    _LOGT_scan("scan request completed (D-Bus request)");
+
+    /* we just completed a scan request, but possibly the supplicant's state is not yet toggled
+     * to "scanning". That means, our internal scanning state "priv->scan_is_scanning" would already
+     * flip to idle, while in a moment the supplicant would toggle the state again.
+     *
+     * Artificially keep the scanning state on, for another SCAN_EXTRA_DELAY_MSEC msec. */
+    nm_clear_g_source_inst(&priv->scan_request_delay_source);
+    priv->scan_request_delay_source =
+        nm_g_source_attach(nm_g_timeout_source_new(SCAN_EXTRA_DELAY_MSEC,
+                                                   G_PRIORITY_DEFAULT,
+                                                   _scan_request_delay_cb,
+                                                   self,
+                                                   NULL),
+                           NULL);
+
+    g_clear_object(&priv->scan_request_cancellable);
+    _scan_notify_is_scanning(self);
+}
+
+static gboolean
+_scan_kickoff_timeout_cb(gpointer user_data)
+{
+    NMDeviceWifi *       self = user_data;
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    priv->scan_kickoff_timeout_id = 0;
+    _scan_kickoff(self);
+    return G_SOURCE_REMOVE;
+}
+
+static void
+_scan_kickoff(NMDeviceWifi *self)
+{
+    NMDeviceWifiPrivate *priv               = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    gs_unref_ptrarray GPtrArray *ssids      = NULL;
+    gboolean                     is_explict = FALSE;
+    NMDeviceState                device_state;
+    gboolean                     has_hidden_profiles;
+    gint64                       now_msec;
+    gint64                       ratelimit_duration_msec;
+
+    if (!priv->sup_iface) {
+        _LOGT_scan("kickoff: don't scan (has no supplicant interface)");
+        return;
+    }
+
+    if (priv->scan_request_cancellable) {
+        _LOGT_scan("kickoff: don't scan (has scan_request_cancellable)");
+        /* We are currently waiting for a scan request to complete. Wait longer. */
+        return;
+    }
+
+    now_msec = nm_utils_get_monotonic_timestamp_msec();
+
+    _scan_request_ssids_remove_all(priv, now_msec, G_MAXUINT);
+
+    device_state = nm_device_get_state(NM_DEVICE(self));
+    if (device_state > NM_DEVICE_STATE_DISCONNECTED && device_state <= NM_DEVICE_STATE_ACTIVATED) {
+        /* while we are activated, we rate limit more. */
+        ratelimit_duration_msec = 8000;
+    } else
+        ratelimit_duration_msec = 1500;
+
+    if (priv->scan_last_request_started_at_msec + ratelimit_duration_msec > now_msec) {
+        _LOGT_scan(
+            "kickoff: don't scan (rate limited for another %d.%03d sec%s)",
+            (int) ((priv->scan_last_request_started_at_msec + ratelimit_duration_msec - now_msec)
+                   / 1000),
+            (int) ((priv->scan_last_request_started_at_msec + ratelimit_duration_msec - now_msec)
+                   % 1000),
+            !priv->scan_kickoff_timeout_id ? ", schedule timeout" : "");
+        if (!priv->scan_kickoff_timeout_id
+            && (priv->scan_explicit_allowed || priv->scan_periodic_allowed)) {
+            priv->scan_kickoff_timeout_id = g_timeout_add(priv->scan_last_request_started_at_msec
+                                                              + ratelimit_duration_msec - now_msec,
+                                                          _scan_kickoff_timeout_cb,
+                                                          self);
+        }
+        return;
+    }
+
+    if (priv->scan_last_complete_msec + 200 > now_msec) {
+        gint32 timeout_msec = priv->scan_last_complete_msec + 200 - now_msec;
+
+        /* after a scan just completed, it is ratelimited for another 200 msec. This is in
+         * addition to our rate limiting above (where scanning can take longer than our rate limit
+         * duration).
+         *
+         * This gives the device a chance to autoconnect. Also, if a scanning just completed,
+         * we want to back off a bit before starting again. */
+        _LOGT_scan("kickoff: don't scan (rate limited for another %d.%03d sec after previous scan)",
+                   timeout_msec / 1000,
+                   timeout_msec % 1000);
+        nm_clear_g_source(&priv->scan_kickoff_timeout_id);
+        priv->scan_kickoff_timeout_id = g_timeout_add(timeout_msec, _scan_kickoff_timeout_cb, self);
+        return;
+    }
+
+    if (priv->scan_explicit_requested) {
+        if (!priv->scan_explicit_allowed) {
+            _LOGT_scan("kickoff: don't scan (explicit scan requested but not allowed)");
+            return;
+        }
+        priv->scan_explicit_requested = FALSE;
+        is_explict                    = TRUE;
+    } else {
+        if (!priv->scan_periodic_allowed) {
+            _LOGT_scan("kickoff: don't scan (periodic scan currently not allowed)");
+            priv->scan_periodic_next_msec    = 0;
+            priv->scan_periodic_interval_sec = 0;
+            nm_clear_g_source(&priv->scan_kickoff_timeout_id);
+            return;
+        }
+
+        nm_assert(priv->scan_explicit_allowed);
+
+        if (now_msec < priv->scan_periodic_next_msec) {
+            _LOGT_scan("kickoff: don't scan (periodic scan waiting for another %d.%03d sec%s)",
+                       (int) ((priv->scan_periodic_next_msec - now_msec) / 1000),
+                       (int) ((priv->scan_periodic_next_msec - now_msec) % 1000),
+                       !priv->scan_kickoff_timeout_id ? ", schedule timeout" : "");
+            if (!priv->scan_kickoff_timeout_id) {
+                priv->scan_kickoff_timeout_id =
+                    g_timeout_add_seconds((priv->scan_periodic_next_msec - now_msec + 999) / 1000,
+                                          _scan_kickoff_timeout_cb,
+                                          self);
+            }
+            return;
+        }
+
+        priv->scan_periodic_interval_sec =
+            NM_CLAMP(((int) priv->scan_periodic_interval_sec) * 3 / 2,
+                     SCAN_INTERVAL_SEC_MIN,
+                     SCAN_INTERVAL_SEC_MAX);
+        priv->scan_periodic_next_msec = now_msec + 1000 * priv->scan_periodic_interval_sec;
+    }
+
+    ssids = _scan_request_ssids_build_hidden(self, now_msec, &has_hidden_profiles);
+    if (has_hidden_profiles) {
+        if (priv->hidden_probe_scan_warn) {
+            priv->hidden_probe_scan_warn = FALSE;
+            _LOGW(LOGD_WIFI,
+                  "wifi-scan: active scanning for networks due to profiles with wifi.hidden=yes. "
+                  "This makes you trackable");
+        }
+    } else if (!is_explict)
+        priv->hidden_probe_scan_warn = TRUE;
+
+    if (_LOGD_ENABLED(LOGD_WIFI)) {
+        gs_free char *ssids_str = NULL;
+        guint         ssids_len = 0;
+
+        if (ssids) {
+            gs_strfreev char **strv = NULL;
+            guint              i;
+
+            strv = g_new(char *, ssids->len + 1u);
+            for (i = 0; i < ssids->len; i++)
+                strv[i] = _nm_utils_ssid_to_string(ssids->pdata[i]);
+            strv[i] = NULL;
+
+            nm_assert(ssids->len > 0);
+            nm_assert(ssids->len == NM_PTRARRAY_LEN(strv));
+
+            ssids_str = g_strjoinv(", ", strv);
+            ssids_len = ssids->len;
+        }
+        _LOGD(LOGD_WIFI,
+              "wifi-scan: start %s scan (%u SSIDs to probe scan%s%s%s)",
+              is_explict ? "explicit" : "periodic",
+              ssids_len,
+              NM_PRINT_FMT_QUOTED(ssids_str, " [", ssids_str, "]", ""));
+    }
+
+    priv->scan_last_request_started_at_msec = now_msec;
+
+    if (is_explict)
+        _LOGT_scan("kickoff: explicit scan starting");
+    else {
+        _LOGT_scan("kickoff: periodic scan starting (next scan is scheduled in %d.%03d sec)",
+                   (int) ((priv->scan_periodic_next_msec - now_msec) / 1000),
+                   (int) ((priv->scan_periodic_next_msec - now_msec) % 1000));
+    }
+
+    _hw_addr_set_scanning(self, FALSE);
+
+    priv->scan_request_cancellable = g_cancellable_new();
+    nm_supplicant_interface_request_scan(priv->sup_iface,
+                                         ssids ? (GBytes *const *) ssids->pdata : NULL,
+                                         ssids ? ssids->len : 0u,
+                                         priv->scan_request_cancellable,
+                                         _scan_supplicant_request_scan_cb,
+                                         self);
+
+    /* It's OK to call _scan_notify_is_scanning() again. They mutually call each other,
+     * but _scan_kickoff() sets "priv->scan_request_cancellable" which will stop
+     * them from recursing indefinitely. */
+    _scan_notify_is_scanning(self);
+}
+
+/****************************************************************************
+ * WPA Supplicant control stuff
+ *
+ */
+
+static gboolean
+ap_list_dump(gpointer user_data)
+{
+    NMDeviceWifi *       self = NM_DEVICE_WIFI(user_data);
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    priv->ap_dump_id = 0;
+
+    if (_LOGD_ENABLED(LOGD_WIFI_SCAN)) {
+        NMWifiAP *ap;
+        gint64    now_msec = nm_utils_get_monotonic_timestamp_msec();
+        char      str_buf[100];
+
+        _LOGD(LOGD_WIFI_SCAN,
+              "APs: [now:%u.%03u, last:%s]",
+              (guint)(now_msec / NM_UTILS_MSEC_PER_SEC),
+              (guint)(now_msec % NM_UTILS_MSEC_PER_SEC),
+              priv->scan_last_complete_msec > 0
+                  ? nm_sprintf_buf(str_buf,
+                                   "%u.%03u",
+                                   (guint)(priv->scan_last_complete_msec / NM_UTILS_MSEC_PER_SEC),
+                                   (guint)(priv->scan_last_complete_msec % NM_UTILS_MSEC_PER_SEC))
+                  : "-1");
+        c_list_for_each_entry (ap, &priv->aps_lst_head, aps_lst)
+            _ap_dump(self, LOGL_DEBUG, ap, "dump", now_msec);
+    }
+    return G_SOURCE_REMOVE;
+}
+
+static void
+schedule_ap_list_dump(NMDeviceWifi *self)
+{
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    if (!priv->ap_dump_id && _LOGD_ENABLED(LOGD_WIFI_SCAN))
+        priv->ap_dump_id = g_timeout_add_seconds(1, ap_list_dump, self);
+}
+
+static void
+try_fill_ssid_for_hidden_ap(NMDeviceWifi *self, NMWifiAP *ap)
+{
+    const char *                 bssid;
+    NMSettingsConnection *const *connections;
+    guint                        i;
+
+    g_return_if_fail(nm_wifi_ap_get_ssid(ap) == NULL);
+
+    bssid = nm_wifi_ap_get_address(ap);
+    g_return_if_fail(bssid);
+
+    /* Look for this AP's BSSID in the seen-bssids list of a connection,
+     * and if a match is found, copy over the SSID */
+    connections = nm_settings_get_connections(nm_device_get_settings((NMDevice *) self), NULL);
+    for (i = 0; connections[i]; i++) {
+        NMSettingsConnection *sett_conn = connections[i];
+        NMSettingWireless *   s_wifi;
+
+        if (!nm_settings_connection_has_seen_bssid(sett_conn, bssid))
+            continue;
+        s_wifi =
+            nm_connection_get_setting_wireless(nm_settings_connection_get_connection(sett_conn));
+        if (!s_wifi)
+            continue;
+
+        nm_wifi_ap_set_ssid(ap, nm_setting_wireless_get_ssid(s_wifi));
+        break;
+    }
+}
+
+static void
+supplicant_iface_bss_changed_cb(NMSupplicantInterface *iface,
+                                NMSupplicantBssInfo *  bss_info,
+                                gboolean               is_present,
+                                NMDeviceWifi *         self)
+{
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    NMWifiAP *           found_ap;
+    GBytes *             ssid;
+
+    found_ap = g_hash_table_lookup(priv->aps_idx_by_supplicant_path, bss_info->bss_path);
+
+    if (!is_present) {
+        if (!found_ap)
+            return;
+        if (found_ap == priv->current_ap) {
+            /* The current AP cannot be removed (to prevent NM indicating that
+             * it is connected, but to nothing), but it must be removed later
+             * when the current AP is changed or cleared.  Set 'fake' to
+             * indicate that this AP is now unknown to the supplicant.
+             */
+            if (nm_wifi_ap_set_fake(found_ap, TRUE))
+                _ap_dump(self, LOGL_DEBUG, found_ap, "updated", 0);
+        } else {
+            ap_add_remove(self, FALSE, found_ap, TRUE);
+            schedule_ap_list_dump(self);
+        }
+        return;
+    }
+
+    if (found_ap) {
+        if (!nm_wifi_ap_update_from_properties(found_ap, bss_info))
+            return;
+        _ap_dump(self, LOGL_DEBUG, found_ap, "updated", 0);
+    } else {
+        gs_unref_object NMWifiAP *ap = NULL;
+
+        if (!bss_info->bssid_valid) {
+            /* We failed to initialize the info about the AP. This can
+             * happen due to an error in the D-Bus communication. In this case
+             * we ignore the info. */
+            return;
+        }
+
+        ap = nm_wifi_ap_new_from_properties(bss_info);
+
+        /* Let the manager try to fill in the SSID from seen-bssids lists */
+        ssid = nm_wifi_ap_get_ssid(ap);
+        if (!ssid || _nm_utils_is_empty_ssid(ssid)) {
+            /* Try to fill the SSID from the AP database */
+            try_fill_ssid_for_hidden_ap(self, ap);
+
+            ssid = nm_wifi_ap_get_ssid(ap);
+            if (ssid && !_nm_utils_is_empty_ssid(ssid)) {
+                gs_free char *s = NULL;
+
+                /* Yay, matched it, no longer treat as hidden */
+                _LOGD(LOGD_WIFI,
+                      "matched hidden AP %s => %s",
+                      nm_wifi_ap_get_address(ap),
+                      (s = _nm_utils_ssid_to_string(ssid)));
+            } else {
+                /* Didn't have an entry for this AP in the database */
+                _LOGD(LOGD_WIFI, "failed to match hidden AP %s", nm_wifi_ap_get_address(ap));
+            }
+        }
+
+        ap_add_remove(self, TRUE, ap, TRUE);
+    }
+
+    /* Update the current AP if the supplicant notified a current BSS change
+     * before it sent the current BSS's scan result.
+     */
+    if (nm_supplicant_interface_get_current_bss(iface) == bss_info->bss_path)
+        supplicant_iface_notify_current_bss(priv->sup_iface, NULL, self);
+
+    schedule_ap_list_dump(self);
+}
+
+static void
+cleanup_association_attempt(NMDeviceWifi *self, gboolean disconnect)
+{
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    nm_clear_g_source(&priv->sup_timeout_id);
+    nm_clear_g_source(&priv->link_timeout_id);
+    nm_clear_g_source(&priv->wps_timeout_id);
+    if (disconnect && priv->sup_iface)
+        nm_supplicant_interface_disconnect(priv->sup_iface);
+}
+
+static void
+cleanup_supplicant_failures(NMDeviceWifi *self)
+{
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    nm_clear_g_source(&priv->reacquire_iface_id);
+    priv->failed_iface_count = 0;
+}
+
+static void
+wifi_secrets_cb(NMActRequest *                req,
+                NMActRequestGetSecretsCallId *call_id,
+                NMSettingsConnection *        connection,
+                GError *                      error,
+                gpointer                      user_data)
+{
+    NMDevice *           device = user_data;
+    NMDeviceWifi *       self   = user_data;
+    NMDeviceWifiPrivate *priv;
+
+    g_return_if_fail(NM_IS_DEVICE_WIFI(self));
+    g_return_if_fail(NM_IS_ACT_REQUEST(req));
+
+    priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    g_return_if_fail(priv->wifi_secrets_id == call_id);
+
+    priv->wifi_secrets_id = NULL;
+
+    if (g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
+        return;
+
+    g_return_if_fail(req == nm_device_get_act_request(device));
+    g_return_if_fail(nm_device_get_state(device) == NM_DEVICE_STATE_NEED_AUTH);
+    g_return_if_fail(nm_act_request_get_settings_connection(req) == connection);
+
+    if (error) {
+        _LOGW(LOGD_WIFI, "no secrets: %s", error->message);
+
+        /* Even if WPS is still pending, let's abort the activation when the secret
+         * request returns.
+         *
+         * This means, a user can only effectively use WPS when also running a secret
+         * agent, and pressing the push button while being prompted for the password.
+         * Note, that in the secret prompt the user can see that WPS is in progress
+         * (via the NM_SECRET_AGENT_GET_SECRETS_FLAG_WPS_PBC_ACTIVE flag).
+         *
+         * Previously, WPS was not cancelled when the secret request returns.
+         * Note that in common use-cases WPS is enabled in the connection profile
+         * but it won't succeed (because it's disabled in the AP or because the
+         * user is not prepared to press the push button).
+         * That means for example, during boot we would try to autoconnect with WPS.
+         * At that point, there is no secret-agent running, and WPS is pending for
+         * full 30 seconds. If in the meantime a secret agent registers (because
+         * of logging into the DE), the profile is still busy waiting for WPS to time
+         * out. Only after that delay, autoconnect starts again (note that autoconnect gets
+         * not blocked in this case, because a secret agent registered in the meantime).
+         *
+         * It seems wrong to continue doing WPS if the user is not aware
+         * that WPS is ongoing. The user is required to perform an action (push button),
+         * and must be told via the secret prompt.
+         * If no secret-agent is running, if the user cancels the secret-request, or any
+         * other error to obtain secrets, the user apparently does not want WPS either.
+         */
+        nm_clear_g_source(&priv->wps_timeout_id);
+        nm_device_state_changed(device, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_NO_SECRETS);
+        return;
+    }
+
+    nm_device_activate_schedule_stage1_device_prepare(device, FALSE);
+}
+
+static void
+wifi_secrets_cancel(NMDeviceWifi *self)
+{
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    if (priv->wifi_secrets_id)
+        nm_act_request_cancel_secrets(NULL, priv->wifi_secrets_id);
+    nm_assert(!priv->wifi_secrets_id);
+}
+
+static void
+supplicant_iface_wps_credentials_cb(NMSupplicantInterface *iface,
+                                    GVariant *             credentials,
+                                    NMDeviceWifi *         self)
+{
+    NMActRequest *   req;
+    gs_unref_variant GVariant *val_key = NULL;
+    gs_unref_variant GVariant *secrets = NULL;
+    gs_free_error GError *error        = NULL;
+    const char *          array;
+    gsize                 psk_len = 0;
+
+    if (nm_device_get_state(NM_DEVICE(self)) != NM_DEVICE_STATE_NEED_AUTH) {
+        _LOGI(LOGD_DEVICE | LOGD_WIFI, "WPS: The connection can't be updated with credentials");
+        return;
+    }
+
+    _LOGI(LOGD_DEVICE | LOGD_WIFI, "WPS: Updating the connection with credentials");
+
+    req = nm_device_get_act_request(NM_DEVICE(self));
+    g_return_if_fail(NM_IS_ACT_REQUEST(req));
+
+    val_key = g_variant_lookup_value(credentials, "Key", G_VARIANT_TYPE_BYTESTRING);
+    if (val_key) {
+        char psk[64];
+
+        array = g_variant_get_fixed_array(val_key, &psk_len, 1);
+        if (psk_len >= 8 && psk_len <= 63) {
+            memcpy(psk, array, psk_len);
+            psk[psk_len] = '\0';
+            if (g_utf8_validate(psk, psk_len, NULL)) {
+                secrets = g_variant_new_parsed("[{%s, [{%s, <%s>}]}]",
+                                               NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                                               NM_SETTING_WIRELESS_SECURITY_PSK,
+                                               psk);
+                g_variant_ref_sink(secrets);
+            }
+        }
+        if (!secrets)
+            _LOGW(LOGD_DEVICE | LOGD_WIFI, "WPS: ignore invalid PSK");
+    }
+
+    if (!secrets)
+        return;
+
+    if (!nm_settings_connection_new_secrets(nm_act_request_get_settings_connection(req),
+                                            nm_act_request_get_applied_connection(req),
+                                            NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                                            secrets,
+                                            &error)) {
+        _LOGW(LOGD_DEVICE | LOGD_WIFI,
+              "WPS: Could not update the connection with credentials: %s",
+              error->message);
+        return;
+    }
+
+    wifi_secrets_cancel(self);
+    nm_device_activate_schedule_stage1_device_prepare(NM_DEVICE(self), FALSE);
+}
+
+static gboolean
+wps_timeout_cb(gpointer user_data)
+{
+    NMDeviceWifi *       self = NM_DEVICE_WIFI(user_data);
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    priv->wps_timeout_id = 0;
+    if (!priv->wifi_secrets_id) {
+        /* Fail only if the secrets are not being requested. */
+        nm_device_state_changed(NM_DEVICE(self),
+                                NM_DEVICE_STATE_FAILED,
+                                NM_DEVICE_STATE_REASON_NO_SECRETS);
+    }
+
+    return G_SOURCE_REMOVE;
+}
+
+static void
+wifi_secrets_get_secrets(NMDeviceWifi *               self,
+                         const char *                 setting_name,
+                         NMSecretAgentGetSecretsFlags flags)
+{
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    NMActRequest *       req;
+
+    wifi_secrets_cancel(self);
+
+    req = nm_device_get_act_request(NM_DEVICE(self));
+    g_return_if_fail(NM_IS_ACT_REQUEST(req));
+
+    priv->wifi_secrets_id =
+        nm_act_request_get_secrets(req, TRUE, setting_name, flags, NULL, wifi_secrets_cb, self);
+    g_return_if_fail(priv->wifi_secrets_id);
+}
+
+/*
+ * link_timeout_cb
+ *
+ * Called when the link to the access point has been down for a specified
+ * period of time.
+ */
+static gboolean
+link_timeout_cb(gpointer user_data)
+{
+    NMDevice *           device = NM_DEVICE(user_data);
+    NMDeviceWifi *       self   = NM_DEVICE_WIFI(device);
+    NMDeviceWifiPrivate *priv   = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    _LOGW(LOGD_WIFI, "link timed out.");
+
+    priv->link_timeout_id = 0;
+
+    /* Disconnect event while activated; the supplicant hasn't been able
+     * to reassociate within the timeout period, so the connection must
+     * fail.
+     */
+    if (nm_device_get_state(device) != NM_DEVICE_STATE_ACTIVATED)
+        return FALSE;
+
+    set_current_ap(self, NULL, TRUE);
+
+    nm_device_state_changed(device,
+                            NM_DEVICE_STATE_FAILED,
+                            priv->ssid_found ? NM_DEVICE_STATE_REASON_SUPPLICANT_TIMEOUT
+                                             : NM_DEVICE_STATE_REASON_SSID_NOT_FOUND);
+    return FALSE;
+}
+
+static gboolean
+need_new_8021x_secrets(NMDeviceWifi *             self,
+                       NMSupplicantInterfaceState old_state,
+                       const char **              setting_name)
+{
+    NMSetting8021x *           s_8021x;
+    NMSettingWirelessSecurity *s_wsec;
+    NMSettingSecretFlags       secret_flags = NM_SETTING_SECRET_FLAG_NONE;
+    NMConnection *             connection;
+
+    g_return_val_if_fail(setting_name, FALSE);
+
+    connection = nm_device_get_applied_connection(NM_DEVICE(self));
+
+    g_return_val_if_fail(connection != NULL, FALSE);
+
+    /* 802.1x stuff only happens in the supplicant's ASSOCIATED state when it's
+     * attempting to authenticate with the AP.
+     */
+    if (old_state != NM_SUPPLICANT_INTERFACE_STATE_ASSOCIATED)
+        return FALSE;
+
+    /* If it's an 802.1x or LEAP connection with "always ask"/unsaved secrets
+     * then we need to ask again because it might be an OTP token and the PIN
+     * may have changed.
+     */
+
+    s_8021x = nm_connection_get_setting_802_1x(connection);
+    if (s_8021x) {
+        if (!nm_setting_get_secret_flags(NM_SETTING(s_8021x),
+                                         NM_SETTING_802_1X_PASSWORD,
+                                         &secret_flags,
+                                         NULL))
+            g_assert_not_reached();
+        if (secret_flags & NM_SETTING_SECRET_FLAG_NOT_SAVED)
+            *setting_name = NM_SETTING_802_1X_SETTING_NAME;
+        return *setting_name ? TRUE : FALSE;
+    }
+
+    s_wsec = nm_connection_get_setting_wireless_security(connection);
+    if (s_wsec) {
+        if (!nm_setting_get_secret_flags(NM_SETTING(s_wsec),
+                                         NM_SETTING_WIRELESS_SECURITY_LEAP_PASSWORD,
+                                         &secret_flags,
+                                         NULL))
+            g_assert_not_reached();
+        if (secret_flags & NM_SETTING_SECRET_FLAG_NOT_SAVED)
+            *setting_name = NM_SETTING_WIRELESS_SECURITY_SETTING_NAME;
+        return *setting_name ? TRUE : FALSE;
+    }
+
+    /* Not a LEAP or 802.1x connection */
+    return FALSE;
+}
+
+static gboolean
+need_new_wpa_psk(NMDeviceWifi *             self,
+                 NMSupplicantInterfaceState old_state,
+                 int                        disconnect_reason,
+                 const char **              setting_name)
+{
+    NMSettingWirelessSecurity *s_wsec;
+    NMConnection *             connection;
+    const char *               key_mgmt = NULL;
+
+    g_return_val_if_fail(setting_name, FALSE);
+
+    connection = nm_device_get_applied_connection(NM_DEVICE(self));
+
+    g_return_val_if_fail(connection, FALSE);
+
+    /* A bad PSK will cause the supplicant to disconnect during the 4-way handshake */
+    if (old_state != NM_SUPPLICANT_INTERFACE_STATE_4WAY_HANDSHAKE)
+        return FALSE;
+
+    s_wsec = nm_connection_get_setting_wireless_security(connection);
+    if (s_wsec)
+        key_mgmt = nm_setting_wireless_security_get_key_mgmt(s_wsec);
+
+    if (g_strcmp0(key_mgmt, "wpa-psk") == 0) {
+/* -4 (locally-generated WLAN_REASON_DISASSOC_DUE_TO_INACTIVITY) usually
+         * means the driver missed beacons from the AP.  This usually happens
+         * due to driver bugs or faulty power-save management.  It doesn't
+         * indicate that the PSK is wrong.
+         */
+#define LOCAL_WLAN_REASON_DISASSOC_DUE_TO_INACTIVITY -4
+        if (disconnect_reason == LOCAL_WLAN_REASON_DISASSOC_DUE_TO_INACTIVITY)
+            return FALSE;
+
+        *setting_name = NM_SETTING_WIRELESS_SECURITY_SETTING_NAME;
+        return TRUE;
+    }
+
+    /* Not a WPA-PSK connection */
+    return FALSE;
+}
+
+static gboolean
+handle_8021x_or_psk_auth_fail(NMDeviceWifi *             self,
+                              NMSupplicantInterfaceState new_state,
+                              NMSupplicantInterfaceState old_state,
+                              int                        disconnect_reason)
+{
+    NMDevice *    device = NM_DEVICE(self);
+    NMActRequest *req;
+    const char *  setting_name = NULL;
+    gboolean      handled      = FALSE;
+
+    g_return_val_if_fail(new_state == NM_SUPPLICANT_INTERFACE_STATE_DISCONNECTED, FALSE);
+
+    req = nm_device_get_act_request(NM_DEVICE(self));
+    g_return_val_if_fail(req != NULL, FALSE);
+
+    if (need_new_8021x_secrets(self, old_state, &setting_name)
+        || need_new_wpa_psk(self, old_state, disconnect_reason, &setting_name)) {
+        nm_act_request_clear_secrets(req);
+
+        _LOGI(LOGD_DEVICE | LOGD_WIFI,
+              "Activation: (wifi) disconnected during association, asking for new key");
+
+        cleanup_association_attempt(self, TRUE);
+        nm_device_state_changed(device,
+                                NM_DEVICE_STATE_NEED_AUTH,
+                                NM_DEVICE_STATE_REASON_SUPPLICANT_DISCONNECT);
+        wifi_secrets_get_secrets(self,
+                                 setting_name,
+                                 NM_SECRET_AGENT_GET_SECRETS_FLAG_ALLOW_INTERACTION
+                                     | NM_SECRET_AGENT_GET_SECRETS_FLAG_REQUEST_NEW);
+        handled = TRUE;
+    }
+
+    return handled;
+}
+
+static gboolean
+reacquire_interface_cb(gpointer user_data)
+{
+    NMDevice *           device = NM_DEVICE(user_data);
+    NMDeviceWifi *       self   = NM_DEVICE_WIFI(device);
+    NMDeviceWifiPrivate *priv   = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    priv->reacquire_iface_id = 0;
+    priv->failed_iface_count++;
+
+    _LOGW(LOGD_WIFI, "re-acquiring supplicant interface (#%d).", priv->failed_iface_count);
+
+    if (!priv->sup_iface)
+        supplicant_interface_acquire(self);
+
+    return G_SOURCE_REMOVE;
+}
+
+static void
+supplicant_iface_state_down(NMDeviceWifi *self)
+{
+    NMDeviceWifiPrivate *priv   = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    NMDevice *           device = NM_DEVICE(self);
+
+    nm_device_queue_recheck_available(device,
+                                      NM_DEVICE_STATE_REASON_SUPPLICANT_AVAILABLE,
+                                      NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
+    cleanup_association_attempt(self, FALSE);
+
+    /* If the device is already in UNAVAILABLE state then the state change
+     * is a NOP and the interface won't be re-acquired in the device state
+     * change handler.  So ensure we have a new one here so that we're
+     * ready if the supplicant comes back.
+     */
+    supplicant_interface_release(self);
+    if (priv->failed_iface_count < 5)
+        priv->reacquire_iface_id = g_timeout_add_seconds(10, reacquire_interface_cb, self);
+    else
+        _LOGI(LOGD_DEVICE | LOGD_WIFI, "supplicant interface keeps failing, giving up");
+}
+
+static void
+supplicant_iface_state(NMDeviceWifi *             self,
+                       NMSupplicantInterfaceState new_state,
+                       NMSupplicantInterfaceState old_state,
+                       int                        disconnect_reason,
+                       gboolean                   is_real_signal)
+{
+    NMDeviceWifiPrivate *priv   = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    NMDevice *           device = NM_DEVICE(self);
+    NMDeviceState        devstate;
+    gboolean             scanning;
+    gboolean             scan_changed;
+
+    _LOGI(LOGD_DEVICE | LOGD_WIFI,
+          "supplicant interface state: %s -> %s%s",
+          nm_supplicant_interface_state_to_string(old_state),
+          nm_supplicant_interface_state_to_string(new_state),
+          is_real_signal ? "" : " (simulated signal)");
+
+    if (new_state == NM_SUPPLICANT_INTERFACE_STATE_DOWN) {
+        supplicant_iface_state_down(self);
+        goto out;
+    }
+
+    devstate = nm_device_get_state(device);
+    scanning = nm_supplicant_interface_get_scanning(priv->sup_iface);
+
+    if (old_state == NM_SUPPLICANT_INTERFACE_STATE_STARTING) {
+        _LOGD(LOGD_WIFI, "supplicant ready");
+        nm_device_queue_recheck_available(NM_DEVICE(device),
+                                          NM_DEVICE_STATE_REASON_SUPPLICANT_AVAILABLE,
+                                          NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
+        priv->scan_periodic_interval_sec = 0;
+        priv->scan_periodic_next_msec    = 0;
+    }
+
+    /* In these states we know the supplicant is actually talking to something */
+    if (new_state >= NM_SUPPLICANT_INTERFACE_STATE_ASSOCIATING
+        && new_state <= NM_SUPPLICANT_INTERFACE_STATE_COMPLETED)
+        priv->ssid_found = TRUE;
+
+    if (old_state == NM_SUPPLICANT_INTERFACE_STATE_STARTING)
+        recheck_p2p_availability(self);
+
+    switch (new_state) {
+    case NM_SUPPLICANT_INTERFACE_STATE_COMPLETED:
+        nm_clear_g_source(&priv->sup_timeout_id);
+        nm_clear_g_source(&priv->link_timeout_id);
+        nm_clear_g_source(&priv->wps_timeout_id);
+
+        /* If this is the initial association during device activation,
+         * schedule the next activation stage.
+         */
+        if (devstate == NM_DEVICE_STATE_CONFIG) {
+            NMSettingWireless *s_wifi;
+            GBytes *           ssid;
+            gs_free char *     ssid_str = NULL;
+
+            s_wifi = nm_device_get_applied_setting(NM_DEVICE(self), NM_TYPE_SETTING_WIRELESS);
+
+            g_return_if_fail(s_wifi);
+
+            ssid = nm_setting_wireless_get_ssid(s_wifi);
+            g_return_if_fail(ssid);
+
+            _LOGI(LOGD_DEVICE | LOGD_WIFI,
+                  "Activation: (wifi) Stage 2 of 5 (Device Configure) successful. %s %s",
+                  priv->mode == NM_802_11_MODE_AP ? "Started Wi-Fi Hotspot"
+                                                  : "Connected to wireless network",
+                  (ssid_str = _nm_utils_ssid_to_string(ssid)));
+            nm_device_activate_schedule_stage3_ip_config_start(device);
+        } else if (devstate == NM_DEVICE_STATE_ACTIVATED)
+            periodic_update(self);
+        break;
+    case NM_SUPPLICANT_INTERFACE_STATE_DISCONNECTED:
+        if ((devstate == NM_DEVICE_STATE_ACTIVATED) || nm_device_is_activating(device)) {
+            /* Disconnect of an 802.1x/LEAP connection during authentication,
+             * or disconnect of a WPA-PSK connection during the 4-way handshake,
+             * often means secrets are wrong. Not always the case, but until we
+             * have more information from wpa_supplicant about why the
+             * disconnect happened this is the best we can do.
+             */
+            if (handle_8021x_or_psk_auth_fail(self, new_state, old_state, disconnect_reason))
+                break;
+        }
+
+        /* Otherwise, it might be a stupid driver or some transient error, so
+         * let the supplicant try to reconnect a few more times.  Give it more
+         * time if a scan is in progress since the link might be dropped during
+         * the scan but will be re-established when the scan is done.
+         */
+        if (devstate == NM_DEVICE_STATE_ACTIVATED) {
+            if (priv->link_timeout_id == 0) {
+                priv->link_timeout_id =
+                    g_timeout_add_seconds(scanning ? 30 : 15, link_timeout_cb, self);
+                priv->ssid_found = FALSE;
+            }
+        }
+        break;
+    case NM_SUPPLICANT_INTERFACE_STATE_INACTIVE:
+        /* we would clear _scan_has_pending_action_set() and trigger a new scan.
+         * However, we don't want to cancel the current pending action, so force
+         * a new scan request. */
+        break;
+    default:
+        break;
+    }
+
+out:
+    scan_changed = _scan_notify_allowed(self, NM_TERNARY_FALSE);
+    scan_changed |= _scan_notify_is_scanning(self);
+    if (scan_changed)
+        _scan_kickoff(self);
+
+    if (old_state == NM_SUPPLICANT_INTERFACE_STATE_STARTING)
+        nm_device_remove_pending_action(device, NM_PENDING_ACTION_WAITING_FOR_SUPPLICANT, TRUE);
+}
+
+static void
+supplicant_iface_state_cb(NMSupplicantInterface *iface,
+                          int                    new_state_i,
+                          int                    old_state_i,
+                          int                    disconnect_reason,
+                          gpointer               user_data)
+{
+    supplicant_iface_state(user_data, new_state_i, old_state_i, disconnect_reason, TRUE);
+}
+
+static void
+supplicant_iface_assoc_cb(NMSupplicantInterface *iface, GError *error, gpointer user_data)
+{
+    NMDeviceWifi *self   = NM_DEVICE_WIFI(user_data);
+    NMDevice *    device = NM_DEVICE(self);
+
+    if (error && !nm_utils_error_is_cancelled_or_disposing(error)
+        && nm_device_is_activating(device)) {
+        cleanup_association_attempt(self, TRUE);
+        nm_device_queue_state(device,
+                              NM_DEVICE_STATE_FAILED,
+                              NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
+    }
+}
+
+static void
+supplicant_iface_notify_current_bss(NMSupplicantInterface *iface,
+                                    GParamSpec *           pspec,
+                                    NMDeviceWifi *         self)
+{
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    NMRefString *        current_bss;
+    NMWifiAP *           new_ap = NULL;
+
+    current_bss = nm_supplicant_interface_get_current_bss(iface);
+    if (current_bss)
+        new_ap = g_hash_table_lookup(priv->aps_idx_by_supplicant_path, current_bss);
+
+    if (new_ap != priv->current_ap) {
+        const char *  new_bssid  = NULL;
+        GBytes *      new_ssid   = NULL;
+        const char *  old_bssid  = NULL;
+        GBytes *      old_ssid   = NULL;
+        gs_free char *new_ssid_s = NULL;
+        gs_free char *old_ssid_s = NULL;
+
+        /* Don't ever replace a "fake" current AP if we don't know about the
+         * supplicant's current BSS yet.  It'll get replaced when we receive
+         * the current BSS's scan result.
+         */
+        if (new_ap == NULL && nm_wifi_ap_get_fake(priv->current_ap))
+            return;
+
+        if (new_ap) {
+            new_bssid = nm_wifi_ap_get_address(new_ap);
+            new_ssid  = nm_wifi_ap_get_ssid(new_ap);
+        }
+
+        if (priv->current_ap) {
+            old_bssid = nm_wifi_ap_get_address(priv->current_ap);
+            old_ssid  = nm_wifi_ap_get_ssid(priv->current_ap);
+        }
+
+        _LOGD(LOGD_WIFI,
+              "roamed from BSSID %s (%s) to %s (%s)",
+              old_bssid ?: "(none)",
+              (old_ssid_s = _nm_utils_ssid_to_string(old_ssid)),
+              new_bssid ?: "(none)",
+              (new_ssid_s = _nm_utils_ssid_to_string(new_ssid)));
+
+        if (new_bssid) {
+            /* The new AP could be in a different layer 3 network
+             * and so the old DHCP lease could be no longer valid.
+             * Also, some APs (e.g. Cisco) can be configured to drop
+             * all traffic until DHCP completes. To support such
+             * cases, renew the lease when roaming to a new AP. */
+            nm_device_update_dynamic_ip_setup(NM_DEVICE(self));
+        }
+
+        set_current_ap(self, new_ap, TRUE);
+    }
+}
+
+/* We bind the existence of the P2P device to a wifi device that is being
+ * managed by NetworkManager and is capable of P2P operation.
+ * Note that some care must be taken here, because we don't want to re-create
+ * the device every time the supplicant interface is destroyed (e.g. due to
+ * a suspend/resume cycle).
+ * Therefore, this function will be called when a change in the P2P capability
+ * is detected and the supplicant interface has been initialised.
+ */
+static void
+recheck_p2p_availability(NMDeviceWifi *self)
+{
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    gboolean             p2p_available;
+
+    g_object_get(priv->sup_iface, NM_SUPPLICANT_INTERFACE_P2P_AVAILABLE, &p2p_available, NULL);
+
+    if (p2p_available && !priv->p2p_device) {
+        gs_free char *iface_name = NULL;
+
+        /* Create a P2P device. "p2p-dev-" is the same prefix as chosen by
+         * wpa_supplicant internally.
+         */
+        iface_name = g_strconcat("p2p-dev-", nm_device_get_iface(NM_DEVICE(self)), NULL);
+
+        priv->p2p_device = nm_device_wifi_p2p_new(iface_name);
+
+        nm_device_wifi_p2p_set_mgmt_iface(priv->p2p_device, priv->sup_iface);
+
+        g_signal_emit(self, signals[P2P_DEVICE_CREATED], 0, priv->p2p_device);
+        g_object_add_weak_pointer(G_OBJECT(priv->p2p_device), (gpointer *) &priv->p2p_device);
+        g_object_unref(priv->p2p_device);
+        return;
+    }
+
+    if (p2p_available && priv->p2p_device) {
+        nm_device_wifi_p2p_set_mgmt_iface(priv->p2p_device, priv->sup_iface);
+        return;
+    }
+
+    if (!p2p_available && priv->p2p_device) {
+        /* Destroy the P2P device. */
+        g_object_remove_weak_pointer(G_OBJECT(priv->p2p_device), (gpointer *) &priv->p2p_device);
+        nm_device_wifi_p2p_remove(g_steal_pointer(&priv->p2p_device));
+        return;
+    }
+}
+
+static void
+supplicant_iface_notify_p2p_available(NMSupplicantInterface *iface,
+                                      GParamSpec *           pspec,
+                                      NMDeviceWifi *         self)
+{
+    if (nm_supplicant_interface_get_state(iface) > NM_SUPPLICANT_INTERFACE_STATE_STARTING)
+        recheck_p2p_availability(self);
+}
+
+static gboolean
+handle_auth_or_fail(NMDeviceWifi *self, NMActRequest *req, gboolean new_secrets)
+{
+    NMDeviceWifiPrivate *              priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    const char *                       setting_name;
+    NMConnection *                     applied_connection;
+    NMSettingWirelessSecurity *        s_wsec;
+    const char *                       bssid = NULL;
+    NM80211ApFlags                     ap_flags;
+    NMSettingWirelessSecurityWpsMethod wps_method;
+    const char *                       type;
+    NMSecretAgentGetSecretsFlags       get_secret_flags =
+        NM_SECRET_AGENT_GET_SECRETS_FLAG_ALLOW_INTERACTION;
+
+    g_return_val_if_fail(NM_IS_DEVICE_WIFI(self), FALSE);
+
+    if (!req) {
+        req = nm_device_get_act_request(NM_DEVICE(self));
+        g_return_val_if_fail(req, FALSE);
+    }
+
+    if (!nm_device_auth_retries_try_next(NM_DEVICE(self)))
+        return FALSE;
+
+    nm_device_state_changed(NM_DEVICE(self),
+                            NM_DEVICE_STATE_NEED_AUTH,
+                            NM_DEVICE_STATE_REASON_NONE);
+
+    applied_connection = nm_act_request_get_applied_connection(req);
+    s_wsec             = nm_connection_get_setting_wireless_security(applied_connection);
+    wps_method         = nm_setting_wireless_security_get_wps_method(s_wsec);
+
+    /* Negotiate the WPS method */
+    if (wps_method == NM_SETTING_WIRELESS_SECURITY_WPS_METHOD_DEFAULT)
+        wps_method = NM_SETTING_WIRELESS_SECURITY_WPS_METHOD_AUTO;
+
+    if (wps_method & NM_SETTING_WIRELESS_SECURITY_WPS_METHOD_AUTO && priv->current_ap) {
+        /* Determine the method to use from AP capabilities. */
+        ap_flags = nm_wifi_ap_get_flags(priv->current_ap);
+        if (ap_flags & NM_802_11_AP_FLAGS_WPS_PBC)
+            wps_method |= NM_SETTING_WIRELESS_SECURITY_WPS_METHOD_PBC;
+        if (ap_flags & NM_802_11_AP_FLAGS_WPS_PIN)
+            wps_method |= NM_SETTING_WIRELESS_SECURITY_WPS_METHOD_PIN;
+        if (ap_flags & NM_802_11_AP_FLAGS_WPS
+            && wps_method == NM_SETTING_WIRELESS_SECURITY_WPS_METHOD_AUTO) {
+            /* The AP doesn't specify which methods are supported. Allow all. */
+            wps_method |= NM_SETTING_WIRELESS_SECURITY_WPS_METHOD_PBC;
+            wps_method |= NM_SETTING_WIRELESS_SECURITY_WPS_METHOD_PIN;
+        }
+    }
+
+    if (wps_method & NM_SETTING_WIRELESS_SECURITY_WPS_METHOD_PBC) {
+        get_secret_flags |= NM_SECRET_AGENT_GET_SECRETS_FLAG_WPS_PBC_ACTIVE;
+        type = "pbc";
+    } else if (wps_method & NM_SETTING_WIRELESS_SECURITY_WPS_METHOD_PIN) {
+        type = "pin";
+    } else
+        type = NULL;
+
+    if (type) {
+        priv->wps_timeout_id = g_timeout_add_seconds(30, wps_timeout_cb, self);
+        if (priv->current_ap)
+            bssid = nm_wifi_ap_get_address(priv->current_ap);
+        nm_supplicant_interface_enroll_wps(priv->sup_iface, type, bssid, NULL);
+    }
+
+    nm_act_request_clear_secrets(req);
+    setting_name = nm_connection_need_secrets(applied_connection, NULL);
+    if (!setting_name) {
+        _LOGW(LOGD_DEVICE, "Cleared secrets, but setting didn't need any secrets.");
+        return FALSE;
+    }
+
+    if (new_secrets)
+        get_secret_flags |= NM_SECRET_AGENT_GET_SECRETS_FLAG_REQUEST_NEW;
+    wifi_secrets_get_secrets(self, setting_name, get_secret_flags);
+    return TRUE;
+}
+
+/*
+ * supplicant_connection_timeout_cb
+ *
+ * Called when the supplicant has been unable to connect to an access point
+ * within a specified period of time.
+ */
+static gboolean
+supplicant_connection_timeout_cb(gpointer user_data)
+{
+    NMDevice *           device = NM_DEVICE(user_data);
+    NMDeviceWifi *       self   = NM_DEVICE_WIFI(user_data);
+    NMDeviceWifiPrivate *priv   = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    NMActRequest *       req;
+    NMConnection *       connection;
+
+    cleanup_association_attempt(self, TRUE);
+
+    if (!nm_device_is_activating(device))
+        return FALSE;
+
+    /* Timed out waiting for a successful connection to the AP; if the AP's
+     * security requires network-side authentication (like WPA or 802.1x)
+     * and the connection attempt timed out then it's likely the authentication
+     * information (passwords, pin codes, etc) are wrong.
+     */
+
+    req = nm_device_get_act_request(device);
+    g_assert(req);
+
+    connection = nm_act_request_get_applied_connection(req);
+    g_assert(connection);
+
+    if (NM_IN_SET(priv->mode, NM_802_11_MODE_ADHOC, NM_802_11_MODE_MESH, NM_802_11_MODE_AP)) {
+        /* In Ad-Hoc and AP modes there's nothing to check the encryption key
+         * (if any), so supplicant timeouts here are almost certainly the wifi
+         * driver being really stupid.
+         */
+        _LOGW(LOGD_DEVICE | LOGD_WIFI,
+              "Activation: (wifi) %s network creation took too long, failing activation",
+              priv->mode == NM_802_11_MODE_ADHOC ? "Ad-Hoc" : "Hotspot");
+        nm_device_state_changed(device,
+                                NM_DEVICE_STATE_FAILED,
+                                NM_DEVICE_STATE_REASON_SUPPLICANT_TIMEOUT);
+        return FALSE;
+    }
+
+    g_assert(priv->mode == NM_802_11_MODE_INFRA);
+
+    if (priv->ssid_found && nm_connection_get_setting_wireless_security(connection)) {
+        guint64  timestamp   = 0;
+        gboolean new_secrets = TRUE;
+
+        /* Connection failed; either driver problems, the encryption key is
+         * wrong, or the passwords or certificates were wrong.
+         */
+        _LOGW(LOGD_DEVICE | LOGD_WIFI, "Activation: (wifi) association took too long");
+
+        /* Ask for new secrets only if we've never activated this connection
+         * before.  If we've connected before, don't bother the user with
+         * dialogs, just retry or fail, and if we never connect the user can
+         * fix the password somewhere else.
+         */
+        if (nm_settings_connection_get_timestamp(nm_act_request_get_settings_connection(req),
+                                                 &timestamp))
+            new_secrets = !timestamp;
+
+        if (handle_auth_or_fail(self, req, new_secrets))
+            _LOGW(LOGD_DEVICE | LOGD_WIFI, "Activation: (wifi) asking for new secrets");
+        else {
+            nm_device_state_changed(device,
+                                    NM_DEVICE_STATE_FAILED,
+                                    NM_DEVICE_STATE_REASON_NO_SECRETS);
+        }
+    } else {
+        _LOGW(LOGD_DEVICE | LOGD_WIFI,
+              "Activation: (wifi) association took too long, failing activation");
+        nm_device_state_changed(device,
+                                NM_DEVICE_STATE_FAILED,
+                                priv->ssid_found ? NM_DEVICE_STATE_REASON_SUPPLICANT_TIMEOUT
+                                                 : NM_DEVICE_STATE_REASON_SSID_NOT_FOUND);
+    }
+
+    return FALSE;
+}
+
+static NMSupplicantConfig *
+build_supplicant_config(NMDeviceWifi *self,
+                        NMConnection *connection,
+                        guint32       fixed_freq,
+                        GError **     error)
+{
+    NMDeviceWifiPrivate *         priv   = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    NMSupplicantConfig *          config = NULL;
+    NMSettingWireless *           s_wireless;
+    NMSettingWirelessSecurity *   s_wireless_sec;
+    NMSettingWirelessSecurityPmf  pmf;
+    NMSettingWirelessSecurityFils fils;
+    NMTernary                     ap_isolation;
+
+    g_return_val_if_fail(priv->sup_iface, NULL);
+
+    s_wireless = nm_connection_get_setting_wireless(connection);
+    g_return_val_if_fail(s_wireless != NULL, NULL);
+
+    config = nm_supplicant_config_new(nm_supplicant_interface_get_capabilities(priv->sup_iface));
+
+    /* Warn if AP mode may not be supported */
+    if (nm_streq0(nm_setting_wireless_get_mode(s_wireless), NM_SETTING_WIRELESS_MODE_AP)
+        && nm_supplicant_interface_get_capability(priv->sup_iface, NM_SUPPL_CAP_TYPE_AP)
+               != NM_TERNARY_TRUE) {
+        _LOGW(LOGD_WIFI, "Supplicant may not support AP mode; connection may time out.");
+    }
+
+    if (!nm_supplicant_config_add_setting_wireless(config, s_wireless, fixed_freq, error)) {
+        g_prefix_error(error, "802-11-wireless: ");
+        goto error;
+    }
+
+    if (!nm_supplicant_config_add_bgscan(config, connection, error)) {
+        g_prefix_error(error, "bgscan: ");
+        goto error;
+    }
+
+    ap_isolation = nm_setting_wireless_get_ap_isolation(s_wireless);
+    if (ap_isolation == NM_TERNARY_DEFAULT) {
+        ap_isolation = nm_config_data_get_connection_default_int64(NM_CONFIG_GET_DATA,
+                                                                   "wifi.ap-isolation",
+                                                                   NM_DEVICE(self),
+                                                                   NM_TERNARY_FALSE,
+                                                                   NM_TERNARY_TRUE,
+                                                                   NM_TERNARY_FALSE);
+    }
+    nm_supplicant_config_set_ap_isolation(config, ap_isolation == NM_TERNARY_TRUE);
+
+    s_wireless_sec = nm_connection_get_setting_wireless_security(connection);
+    if (s_wireless_sec) {
+        NMSetting8021x *s_8021x;
+        const char *    con_uuid = nm_connection_get_uuid(connection);
+        guint32         mtu      = nm_platform_link_get_mtu(nm_device_get_platform(NM_DEVICE(self)),
+                                               nm_device_get_ifindex(NM_DEVICE(self)));
+
+        g_assert(con_uuid);
+
+        /* Configure PMF (802.11w) */
+        pmf = nm_setting_wireless_security_get_pmf(s_wireless_sec);
+        if (pmf == NM_SETTING_WIRELESS_SECURITY_PMF_DEFAULT) {
+            pmf = nm_config_data_get_connection_default_int64(
+                NM_CONFIG_GET_DATA,
+                "wifi-sec.pmf",
+                NM_DEVICE(self),
+                NM_SETTING_WIRELESS_SECURITY_PMF_DISABLE,
+                NM_SETTING_WIRELESS_SECURITY_PMF_REQUIRED,
+                NM_SETTING_WIRELESS_SECURITY_PMF_OPTIONAL);
+        }
+
+        /* Configure FILS (802.11ai) */
+        fils = nm_setting_wireless_security_get_fils(s_wireless_sec);
+        if (fils == NM_SETTING_WIRELESS_SECURITY_FILS_DEFAULT) {
+            fils = nm_config_data_get_connection_default_int64(
+                NM_CONFIG_GET_DATA,
+                "wifi-sec.fils",
+                NM_DEVICE(self),
+                NM_SETTING_WIRELESS_SECURITY_FILS_DISABLE,
+                NM_SETTING_WIRELESS_SECURITY_FILS_REQUIRED,
+                NM_SETTING_WIRELESS_SECURITY_FILS_OPTIONAL);
+        }
+
+        s_8021x = nm_connection_get_setting_802_1x(connection);
+        if (!nm_supplicant_config_add_setting_wireless_security(config,
+                                                                s_wireless_sec,
+                                                                s_8021x,
+                                                                con_uuid,
+                                                                mtu,
+                                                                pmf,
+                                                                fils,
+                                                                error)) {
+            g_prefix_error(error, "802-11-wireless-security: ");
+            goto error;
+        }
+    } else {
+        if (!nm_supplicant_config_add_no_security(config, error)) {
+            g_prefix_error(error, "unsecured-option: ");
+            goto error;
+        }
+    }
+
+    return config;
+
+error:
+    g_object_unref(config);
+    return NULL;
+}
+
+/*****************************************************************************/
+
+static gboolean
+wake_on_wlan_enable(NMDeviceWifi *self)
+{
+    NMDeviceWifiPrivate *       priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    NMSettingWirelessWakeOnWLan wowl;
+    NMSettingWireless *         s_wireless;
+
+    s_wireless = nm_device_get_applied_setting(NM_DEVICE(self), NM_TYPE_SETTING_WIRELESS);
+    if (s_wireless) {
+        wowl = nm_setting_wireless_get_wake_on_wlan(s_wireless);
+        if (wowl != NM_SETTING_WIRELESS_WAKE_ON_WLAN_DEFAULT)
+            goto found;
+    }
+
+    wowl = nm_config_data_get_connection_default_int64(NM_CONFIG_GET_DATA,
+                                                       "wifi.wake-on-wlan",
+                                                       NM_DEVICE(self),
+                                                       NM_SETTING_WIRELESS_WAKE_ON_WLAN_NONE,
+                                                       G_MAXINT32,
+                                                       NM_SETTING_WIRELESS_WAKE_ON_WLAN_DEFAULT);
+
+    if (NM_FLAGS_ANY(wowl, NM_SETTING_WIRELESS_WAKE_ON_WLAN_EXCLUSIVE_FLAGS)) {
+        if (!nm_utils_is_power_of_two(wowl)) {
+            _LOGD(LOGD_WIFI,
+                  "invalid default value %u for wake-on-wlan: "
+                  "'default' and 'ignore' are exclusive flags",
+                  (guint) wowl);
+            wowl = NM_SETTING_WIRELESS_WAKE_ON_WLAN_DEFAULT;
+        }
+    } else if (NM_FLAGS_ANY(wowl, ~NM_SETTING_WIRELESS_WAKE_ON_WLAN_ALL)) {
+        _LOGD(LOGD_WIFI, "invalid default value %u for wake-on-wlan", (guint) wowl);
+        wowl = NM_SETTING_WIRELESS_WAKE_ON_WLAN_DEFAULT;
+    }
+    if (wowl != NM_SETTING_WIRELESS_WAKE_ON_WLAN_DEFAULT)
+        goto found;
+
+    wowl = NM_SETTING_WIRELESS_WAKE_ON_WLAN_IGNORE;
+found:
+    if (wowl == NM_SETTING_WIRELESS_WAKE_ON_WLAN_IGNORE) {
+        priv->wowlan_restore = wowl;
+        return TRUE;
+    }
+
+    priv->wowlan_restore =
+        nm_platform_wifi_get_wake_on_wlan(NM_PLATFORM_GET, nm_device_get_ifindex(NM_DEVICE(self)));
+
+    return nm_platform_wifi_set_wake_on_wlan(NM_PLATFORM_GET,
+                                             nm_device_get_ifindex(NM_DEVICE(self)),
+                                             wowl);
+}
+
+static NMActStageReturn
+act_stage1_prepare(NMDevice *device, NMDeviceStateReason *out_failure_reason)
+{
+    NMDeviceWifi *       self         = NM_DEVICE_WIFI(device);
+    NMDeviceWifiPrivate *priv         = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    NMWifiAP *           ap           = NULL;
+    gs_unref_object NMWifiAP *ap_fake = NULL;
+    NMActRequest *            req;
+    NMConnection *            connection;
+    NMSettingWireless *       s_wireless;
+    const char *              mode;
+    const char *              ap_path;
+
+    req = nm_device_get_act_request(NM_DEVICE(self));
+    g_return_val_if_fail(req, NM_ACT_STAGE_RETURN_FAILURE);
+
+    connection = nm_act_request_get_applied_connection(req);
+    g_return_val_if_fail(connection, NM_ACT_STAGE_RETURN_FAILURE);
+
+    s_wireless = nm_connection_get_setting_wireless(connection);
+    g_return_val_if_fail(s_wireless, NM_ACT_STAGE_RETURN_FAILURE);
+
+    nm_supplicant_interface_cancel_wps(priv->sup_iface);
+
+    mode = nm_setting_wireless_get_mode(s_wireless);
+    if (g_strcmp0(mode, NM_SETTING_WIRELESS_MODE_INFRA) == 0)
+        priv->mode = NM_802_11_MODE_INFRA;
+    else if (g_strcmp0(mode, NM_SETTING_WIRELESS_MODE_ADHOC) == 0)
+        priv->mode = NM_802_11_MODE_ADHOC;
+    else if (g_strcmp0(mode, NM_SETTING_WIRELESS_MODE_AP) == 0) {
+        priv->mode = NM_802_11_MODE_AP;
+
+        /* Scanning not done in AP mode; clear the scan list */
+        remove_all_aps(self);
+    } else if (g_strcmp0(mode, NM_SETTING_WIRELESS_MODE_MESH) == 0)
+        priv->mode = NM_802_11_MODE_MESH;
+    _notify(self, PROP_MODE);
+
+    /* expire the temporary MAC address used during scanning */
+    priv->hw_addr_scan_expire = 0;
+
+    /* Set spoof MAC to the interface */
+    if (!nm_device_hw_addr_set_cloned(device, connection, TRUE)) {
+        *out_failure_reason = NM_DEVICE_STATE_REASON_CONFIG_FAILED;
+        return NM_ACT_STAGE_RETURN_FAILURE;
+    }
+
+    /* AP and Mesh modes never use a specific object or existing scanned AP */
+    if (!NM_IN_SET(priv->mode, NM_802_11_MODE_AP, NM_802_11_MODE_MESH)) {
+        ap_path = nm_active_connection_get_specific_object(NM_ACTIVE_CONNECTION(req));
+        ap      = ap_path ? nm_wifi_ap_lookup_for_device(NM_DEVICE(self), ap_path) : NULL;
+    }
+    if (!ap)
+        ap = nm_wifi_aps_find_first_compatible(&priv->aps_lst_head, connection);
+
+    if (!ap) {
+        /* If the user is trying to connect to an AP that NM doesn't yet know about
+         * (hidden network or something), starting a Hotspot or joining a Mesh,
+         * create a fake APfrom the security settings in the connection.  This "fake"
+         * AP gets used until the real one is found in the scan list (Ad-Hoc or Hidden),
+         * or until the device is deactivated (Hotspot).
+         */
+        ap_fake = nm_wifi_ap_new_fake_from_connection(connection);
+        if (!ap_fake)
+            g_return_val_if_reached(NM_ACT_STAGE_RETURN_FAILURE);
+
+        if (nm_wifi_ap_is_hotspot(ap_fake))
+            nm_wifi_ap_set_address(ap_fake, nm_device_get_hw_address(device));
+
+        g_object_freeze_notify(G_OBJECT(self));
+        ap_add_remove(self, TRUE, ap_fake, TRUE);
+        g_object_thaw_notify(G_OBJECT(self));
+        ap = ap_fake;
+    }
+
+    _scan_notify_allowed(self, NM_TERNARY_DEFAULT);
+
+    set_current_ap(self, ap, FALSE);
+    nm_active_connection_set_specific_object(NM_ACTIVE_CONNECTION(req),
+                                             nm_dbus_object_get_path(NM_DBUS_OBJECT(ap)));
+    return NM_ACT_STAGE_RETURN_SUCCESS;
+}
+
+static void
+ensure_hotspot_frequency(NMDeviceWifi *self, NMSettingWireless *s_wifi, NMWifiAP *ap)
+{
+    NMDevice *    device     = NM_DEVICE(self);
+    const char *  band       = nm_setting_wireless_get_band(s_wifi);
+    const guint32 a_freqs[]  = {5180, 5200, 5220, 5745, 5765, 5785, 5805, 0};
+    const guint32 bg_freqs[] = {2412, 2437, 2462, 2472, 0};
+    guint32       freq       = 0;
+
+    g_assert(ap);
+
+    if (nm_wifi_ap_get_freq(ap))
+        return;
+
+    if (g_strcmp0(band, "a") == 0)
+        freq = nm_platform_wifi_find_frequency(nm_device_get_platform(device),
+                                               nm_device_get_ifindex(device),
+                                               a_freqs);
+    else
+        freq = nm_platform_wifi_find_frequency(nm_device_get_platform(device),
+                                               nm_device_get_ifindex(device),
+                                               bg_freqs);
+
+    if (!freq)
+        freq = (g_strcmp0(band, "a") == 0) ? 5180 : 2462;
+
+    if (nm_wifi_ap_set_freq(ap, freq))
+        _ap_dump(self, LOGL_DEBUG, ap, "updated", 0);
+}
+
+static void
+set_powersave(NMDevice *device)
+{
+    NMDeviceWifi *             self = NM_DEVICE_WIFI(device);
+    NMSettingWireless *        s_wireless;
+    NMSettingWirelessPowersave val;
+
+    s_wireless = nm_device_get_applied_setting(device, NM_TYPE_SETTING_WIRELESS);
+
+    g_return_if_fail(s_wireless);
+
+    val = nm_setting_wireless_get_powersave(s_wireless);
+    if (val == NM_SETTING_WIRELESS_POWERSAVE_DEFAULT) {
+        val = nm_config_data_get_connection_default_int64(NM_CONFIG_GET_DATA,
+                                                          "wifi.powersave",
+                                                          device,
+                                                          NM_SETTING_WIRELESS_POWERSAVE_IGNORE,
+                                                          NM_SETTING_WIRELESS_POWERSAVE_ENABLE,
+                                                          NM_SETTING_WIRELESS_POWERSAVE_IGNORE);
+    }
+
+    _LOGT(LOGD_WIFI, "powersave is set to %u", (unsigned) val);
+
+    if (val == NM_SETTING_WIRELESS_POWERSAVE_IGNORE)
+        return;
+
+    nm_platform_wifi_set_powersave(nm_device_get_platform(device),
+                                   nm_device_get_ifindex(device),
+                                   val == NM_SETTING_WIRELESS_POWERSAVE_ENABLE);
+}
+
+static NMActStageReturn
+act_stage2_config(NMDevice *device, NMDeviceStateReason *out_failure_reason)
+{
+    NMDeviceWifi *       self                  = NM_DEVICE_WIFI(device);
+    NMDeviceWifiPrivate *priv                  = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    gs_unref_object NMSupplicantConfig *config = NULL;
+    NM80211Mode                         ap_mode;
+    NMActRequest *                      req;
+    NMWifiAP *                          ap;
+    NMConnection *                      connection;
+    const char *                        setting_name;
+    NMSettingWireless *                 s_wireless;
+    GError *                            error = NULL;
+    guint                               timeout;
+    NMActRequest *                      request;
+    NMActiveConnection *                master_ac;
+    NMDevice *                          master;
+
+    nm_clear_g_source(&priv->sup_timeout_id);
+    nm_clear_g_source(&priv->link_timeout_id);
+    nm_clear_g_source(&priv->wps_timeout_id);
+
+    req = nm_device_get_act_request(device);
+    g_return_val_if_fail(req, NM_ACT_STAGE_RETURN_FAILURE);
+
+    ap = priv->current_ap;
+    if (!ap) {
+        NM_SET_OUT(out_failure_reason, NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED);
+        goto out_fail;
+    }
+
+    ap_mode = nm_wifi_ap_get_mode(ap);
+
+    connection = nm_act_request_get_applied_connection(req);
+    s_wireless = nm_connection_get_setting_wireless(connection);
+    nm_assert(s_wireless);
+
+    /* If we need secrets, get them */
+    setting_name = nm_connection_need_secrets(connection, NULL);
+    if (setting_name) {
+        _LOGI(LOGD_DEVICE | LOGD_WIFI,
+              "Activation: (wifi) access point '%s' has security, but secrets are required.",
+              nm_connection_get_id(connection));
+
+        if (!handle_auth_or_fail(self, req, FALSE)) {
+            NM_SET_OUT(out_failure_reason, NM_DEVICE_STATE_REASON_NO_SECRETS);
+            goto out_fail;
+        }
+
+        return NM_ACT_STAGE_RETURN_POSTPONE;
+    }
+
+    if (!wake_on_wlan_enable(self))
+        _LOGW(LOGD_DEVICE | LOGD_WIFI, "Cannot configure WoWLAN.");
+
+    /* have secrets, or no secrets required */
+    if (nm_connection_get_setting_wireless_security(connection)) {
+        _LOGI(LOGD_DEVICE | LOGD_WIFI,
+              "Activation: (wifi) connection '%s' has security, and secrets exist.  No new secrets "
+              "needed.",
+              nm_connection_get_id(connection));
+    } else {
+        _LOGI(LOGD_DEVICE | LOGD_WIFI,
+              "Activation: (wifi) connection '%s' requires no security.  No secrets needed.",
+              nm_connection_get_id(connection));
+    }
+
+    priv->ssid_found = FALSE;
+
+    /* Supplicant requires an initial frequency for Ad-Hoc, Hotspot and Mesh;
+     * if the user didn't specify one and we didn't find an AP that matched
+     * the connection, just pick a frequency the device supports.
+     */
+    if (NM_IN_SET(ap_mode, NM_802_11_MODE_ADHOC, NM_802_11_MODE_MESH) || nm_wifi_ap_is_hotspot(ap))
+        ensure_hotspot_frequency(self, s_wireless, ap);
+
+    if (ap_mode == NM_802_11_MODE_INFRA)
+        set_powersave(device);
+
+    /* Build up the supplicant configuration */
+    config = build_supplicant_config(self, connection, nm_wifi_ap_get_freq(ap), &error);
+    if (!config) {
+        _LOGE(LOGD_DEVICE | LOGD_WIFI,
+              "Activation: (wifi) couldn't build wireless configuration: %s",
+              error->message);
+        g_clear_error(&error);
+        NM_SET_OUT(out_failure_reason, NM_DEVICE_STATE_REASON_SUPPLICANT_CONFIG_FAILED);
+        goto out_fail;
+    }
+
+    /* Tell the supplicant in which bridge the interface is */
+    if ((request = nm_device_get_act_request(device))
+        && (master_ac = nm_active_connection_get_master(NM_ACTIVE_CONNECTION(request)))
+        && (master = nm_active_connection_get_device(master_ac))
+        && nm_device_get_device_type(master) == NM_DEVICE_TYPE_BRIDGE) {
+        nm_supplicant_interface_set_bridge(priv->sup_iface, nm_device_get_iface(master));
+    } else
+        nm_supplicant_interface_set_bridge(priv->sup_iface, NULL);
+
+    nm_supplicant_interface_assoc(priv->sup_iface, config, supplicant_iface_assoc_cb, self);
+
+    /* Set up a timeout on the association attempt */
+    timeout              = nm_device_get_supplicant_timeout(NM_DEVICE(self));
+    priv->sup_timeout_id = g_timeout_add_seconds(timeout, supplicant_connection_timeout_cb, self);
+
+    if (!priv->periodic_update_id)
+        priv->periodic_update_id = g_timeout_add_seconds(6, periodic_update_cb, self);
+
+    /* We'll get stage3 started when the supplicant connects */
+    return NM_ACT_STAGE_RETURN_POSTPONE;
+
+out_fail:
+    cleanup_association_attempt(self, TRUE);
+    wake_on_wlan_restore(self);
+    return NM_ACT_STAGE_RETURN_FAILURE;
+}
+
+static NMActStageReturn
+act_stage3_ip_config_start(NMDevice *           device,
+                           int                  addr_family,
+                           gpointer *           out_config,
+                           NMDeviceStateReason *out_failure_reason)
+{
+    gboolean      indicate_addressing_running;
+    NMConnection *connection;
+    const char *  method;
+
+    connection = nm_device_get_applied_connection(device);
+
+    method = nm_utils_get_ip_config_method(connection, addr_family);
+    if (addr_family == AF_INET)
+        indicate_addressing_running = NM_IN_STRSET(method, NM_SETTING_IP4_CONFIG_METHOD_AUTO);
+    else {
+        indicate_addressing_running = NM_IN_STRSET(method,
+                                                   NM_SETTING_IP6_CONFIG_METHOD_AUTO,
+                                                   NM_SETTING_IP6_CONFIG_METHOD_DHCP);
+    }
+
+    if (indicate_addressing_running)
+        nm_platform_wifi_indicate_addressing_running(nm_device_get_platform(device),
+                                                     nm_device_get_ip_ifindex(device),
+                                                     TRUE);
+
+    return NM_DEVICE_CLASS(nm_device_wifi_parent_class)
+        ->act_stage3_ip_config_start(device, addr_family, out_config, out_failure_reason);
+}
+
+static guint32
+get_configured_mtu(NMDevice *device, NMDeviceMtuSource *out_source, gboolean *out_force)
+{
+    return nm_device_get_configured_mtu_from_connection(device,
+                                                        NM_TYPE_SETTING_WIRELESS,
+                                                        out_source);
+}
+
+static gboolean
+is_static_wep(NMConnection *connection)
+{
+    NMSettingWirelessSecurity *s_wsec;
+    const char *               str;
+
+    g_return_val_if_fail(connection != NULL, FALSE);
+
+    s_wsec = nm_connection_get_setting_wireless_security(connection);
+    if (!s_wsec)
+        return FALSE;
+
+    str = nm_setting_wireless_security_get_key_mgmt(s_wsec);
+    if (g_strcmp0(str, "none") != 0)
+        return FALSE;
+
+    str = nm_setting_wireless_security_get_auth_alg(s_wsec);
+    if (g_strcmp0(str, "leap") == 0)
+        return FALSE;
+
+    return TRUE;
+}
+
+static NMActStageReturn
+act_stage4_ip_config_timeout(NMDevice *           device,
+                             int                  addr_family,
+                             NMDeviceStateReason *out_failure_reason)
+{
+    NMDeviceWifi *       self = NM_DEVICE_WIFI(device);
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    NMConnection *       connection;
+    NMSettingIPConfig *  s_ip;
+    gboolean             may_fail;
+
+    connection = nm_device_get_applied_connection(device);
+    s_ip       = nm_connection_get_setting_ip_config(connection, addr_family);
+    may_fail   = nm_setting_ip_config_get_may_fail(s_ip);
+
+    if (priv->mode == NM_802_11_MODE_AP)
+        goto call_parent;
+
+    if (may_fail || !is_static_wep(connection)) {
+        /* Not static WEP or failure allowed; let superclass handle it */
+        goto call_parent;
+    }
+
+    /* If IP configuration times out and it's a static WEP connection, that
+     * usually means the WEP key is wrong.  WEP's Open System auth mode has
+     * no provision for figuring out if the WEP key is wrong, so you just have
+     * to wait for DHCP to fail to figure it out.  For all other Wi-Fi security
+     * types (open, WPA, 802.1x, etc) if the secrets/certs were wrong the
+     * connection would have failed before IP configuration.
+     *
+     * Activation failed, we must have bad encryption key */
+    _LOGW(LOGD_DEVICE | LOGD_WIFI,
+          "Activation: (wifi) could not get IP configuration for connection '%s'.",
+          nm_connection_get_id(connection));
+
+    if (!handle_auth_or_fail(self, NULL, TRUE)) {
+        NM_SET_OUT(out_failure_reason, NM_DEVICE_STATE_REASON_NO_SECRETS);
+        return NM_ACT_STAGE_RETURN_FAILURE;
+    }
+
+    _LOGI(LOGD_DEVICE | LOGD_WIFI, "Activation: (wifi) asking for new secrets");
+    return NM_ACT_STAGE_RETURN_POSTPONE;
+
+call_parent:
+    return NM_DEVICE_CLASS(nm_device_wifi_parent_class)
+        ->act_stage4_ip_config_timeout(device, addr_family, out_failure_reason);
+}
+
+static void
+activation_success_handler(NMDevice *device)
+{
+    NMDeviceWifi *       self    = NM_DEVICE_WIFI(device);
+    NMDeviceWifiPrivate *priv    = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    int                  ifindex = nm_device_get_ifindex(device);
+    NMActRequest *       req;
+
+    req = nm_device_get_act_request(device);
+    g_assert(req);
+
+    /* Clear any critical protocol notification in the wifi stack */
+    nm_platform_wifi_indicate_addressing_running(nm_device_get_platform(device), ifindex, FALSE);
+
+    /* There should always be a current AP, either a fake one because we haven't
+     * seen a scan result for the activated AP yet, or a real one from the
+     * supplicant's scan list.
+     */
+    g_warn_if_fail(priv->current_ap);
+    if (priv->current_ap) {
+        if (nm_wifi_ap_get_fake(priv->current_ap)) {
+            gboolean    ap_changed   = FALSE;
+            gboolean    update_bssid = !nm_wifi_ap_get_address(priv->current_ap);
+            gboolean    update_rate  = !nm_wifi_ap_get_max_bitrate(priv->current_ap);
+            NMEtherAddr bssid;
+            guint32     rate;
+
+            /* If the activation AP hasn't been seen by the supplicant in a scan
+             * yet, it will be "fake".  This usually happens for Ad-Hoc and
+             * AP-mode connections.  Fill in the details from the device itself
+             * until the supplicant sends the scan result.
+             */
+            if (!nm_wifi_ap_get_freq(priv->current_ap))
+                ap_changed |= nm_wifi_ap_set_freq(
+                    priv->current_ap,
+                    nm_platform_wifi_get_frequency(nm_device_get_platform(device), ifindex));
+
+            if ((update_bssid || update_rate)
+                && nm_platform_wifi_get_station(nm_device_get_platform(device),
+                                                ifindex,
+                                                update_bssid ? &bssid : NULL,
+                                                NULL,
+                                                update_rate ? &rate : NULL)) {
+                if (update_bssid && nm_ether_addr_is_valid(&bssid))
+                    ap_changed |= nm_wifi_ap_set_address_bin(priv->current_ap, &bssid);
+                if (update_rate)
+                    ap_changed |= nm_wifi_ap_set_max_bitrate(priv->current_ap, rate);
+            }
+
+            if (ap_changed)
+                _ap_dump(self, LOGL_DEBUG, priv->current_ap, "updated", 0);
+        }
+
+        nm_active_connection_set_specific_object(
+            NM_ACTIVE_CONNECTION(req),
+            nm_dbus_object_get_path(NM_DBUS_OBJECT(priv->current_ap)));
+    }
+
+    periodic_update(self);
+
+    update_seen_bssids_cache(self, priv->current_ap);
+
+    priv->scan_periodic_interval_sec = 0;
+    priv->scan_periodic_next_msec    = 0;
+}
+
+static void
+device_state_changed(NMDevice *          device,
+                     NMDeviceState       new_state,
+                     NMDeviceState       old_state,
+                     NMDeviceStateReason reason)
+{
+    NMDeviceWifi *       self      = NM_DEVICE_WIFI(device);
+    NMDeviceWifiPrivate *priv      = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    gboolean             clear_aps = FALSE;
+
+    if (new_state > NM_DEVICE_STATE_ACTIVATED)
+        wifi_secrets_cancel(self);
+
+    if (new_state <= NM_DEVICE_STATE_UNAVAILABLE) {
+        /* Clean up the supplicant interface because in these states the
+         * device cannot be used.
+         */
+        supplicant_interface_release(self);
+
+        nm_clear_g_source(&priv->periodic_update_id);
+
+        cleanup_association_attempt(self, TRUE);
+        cleanup_supplicant_failures(self);
+        remove_all_aps(self);
+    }
+
+    switch (new_state) {
+    case NM_DEVICE_STATE_UNMANAGED:
+        clear_aps = TRUE;
+        break;
+    case NM_DEVICE_STATE_UNAVAILABLE:
+        /* If the device is enabled and the supplicant manager is ready,
+         * acquire a supplicant interface and transition to DISCONNECTED because
+         * the device is now ready to use.
+         */
+        if (priv->enabled && (nm_device_get_firmware_missing(device) == FALSE)) {
+            if (!priv->sup_iface)
+                supplicant_interface_acquire(self);
+        }
+        clear_aps = TRUE;
+        break;
+    case NM_DEVICE_STATE_NEED_AUTH:
+        if (priv->sup_iface)
+            nm_supplicant_interface_disconnect(priv->sup_iface);
+        break;
+    case NM_DEVICE_STATE_IP_CHECK:
+        /* Clear any critical protocol notification in the wifi stack */
+        nm_platform_wifi_indicate_addressing_running(nm_device_get_platform(device),
+                                                     nm_device_get_ifindex(device),
+                                                     FALSE);
+        break;
+    case NM_DEVICE_STATE_ACTIVATED:
+        activation_success_handler(device);
+        break;
+    case NM_DEVICE_STATE_FAILED:
+        /* Clear any critical protocol notification in the wifi stack */
+        nm_platform_wifi_indicate_addressing_running(nm_device_get_platform(device),
+                                                     nm_device_get_ifindex(device),
+                                                     FALSE);
+        break;
+    case NM_DEVICE_STATE_DISCONNECTED:
+        break;
+    default:
+        break;
+    }
+
+    if (clear_aps)
+        remove_all_aps(self);
+
+    _scan_notify_allowed(self, NM_TERNARY_DEFAULT);
+}
+
+static gboolean
+get_enabled(NMDevice *device)
+{
+    return NM_DEVICE_WIFI_GET_PRIVATE(device)->enabled;
+}
+
+static void
+set_enabled(NMDevice *device, gboolean enabled)
+{
+    NMDeviceWifi *       self = NM_DEVICE_WIFI(device);
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    NMDeviceState        state;
+
+    enabled = !!enabled;
+
+    if (priv->enabled == enabled)
+        return;
+
+    priv->enabled = enabled;
+
+    _LOGD(LOGD_WIFI, "device now %s", enabled ? "enabled" : "disabled");
+
+    state = nm_device_get_state(NM_DEVICE(self));
+    if (state < NM_DEVICE_STATE_UNAVAILABLE) {
+        _LOGD(LOGD_WIFI, "(%s): device blocked by UNMANAGED state", enabled ? "enable" : "disable");
+        return;
+    }
+
+    if (enabled) {
+        gboolean no_firmware = FALSE;
+
+        if (state != NM_DEVICE_STATE_UNAVAILABLE)
+            _LOGW(LOGD_CORE, "not in expected unavailable state!");
+
+        if (!nm_device_bring_up(NM_DEVICE(self), TRUE, &no_firmware)) {
+            _LOGD(LOGD_WIFI, "enable blocked by failure to bring device up");
+
+            if (no_firmware)
+                nm_device_set_firmware_missing(NM_DEVICE(device), TRUE);
+            else {
+                /* The device sucks, or the kernel was lying to us about the killswitch state */
+                priv->enabled = FALSE;
+            }
+            return;
+        }
+
+        /* Re-initialize the supplicant interface and wait for it to be ready */
+        cleanup_supplicant_failures(self);
+        supplicant_interface_release(self);
+        supplicant_interface_acquire(self);
+
+        _LOGD(LOGD_WIFI, "enable waiting on supplicant state");
+    } else {
+        nm_device_state_changed(NM_DEVICE(self),
+                                NM_DEVICE_STATE_UNAVAILABLE,
+                                NM_DEVICE_STATE_REASON_NONE);
+        nm_device_take_down(NM_DEVICE(self), TRUE);
+    }
+}
+
+static gboolean
+get_guessed_metered(NMDevice *device)
+{
+    NMDeviceWifi *       self = NM_DEVICE_WIFI(device);
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    return priv->current_ap && nm_wifi_ap_get_metered(priv->current_ap);
+}
+
+static gboolean
+can_reapply_change(NMDevice *  device,
+                   const char *setting_name,
+                   NMSetting * s_old,
+                   NMSetting * s_new,
+                   GHashTable *diffs,
+                   GError **   error)
+{
+    NMDeviceClass *device_class;
+
+    /* Only handle wireless setting here, delegate other settings to parent class */
+    if (nm_streq(setting_name, NM_SETTING_WIRELESS_SETTING_NAME)) {
+        return nm_device_hash_check_invalid_keys(
+            diffs,
+            NM_SETTING_WIRELESS_SETTING_NAME,
+            error,
+            NM_SETTING_WIRELESS_SEEN_BSSIDS, /* ignored */
+            NM_SETTING_WIRELESS_MTU,         /* reapplied with IP config */
+            NM_SETTING_WIRELESS_WAKE_ON_WLAN);
+    }
+
+    device_class = NM_DEVICE_CLASS(nm_device_wifi_parent_class);
+    return device_class->can_reapply_change(device, setting_name, s_old, s_new, diffs, error);
+}
+
+static void
+reapply_connection(NMDevice *device, NMConnection *con_old, NMConnection *con_new)
+{
+    NMDeviceWifi *self  = NM_DEVICE_WIFI(device);
+    NMDeviceState state = nm_device_get_state(device);
+
+    NM_DEVICE_CLASS(nm_device_wifi_parent_class)->reapply_connection(device, con_old, con_new);
+
+    _LOGD(LOGD_DEVICE, "reapplying wireless settings");
+
+    if (state >= NM_DEVICE_STATE_CONFIG && !wake_on_wlan_enable(self))
+        _LOGW(LOGD_DEVICE | LOGD_WIFI, "Cannot configure WoWLAN.");
+}
+
+/*****************************************************************************/
+
+static void
+get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec)
+{
+    NMDeviceWifi *       self = NM_DEVICE_WIFI(object);
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+    const char **        list;
+
+    switch (prop_id) {
+    case PROP_MODE:
+        g_value_set_uint(value, priv->mode);
+        break;
+    case PROP_BITRATE:
+        g_value_set_uint(value, priv->rate);
+        break;
+    case PROP_CAPABILITIES:
+        g_value_set_uint(value, priv->capabilities);
+        break;
+    case PROP_ACCESS_POINTS:
+        list = nm_wifi_aps_get_paths(&priv->aps_lst_head, TRUE);
+        g_value_take_boxed(value, nm_utils_strv_make_deep_copied(list));
+        break;
+    case PROP_ACTIVE_ACCESS_POINT:
+        nm_dbus_utils_g_value_set_object_path(value, priv->current_ap);
+        break;
+    case PROP_SCANNING:
+        g_value_set_boolean(value, nm_device_wifi_get_scanning(self));
+        break;
+    case PROP_LAST_SCAN:
+        g_value_set_int64(
+            value,
+            priv->scan_last_complete_msec > 0
+                ? nm_utils_monotonic_timestamp_as_boottime(priv->scan_last_complete_msec,
+                                                           NM_UTILS_NSEC_PER_MSEC)
+                : (gint64) -1);
+        break;
+    default:
+        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
+        break;
+    }
+}
+
+static void
+set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec)
+{
+    NMDeviceWifi *       device = NM_DEVICE_WIFI(object);
+    NMDeviceWifiPrivate *priv   = NM_DEVICE_WIFI_GET_PRIVATE(device);
+
+    switch (prop_id) {
+    case PROP_CAPABILITIES:
+        /* construct-only */
+        priv->capabilities = g_value_get_uint(value);
+        break;
+    default:
+        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
+        break;
+    }
+}
+
+/*****************************************************************************/
+
+static void
+nm_device_wifi_init(NMDeviceWifi *self)
+{
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    c_list_init(&priv->aps_lst_head);
+    c_list_init(&priv->scanning_prohibited_lst_head);
+    c_list_init(&priv->scan_request_ssids_lst_head);
+    priv->aps_idx_by_supplicant_path = g_hash_table_new(nm_direct_hash, NULL);
+
+    priv->scan_last_request_started_at_msec = G_MININT64;
+    priv->hidden_probe_scan_warn            = TRUE;
+    priv->mode                              = NM_802_11_MODE_INFRA;
+    priv->wowlan_restore                    = NM_SETTING_WIRELESS_WAKE_ON_WLAN_IGNORE;
+}
+
+static void
+constructed(GObject *object)
+{
+    NMDeviceWifi *       self = NM_DEVICE_WIFI(object);
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    G_OBJECT_CLASS(nm_device_wifi_parent_class)->constructed(object);
+
+    if (priv->capabilities & NM_WIFI_DEVICE_CAP_AP)
+        _LOGI(LOGD_PLATFORM | LOGD_WIFI, "driver supports Access Point (AP) mode");
+
+    /* Connect to the supplicant manager */
+    priv->sup_mgr = g_object_ref(nm_supplicant_manager_get());
+}
+
+NMDevice *
+nm_device_wifi_new(const char *iface, NMDeviceWifiCapabilities capabilities)
+{
+    return g_object_new(NM_TYPE_DEVICE_WIFI,
+                        NM_DEVICE_IFACE,
+                        iface,
+                        NM_DEVICE_TYPE_DESC,
+                        "802.11 Wi-Fi",
+                        NM_DEVICE_DEVICE_TYPE,
+                        NM_DEVICE_TYPE_WIFI,
+                        NM_DEVICE_LINK_TYPE,
+                        NM_LINK_TYPE_WIFI,
+                        NM_DEVICE_RFKILL_TYPE,
+                        RFKILL_TYPE_WLAN,
+                        NM_DEVICE_WIFI_CAPABILITIES,
+                        (guint) capabilities,
+                        NULL);
+}
+
+static void
+dispose(GObject *object)
+{
+    NMDeviceWifi *       self = NM_DEVICE_WIFI(object);
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    nm_assert(c_list_is_empty(&priv->scanning_prohibited_lst_head));
+
+    nm_clear_g_source(&priv->periodic_update_id);
+
+    wifi_secrets_cancel(self);
+
+    cleanup_association_attempt(self, TRUE);
+    supplicant_interface_release(self);
+    cleanup_supplicant_failures(self);
+
+    g_clear_object(&priv->sup_mgr);
+
+    remove_all_aps(self);
+
+    if (priv->p2p_device) {
+        /* Destroy the P2P device. */
+        g_object_remove_weak_pointer(G_OBJECT(priv->p2p_device), (gpointer *) &priv->p2p_device);
+        nm_device_wifi_p2p_remove(g_steal_pointer(&priv->p2p_device));
+    }
+
+    G_OBJECT_CLASS(nm_device_wifi_parent_class)->dispose(object);
+}
+
+static void
+finalize(GObject *object)
+{
+    NMDeviceWifi *       self = NM_DEVICE_WIFI(object);
+    NMDeviceWifiPrivate *priv = NM_DEVICE_WIFI_GET_PRIVATE(self);
+
+    nm_assert(c_list_is_empty(&priv->aps_lst_head));
+    nm_assert(g_hash_table_size(priv->aps_idx_by_supplicant_path) == 0);
+
+    g_hash_table_unref(priv->aps_idx_by_supplicant_path);
+
+    G_OBJECT_CLASS(nm_device_wifi_parent_class)->finalize(object);
+}
+
+static void
+nm_device_wifi_class_init(NMDeviceWifiClass *klass)
+{
+    GObjectClass *     object_class      = G_OBJECT_CLASS(klass);
+    NMDBusObjectClass *dbus_object_class = NM_DBUS_OBJECT_CLASS(klass);
+    NMDeviceClass *    device_class      = NM_DEVICE_CLASS(klass);
+
+    object_class->constructed  = constructed;
+    object_class->get_property = get_property;
+    object_class->set_property = set_property;
+    object_class->dispose      = dispose;
+    object_class->finalize     = finalize;
+
+    dbus_object_class->interface_infos =
+        NM_DBUS_INTERFACE_INFOS(&nm_interface_info_device_wireless);
+
+    device_class->connection_type_supported        = NM_SETTING_WIRELESS_SETTING_NAME;
+    device_class->connection_type_check_compatible = NM_SETTING_WIRELESS_SETTING_NAME;
+    device_class->link_types                       = NM_DEVICE_DEFINE_LINK_TYPES(NM_LINK_TYPE_WIFI);
+
+    device_class->can_auto_connect            = can_auto_connect;
+    device_class->get_autoconnect_allowed     = get_autoconnect_allowed;
+    device_class->is_available                = is_available;
+    device_class->check_connection_compatible = check_connection_compatible;
+    device_class->check_connection_available  = check_connection_available;
+    device_class->complete_connection         = complete_connection;
+    device_class->get_enabled                 = get_enabled;
+    device_class->get_guessed_metered         = get_guessed_metered;
+    device_class->set_enabled                 = set_enabled;
+
+    device_class->act_stage1_prepare           = act_stage1_prepare;
+    device_class->act_stage2_config            = act_stage2_config;
+    device_class->get_configured_mtu           = get_configured_mtu;
+    device_class->act_stage3_ip_config_start   = act_stage3_ip_config_start;
+    device_class->act_stage4_ip_config_timeout = act_stage4_ip_config_timeout;
+    device_class->deactivate_async             = deactivate_async;
+    device_class->deactivate                   = deactivate;
+    device_class->deactivate_reset_hw_addr     = deactivate_reset_hw_addr;
+    device_class->unmanaged_on_quit            = unmanaged_on_quit;
+    device_class->can_reapply_change           = can_reapply_change;
+    device_class->reapply_connection           = reapply_connection;
+
+    device_class->state_changed = device_state_changed;
+
+    obj_properties[PROP_MODE] = g_param_spec_uint(NM_DEVICE_WIFI_MODE,
+                                                  "",
+                                                  "",
+                                                  NM_802_11_MODE_UNKNOWN,
+                                                  NM_802_11_MODE_AP,
+                                                  NM_802_11_MODE_INFRA,
+                                                  G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_BITRATE] = g_param_spec_uint(NM_DEVICE_WIFI_BITRATE,
+                                                     "",
+                                                     "",
+                                                     0,
+                                                     G_MAXUINT32,
+                                                     0,
+                                                     G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_ACCESS_POINTS] =
+        g_param_spec_boxed(NM_DEVICE_WIFI_ACCESS_POINTS,
+                           "",
+                           "",
+                           G_TYPE_STRV,
+                           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_ACTIVE_ACCESS_POINT] =
+        g_param_spec_string(NM_DEVICE_WIFI_ACTIVE_ACCESS_POINT,
+                            "",
+                            "",
+                            NULL,
+                            G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_CAPABILITIES] =
+        g_param_spec_uint(NM_DEVICE_WIFI_CAPABILITIES,
+                          "",
+                          "",
+                          0,
+                          G_MAXUINT32,
+                          NM_WIFI_DEVICE_CAP_NONE,
+                          G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_SCANNING] = g_param_spec_boolean(NM_DEVICE_WIFI_SCANNING,
+                                                         "",
+                                                         "",
+                                                         FALSE,
+                                                         G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_LAST_SCAN] = g_param_spec_int64(NM_DEVICE_WIFI_LAST_SCAN,
+                                                        "",
+                                                        "",
+                                                        -1,
+                                                        G_MAXINT64,
+                                                        -1,
+                                                        G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    g_object_class_install_properties(object_class, _PROPERTY_ENUMS_LAST, obj_properties);
+
+    signals[P2P_DEVICE_CREATED] = g_signal_new(NM_DEVICE_WIFI_P2P_DEVICE_CREATED,
+                                               G_OBJECT_CLASS_TYPE(object_class),
+                                               G_SIGNAL_RUN_LAST,
+                                               0,
+                                               NULL,
+                                               NULL,
+                                               g_cclosure_marshal_VOID__OBJECT,
+                                               G_TYPE_NONE,
+                                               1,
+                                               NM_TYPE_DEVICE);
+}
diff --git a/src/core/devices/wifi/nm-device-wifi.h b/src/core/devices/wifi/nm-device-wifi.h
new file mode 100644
index 00000000..d9e9038c
--- /dev/null
+++ b/src/core/devices/wifi/nm-device-wifi.h
@@ -0,0 +1,52 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+/*
+ * Copyright (C) 2005 - 2016 Red Hat, Inc.
+ * Copyright (C) 2006 - 2008 Novell, Inc.
+ */
+
+#ifndef __NETWORKMANAGER_DEVICE_WIFI_H__
+#define __NETWORKMANAGER_DEVICE_WIFI_H__
+
+#include "devices/nm-device.h"
+
+#define NM_TYPE_DEVICE_WIFI (nm_device_wifi_get_type())
+#define NM_DEVICE_WIFI(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), NM_TYPE_DEVICE_WIFI, NMDeviceWifi))
+#define NM_DEVICE_WIFI_CLASS(klass) \
+    (G_TYPE_CHECK_CLASS_CAST((klass), NM_TYPE_DEVICE_WIFI, NMDeviceWifiClass))
+#define NM_IS_DEVICE_WIFI(obj)         (G_TYPE_CHECK_INSTANCE_TYPE((obj), NM_TYPE_DEVICE_WIFI))
+#define NM_IS_DEVICE_WIFI_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), NM_TYPE_DEVICE_WIFI))
+#define NM_DEVICE_WIFI_GET_CLASS(obj) \
+    (G_TYPE_INSTANCE_GET_CLASS((obj), NM_TYPE_DEVICE_WIFI, NMDeviceWifiClass))
+
+#define NM_DEVICE_WIFI_MODE                "mode"
+#define NM_DEVICE_WIFI_BITRATE             "bitrate"
+#define NM_DEVICE_WIFI_ACCESS_POINTS       "access-points"
+#define NM_DEVICE_WIFI_ACTIVE_ACCESS_POINT "active-access-point"
+#define NM_DEVICE_WIFI_CAPABILITIES        "wireless-capabilities"
+#define NM_DEVICE_WIFI_SCANNING            "scanning"
+#define NM_DEVICE_WIFI_LAST_SCAN           "last-scan"
+
+#define NM_DEVICE_WIFI_P2P_DEVICE_CREATED "p2p-device-created"
+
+typedef struct _NMDeviceWifi      NMDeviceWifi;
+typedef struct _NMDeviceWifiClass NMDeviceWifiClass;
+
+GType nm_device_wifi_get_type(void);
+
+NMDevice *nm_device_wifi_new(const char *iface, NMDeviceWifiCapabilities capabilities);
+
+const CList *_nm_device_wifi_get_aps(NMDeviceWifi *self);
+
+void _nm_device_wifi_request_scan(NMDeviceWifi *         self,
+                                  GVariant *             options,
+                                  GDBusMethodInvocation *invocation);
+
+GPtrArray *nmtst_ssids_options_to_ptrarray(GVariant *value, GError **error);
+
+gboolean nm_device_wifi_get_scanning(NMDeviceWifi *self);
+
+void nm_device_wifi_scanning_prohibited_track(NMDeviceWifi *self,
+                                              gpointer      tag,
+                                              gboolean      temporarily_prohibited);
+
+#endif /* __NETWORKMANAGER_DEVICE_WIFI_H__ */
diff --git a/src/core/devices/wifi/nm-iwd-manager.c b/src/core/devices/wifi/nm-iwd-manager.c
new file mode 100644
index 00000000..b4b019d3
--- /dev/null
+++ b/src/core/devices/wifi/nm-iwd-manager.c
@@ -0,0 +1,1359 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+/*
+ * Copyright (C) 2017 Intel Corporation
+ */
+
+#include "src/core/nm-default-daemon.h"
+
+#include "nm-iwd-manager.h"
+
+#include <net/if.h>
+
+#include "nm-core-internal.h"
+#include "nm-manager.h"
+#include "nm-device-iwd.h"
+#include "nm-wifi-utils.h"
+#include "nm-glib-aux/nm-random-utils.h"
+#include "settings/nm-settings.h"
+#include "nm-std-aux/nm-dbus-compat.h"
+
+/*****************************************************************************/
+
+typedef struct {
+    const char *         name;
+    NMIwdNetworkSecurity security;
+    char                 buf[0];
+} KnownNetworkId;
+
+typedef struct {
+    GDBusProxy *          known_network;
+    NMSettingsConnection *mirror_connection;
+} KnownNetworkData;
+
+typedef struct {
+    NMManager *         manager;
+    NMSettings *        settings;
+    GCancellable *      cancellable;
+    gboolean            running;
+    GDBusObjectManager *object_manager;
+    guint               agent_id;
+    char *              agent_path;
+    GHashTable *        known_networks;
+    NMDeviceIwd *       last_agent_call_device;
+} NMIwdManagerPrivate;
+
+struct _NMIwdManager {
+    GObject             parent;
+    NMIwdManagerPrivate _priv;
+};
+
+struct _NMIwdManagerClass {
+    GObjectClass parent;
+};
+
+G_DEFINE_TYPE(NMIwdManager, nm_iwd_manager, G_TYPE_OBJECT)
+
+#define NM_IWD_MANAGER_GET_PRIVATE(self) _NM_GET_PRIVATE(self, NMIwdManager, NM_IS_IWD_MANAGER)
+
+/*****************************************************************************/
+
+#define _NMLOG_PREFIX_NAME "iwd-manager"
+#define _NMLOG_DOMAIN      LOGD_WIFI
+
+#define _NMLOG(level, ...)                                                 \
+    G_STMT_START                                                           \
+    {                                                                      \
+        if (nm_logging_enabled(level, _NMLOG_DOMAIN)) {                    \
+            char __prefix[32];                                             \
+                                                                           \
+            if (self)                                                      \
+                g_snprintf(__prefix,                                       \
+                           sizeof(__prefix),                               \
+                           "%s[%p]",                                       \
+                           ""_NMLOG_PREFIX_NAME                            \
+                           "",                                             \
+                           (self));                                        \
+            else                                                           \
+                g_strlcpy(__prefix, _NMLOG_PREFIX_NAME, sizeof(__prefix)); \
+            _nm_log((level),                                               \
+                    (_NMLOG_DOMAIN),                                       \
+                    0,                                                     \
+                    NULL,                                                  \
+                    NULL,                                                  \
+                    "%s: " _NM_UTILS_MACRO_FIRST(__VA_ARGS__),             \
+                    __prefix _NM_UTILS_MACRO_REST(__VA_ARGS__));           \
+        }                                                                  \
+    }                                                                      \
+    G_STMT_END
+
+/*****************************************************************************/
+
+static void mirror_connection_take_and_delete(NMSettingsConnection *sett_conn,
+                                              KnownNetworkData *    data);
+
+/*****************************************************************************/
+
+static const char *
+get_variant_string_or_null(GVariant *v)
+{
+    if (!v)
+        return NULL;
+
+    if (!g_variant_is_of_type(v, G_VARIANT_TYPE_STRING)
+        && !g_variant_is_of_type(v, G_VARIANT_TYPE_OBJECT_PATH))
+        return NULL;
+
+    return g_variant_get_string(v, NULL);
+}
+
+static const char *
+get_property_string_or_null(GDBusProxy *proxy, const char *property)
+{
+    gs_unref_variant GVariant *value = NULL;
+
+    if (!proxy || !property)
+        return NULL;
+
+    value = g_dbus_proxy_get_cached_property(proxy, property);
+
+    return get_variant_string_or_null(value);
+}
+
+static gboolean
+get_property_bool(GDBusProxy *proxy, const char *property, gboolean default_val)
+{
+    gs_unref_variant GVariant *value = NULL;
+
+    if (!proxy || !property)
+        return default_val;
+
+    value = g_dbus_proxy_get_cached_property(proxy, property);
+    if (!value || !g_variant_is_of_type(value, G_VARIANT_TYPE_BOOLEAN))
+        return default_val;
+
+    return g_variant_get_boolean(value);
+}
+
+static NMDeviceIwd *
+get_device_from_network(NMIwdManager *self, GDBusProxy *network)
+{
+    NMIwdManagerPrivate *priv = NM_IWD_MANAGER_GET_PRIVATE(self);
+    const char *         ifname;
+    const char *         device_path;
+    NMDevice *           device;
+    gs_unref_object GDBusInterface *device_obj = NULL;
+
+    /* Try not to rely on the path of the Device being a prefix of the
+     * Network's object path.
+     */
+
+    device_path = get_property_string_or_null(network, "Device");
+    if (!device_path) {
+        _LOGD("Device not cached for network at %s", g_dbus_proxy_get_object_path(network));
+        return NULL;
+    }
+
+    device_obj = g_dbus_object_manager_get_interface(priv->object_manager,
+                                                     device_path,
+                                                     NM_IWD_DEVICE_INTERFACE);
+
+    ifname = get_property_string_or_null(G_DBUS_PROXY(device_obj), "Name");
+    if (!ifname) {
+        _LOGD("Name not cached for device at %s", device_path);
+        return NULL;
+    }
+
+    device = nm_manager_get_device(priv->manager, ifname, NM_DEVICE_TYPE_WIFI);
+    if (!device || !NM_IS_DEVICE_IWD(device)) {
+        _LOGD("NM device %s is not an IWD-managed device", ifname);
+        return NULL;
+    }
+
+    return NM_DEVICE_IWD(device);
+}
+
+static void
+agent_dbus_method_cb(GDBusConnection *      connection,
+                     const char *           sender,
+                     const char *           object_path,
+                     const char *           interface_name,
+                     const char *           method_name,
+                     GVariant *             parameters,
+                     GDBusMethodInvocation *invocation,
+                     gpointer               user_data)
+{
+    NMIwdManager *       self = user_data;
+    NMIwdManagerPrivate *priv = NM_IWD_MANAGER_GET_PRIVATE(self);
+    const char *         network_path;
+    NMDeviceIwd *        device;
+    gs_free char *       name_owner         = NULL;
+    gs_unref_object GDBusInterface *network = NULL;
+
+    /* Be paranoid and check the sender address */
+    name_owner = g_dbus_object_manager_client_get_name_owner(
+        G_DBUS_OBJECT_MANAGER_CLIENT(priv->object_manager));
+    if (!nm_streq0(name_owner, sender))
+        goto return_error;
+
+    if (!strcmp(method_name, "Cancel")) {
+        const char *reason = NULL;
+
+        g_variant_get(parameters, "(&s)", &reason);
+        _LOGD("agent-request: Cancel reason: %s", reason);
+
+        if (!priv->last_agent_call_device)
+            goto return_error;
+
+        if (nm_device_iwd_agent_query(priv->last_agent_call_device, NULL)) {
+            priv->last_agent_call_device = NULL;
+            g_dbus_method_invocation_return_value(invocation, NULL);
+            return;
+        }
+
+        priv->last_agent_call_device = NULL;
+        goto return_error;
+    }
+
+    if (!strcmp(method_name, "RequestUserPassword"))
+        g_variant_get(parameters, "(&os)", &network_path, NULL);
+    else
+        g_variant_get(parameters, "(&o)", &network_path);
+
+    network = g_dbus_object_manager_get_interface(priv->object_manager,
+                                                  network_path,
+                                                  NM_IWD_NETWORK_INTERFACE);
+    if (!network) {
+        _LOGE("agent-request: unable to find the network object");
+        goto return_error;
+    }
+
+    device = get_device_from_network(self, G_DBUS_PROXY(network));
+    if (!device) {
+        _LOGD("agent-request: device not found in IWD Agent request");
+        goto return_error;
+    }
+
+    if (nm_device_iwd_agent_query(device, invocation)) {
+        priv->last_agent_call_device = device;
+        return;
+    }
+
+    _LOGD("agent-request: device %s did not handle the IWD Agent request",
+          nm_device_get_iface(NM_DEVICE(device)));
+
+return_error:
+    /* IWD doesn't look at the specific error */
+    g_dbus_method_invocation_return_error_literal(invocation,
+                                                  NM_DEVICE_ERROR,
+                                                  NM_DEVICE_ERROR_INVALID_CONNECTION,
+                                                  "Secrets not available for this connection");
+}
+
+static const GDBusInterfaceInfo iwd_agent_iface_info = NM_DEFINE_GDBUS_INTERFACE_INFO_INIT(
+    "net.connman.iwd.Agent",
+    .methods = NM_DEFINE_GDBUS_METHOD_INFOS(
+        NM_DEFINE_GDBUS_METHOD_INFO(
+            "RequestPassphrase",
+            .in_args  = NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("network", "o"), ),
+            .out_args = NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("passphrase", "s"), ), ),
+        NM_DEFINE_GDBUS_METHOD_INFO(
+            "RequestPrivateKeyPassphrase",
+            .in_args  = NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("network", "o"), ),
+            .out_args = NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("passphrase", "s"), ), ),
+        NM_DEFINE_GDBUS_METHOD_INFO(
+            "RequestUserNameAndPassword",
+            .in_args  = NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("network", "o"), ),
+            .out_args = NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("user", "s"),
+                                                  NM_DEFINE_GDBUS_ARG_INFO("password", "s"), ), ),
+        NM_DEFINE_GDBUS_METHOD_INFO(
+            "RequestUserPassword",
+            .in_args  = NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("network", "o"),
+                                                 NM_DEFINE_GDBUS_ARG_INFO("user", "s"), ),
+            .out_args = NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("password", "s"), ), ),
+        NM_DEFINE_GDBUS_METHOD_INFO("Cancel",
+                                    .in_args = NM_DEFINE_GDBUS_ARG_INFOS(
+                                        NM_DEFINE_GDBUS_ARG_INFO("reason", "s"), ), ), ), );
+
+static guint
+iwd_agent_export(GDBusConnection *connection, gpointer user_data, char **agent_path, GError **error)
+{
+    static const GDBusInterfaceVTable vtable = {
+        .method_call = agent_dbus_method_cb,
+    };
+    char         path[50];
+    unsigned int rnd;
+    guint        id;
+
+    nm_utils_random_bytes(&rnd, sizeof(rnd));
+
+    nm_sprintf_buf(path, "/agent/%u", rnd);
+
+    id =
+        g_dbus_connection_register_object(connection,
+                                          path,
+                                          NM_UNCONST_PTR(GDBusInterfaceInfo, &iwd_agent_iface_info),
+                                          &vtable,
+                                          user_data,
+                                          NULL,
+                                          error);
+
+    if (id)
+        *agent_path = g_strdup(path);
+    return id;
+}
+
+static void
+register_agent(NMIwdManager *self)
+{
+    NMIwdManagerPrivate *priv = NM_IWD_MANAGER_GET_PRIVATE(self);
+    GDBusInterface *     agent_manager;
+
+    agent_manager = g_dbus_object_manager_get_interface(priv->object_manager,
+                                                        "/net/connman/iwd", /* IWD 1.0+ */
+                                                        NM_IWD_AGENT_MANAGER_INTERFACE);
+    if (!agent_manager) {
+        _LOGE("unable to register the IWD Agent: PSK/8021x Wi-Fi networks may not work");
+        return;
+    }
+
+    /* Register our agent */
+    g_dbus_proxy_call(G_DBUS_PROXY(agent_manager),
+                      "RegisterAgent",
+                      g_variant_new("(o)", priv->agent_path),
+                      G_DBUS_CALL_FLAGS_NONE,
+                      -1,
+                      NULL,
+                      NULL,
+                      NULL);
+
+    g_object_unref(agent_manager);
+}
+
+/*****************************************************************************/
+
+static KnownNetworkId *
+known_network_id_new(const char *name, NMIwdNetworkSecurity security)
+{
+    KnownNetworkId *id;
+    gsize           strsize = strlen(name) + 1;
+
+    id           = g_malloc(sizeof(KnownNetworkId) + strsize);
+    id->name     = id->buf;
+    id->security = security;
+    memcpy(id->buf, name, strsize);
+
+    return id;
+}
+
+static guint
+known_network_id_hash(KnownNetworkId *id)
+{
+    NMHashState h;
+
+    nm_hash_init(&h, 1947951703u);
+    nm_hash_update_val(&h, id->security);
+    nm_hash_update_str(&h, id->name);
+    return nm_hash_complete(&h);
+}
+
+static gboolean
+known_network_id_equal(KnownNetworkId *a, KnownNetworkId *b)
+{
+    return a->security == b->security && nm_streq(a->name, b->name);
+}
+
+static void
+known_network_data_free(KnownNetworkData *network)
+{
+    if (!network)
+        return;
+
+    g_object_unref(network->known_network);
+    mirror_connection_take_and_delete(network->mirror_connection, network);
+    g_slice_free(KnownNetworkData, network);
+}
+
+/*****************************************************************************/
+
+static void
+set_device_dbus_object(NMIwdManager *self, GDBusProxy *proxy, GDBusObject *object)
+{
+    NMIwdManagerPrivate *priv = NM_IWD_MANAGER_GET_PRIVATE(self);
+    const char *         ifname;
+    int                  ifindex;
+    NMDevice *           device;
+    int                  errsv;
+
+    ifname = get_property_string_or_null(proxy, "Name");
+    if (!ifname) {
+        _LOGE("Name not cached for Device at %s", g_dbus_proxy_get_object_path(proxy));
+        return;
+    }
+
+    ifindex = if_nametoindex(ifname);
+
+    if (!ifindex) {
+        errsv = errno;
+        _LOGE("if_nametoindex failed for Name %s for Device at %s: %i",
+              ifname,
+              g_dbus_proxy_get_object_path(proxy),
+              errsv);
+        return;
+    }
+
+    device = nm_manager_get_device_by_ifindex(priv->manager, ifindex);
+    if (!NM_IS_DEVICE_IWD(device)) {
+        _LOGE("IWD device named %s is not a Wifi device", ifname);
+        return;
+    }
+
+    nm_device_iwd_set_dbus_object(NM_DEVICE_IWD(device), object);
+}
+
+static void
+known_network_update_cb(GObject *source, GAsyncResult *res, gpointer user_data)
+{
+    gs_unref_variant GVariant *variant = NULL;
+    gs_free_error GError *error        = NULL;
+
+    variant = g_dbus_proxy_call_finish(G_DBUS_PROXY(source), res, &error);
+    if (!variant) {
+        nm_log_warn(LOGD_WIFI,
+                    "Updating %s on IWD known network %s failed: %s",
+                    (const char *) user_data,
+                    g_dbus_proxy_get_object_path(G_DBUS_PROXY(source)),
+                    error->message);
+    }
+}
+
+static void
+sett_conn_changed(NMSettingsConnection *sett_conn, guint update_reason, KnownNetworkData *data)
+{
+    NMSettingsConnectionIntFlags flags;
+    NMConnection *               conn   = nm_settings_connection_get_connection(sett_conn);
+    NMSettingConnection *        s_conn = nm_connection_get_setting_connection(conn);
+    gboolean                     nm_autoconnectable = nm_setting_connection_get_autoconnect(s_conn);
+    gboolean iwd_autoconnectable = get_property_bool(data->known_network, "AutoConnect", TRUE);
+
+    nm_assert(sett_conn == data->mirror_connection);
+
+    if (iwd_autoconnectable == nm_autoconnectable)
+        return;
+
+    /* If this is a generated connection it may be ourselves updating it */
+    flags = nm_settings_connection_get_flags(data->mirror_connection);
+    if (NM_FLAGS_HAS(flags, NM_SETTINGS_CONNECTION_INT_FLAGS_NM_GENERATED))
+        return;
+
+    nm_log_dbg(LOGD_WIFI,
+               "Updating AutoConnect on known network at %s based on connection %s",
+               g_dbus_proxy_get_object_path(data->known_network),
+               nm_settings_connection_get_id(data->mirror_connection));
+    g_dbus_proxy_call(data->known_network,
+                      DBUS_INTERFACE_PROPERTIES ".Set",
+                      g_variant_new("(ssv)",
+                                    NM_IWD_KNOWN_NETWORK_INTERFACE,
+                                    "AutoConnect",
+                                    g_variant_new_boolean(nm_autoconnectable)),
+                      G_DBUS_CALL_FLAGS_NONE,
+                      -1,
+                      NULL,
+                      known_network_update_cb,
+                      "AutoConnect");
+}
+
+/* Look up an existing NMSettingsConnection for a network that has been
+ * preprovisioned with an IWD config file or has been connected to before,
+ * or create a new in-memory NMSettingsConnection object.  This will let
+ * users control the few supported properties (mainly make it
+ * IWD-autoconnectable or not), remove/forget the network, or, for a
+ * WPA2-Enterprise type network it will inform the NM autoconnect mechanism
+ * and the clients that this networks needs no additional EAP configuration
+ * from the user.
+ */
+static NMSettingsConnection *
+mirror_connection(NMIwdManager *        self,
+                  const KnownNetworkId *id,
+                  gboolean              create_new,
+                  GDBusProxy *          known_network)
+{
+    NMIwdManagerPrivate *        priv = NM_IWD_MANAGER_GET_PRIVATE(self);
+    NMSettingsConnection *const *iter;
+    gs_unref_object NMConnection *connection          = NULL;
+    NMSettingsConnection *        settings_connection = NULL;
+    char                          uuid[37];
+    NMSetting *                   setting;
+    gs_free_error GError *error            = NULL;
+    gs_unref_bytes GBytes *new_ssid        = NULL;
+    gsize                  ssid_len        = strlen(id->name);
+    gboolean               autoconnectable = TRUE;
+    gboolean               hidden          = FALSE;
+    gboolean               exact_match     = TRUE;
+    const char *           key_mgmt        = NULL;
+
+    if (known_network) {
+        autoconnectable = get_property_bool(known_network, "AutoConnect", TRUE);
+        hidden          = get_property_bool(known_network, "Hidden", FALSE);
+    }
+
+    for (iter = nm_settings_get_connections(priv->settings, NULL); *iter; iter++) {
+        NMSettingsConnection *sett_conn = *iter;
+        NMConnection *        conn      = nm_settings_connection_get_connection(sett_conn);
+        NMIwdNetworkSecurity  security;
+        NMSettingWireless *   s_wifi;
+        const guint8 *        ssid_bytes;
+        gsize                 ssid_len2;
+
+        if (!nm_wifi_connection_get_iwd_ssid_and_security(conn, NULL, &security))
+            continue;
+
+        if (security != id->security)
+            continue;
+
+        s_wifi = nm_connection_get_setting_wireless(conn);
+        if (!s_wifi)
+            continue;
+
+        /* The SSID must be UTF-8 if it matches since id->name is known to be
+         * valid UTF-8, so just memcmp them.
+         */
+        ssid_bytes = g_bytes_get_data(nm_setting_wireless_get_ssid(s_wifi), &ssid_len2);
+        if (!ssid_bytes || ssid_len2 != ssid_len || memcmp(ssid_bytes, id->name, ssid_len))
+            continue;
+
+        exact_match = TRUE;
+
+        if (known_network) {
+            NMSettingConnection *s_conn = nm_connection_get_setting_connection(conn);
+
+            if (nm_setting_connection_get_autoconnect(s_conn) != autoconnectable
+                || nm_setting_wireless_get_hidden(s_wifi) != hidden)
+                exact_match = FALSE;
+        }
+
+        switch (id->security) {
+        case NM_IWD_NETWORK_SECURITY_WEP:
+        case NM_IWD_NETWORK_SECURITY_OPEN:
+        case NM_IWD_NETWORK_SECURITY_PSK:
+            break;
+        case NM_IWD_NETWORK_SECURITY_8021X:
+        {
+            NMSetting8021x *s_8021x  = nm_connection_get_setting_802_1x(conn);
+            gboolean        external = FALSE;
+            guint           i;
+
+            for (i = 0; i < nm_setting_802_1x_get_num_eap_methods(s_8021x); i++) {
+                if (nm_streq(nm_setting_802_1x_get_eap_method(s_8021x, i), "external")) {
+                    external = TRUE;
+                    break;
+                }
+            }
+
+            /* Prefer returning connections with EAP method "external" */
+            if (!external)
+                exact_match = FALSE;
+        }
+        }
+
+        if (!settings_connection || exact_match)
+            settings_connection = sett_conn;
+
+        if (exact_match)
+            break;
+    }
+
+    if (settings_connection && known_network && !exact_match) {
+        NMSettingsConnectionIntFlags flags = nm_settings_connection_get_flags(settings_connection);
+
+        /* If we found a connection and it's generated (likely by ourselves)
+         * it may have been created on a request by
+         * nm_iwd_manager_get_ap_mirror_connection() when no Known Network
+         * was available so we didn't have access to its properties other
+         * than Name and Security.  Copy their values to the generated
+         * NMConnection.
+         * TODO: avoid notify signals triggering our own watch.
+         *
+         * If on the other hand this is a user-created NMConnection we
+         * should try to copy the properties from it to IWD's Known Network
+         * using the Properties DBus interface in case the user created an
+         * NM connection before IWD appeared on the bus, or before IWD
+         * created its Known Network object.
+         */
+        if (NM_FLAGS_HAS(flags, NM_SETTINGS_CONNECTION_INT_FLAGS_NM_GENERATED)) {
+            NMConnection *tmp_conn = nm_settings_connection_get_connection(settings_connection);
+            NMSettingConnection *s_conn = nm_connection_get_setting_connection(tmp_conn);
+            NMSettingWireless *  s_wifi = nm_connection_get_setting_wireless(tmp_conn);
+
+            g_object_set(G_OBJECT(s_conn),
+                         NM_SETTING_CONNECTION_AUTOCONNECT,
+                         autoconnectable,
+                         NULL);
+            g_object_set(G_OBJECT(s_wifi), NM_SETTING_WIRELESS_HIDDEN, hidden, NULL);
+        } else {
+            KnownNetworkData data = {known_network, settings_connection};
+            sett_conn_changed(settings_connection, 0, &data);
+        }
+    }
+
+    if (settings_connection && known_network) {
+        /* Reset NM_SETTINGS_CONNECTION_INT_FLAGS_EXTERNAL now that the
+         * connection is going to be referenced by a known network, we don't
+         * want it to be deleted when activation fails anymore.
+         */
+        nm_settings_connection_set_flags_full(settings_connection,
+                                              NM_SETTINGS_CONNECTION_INT_FLAGS_EXTERNAL,
+                                              0);
+    }
+
+    /* If we already have an NMSettingsConnection matching this
+     * KnownNetwork, whether it's saved or an in-memory connection
+     * potentially created by ourselves then we have nothing left to
+     * do here.
+     */
+    if (settings_connection || !create_new)
+        return settings_connection;
+
+    connection = nm_simple_connection_new();
+
+    setting = g_object_new(NM_TYPE_SETTING_CONNECTION,
+                           NM_SETTING_CONNECTION_TYPE,
+                           NM_SETTING_WIRELESS_SETTING_NAME,
+                           NM_SETTING_CONNECTION_ID,
+                           id->name,
+                           NM_SETTING_CONNECTION_UUID,
+                           nm_utils_uuid_generate_buf(uuid),
+                           NM_SETTING_CONNECTION_AUTOCONNECT,
+                           autoconnectable,
+                           NULL);
+    nm_connection_add_setting(connection, setting);
+
+    new_ssid = g_bytes_new(id->name, ssid_len);
+    setting  = g_object_new(NM_TYPE_SETTING_WIRELESS,
+                           NM_SETTING_WIRELESS_SSID,
+                           new_ssid,
+                           NM_SETTING_WIRELESS_MODE,
+                           NM_SETTING_WIRELESS_MODE_INFRA,
+                           NM_SETTING_WIRELESS_HIDDEN,
+                           hidden,
+                           NULL);
+    nm_connection_add_setting(connection, setting);
+
+    switch (id->security) {
+    case NM_IWD_NETWORK_SECURITY_WEP:
+        key_mgmt = "none";
+        break;
+    case NM_IWD_NETWORK_SECURITY_OPEN:
+        key_mgmt = NULL;
+        break;
+    case NM_IWD_NETWORK_SECURITY_PSK:
+        key_mgmt = "wpa-psk";
+        break;
+    case NM_IWD_NETWORK_SECURITY_8021X:
+        key_mgmt = "wpa-eap";
+        break;
+    }
+
+    if (key_mgmt) {
+        setting = g_object_new(NM_TYPE_SETTING_WIRELESS_SECURITY,
+                               NM_SETTING_WIRELESS_SECURITY_AUTH_ALG,
+                               "open",
+                               NM_SETTING_WIRELESS_SECURITY_KEY_MGMT,
+                               key_mgmt,
+                               NULL);
+        nm_connection_add_setting(connection, setting);
+    }
+
+    if (id->security == NM_IWD_NETWORK_SECURITY_8021X) {
+        /* "password" and "private-key-password" may be requested by the IWD agent
+         * from NM and IWD will implement a specific secret cache policy so by
+         * default respect that policy and don't save copies of those secrets in
+         * NM settings.  The saved values can not be used anyway because of our
+         * use of NM_SECRET_AGENT_GET_SECRETS_FLAG_REQUEST_NEW.
+         */
+        setting = g_object_new(NM_TYPE_SETTING_802_1X,
+                               NM_SETTING_802_1X_PASSWORD_FLAGS,
+                               NM_SETTING_SECRET_FLAG_NOT_SAVED,
+                               NM_SETTING_802_1X_PRIVATE_KEY_PASSWORD_FLAGS,
+                               NM_SETTING_SECRET_FLAG_NOT_SAVED,
+                               NULL);
+        nm_setting_802_1x_add_eap_method(NM_SETTING_802_1X(setting), "external");
+        nm_connection_add_setting(connection, setting);
+    }
+
+    if (!nm_connection_normalize(connection, NULL, NULL, NULL))
+        return NULL;
+
+    if (!nm_settings_add_connection(
+            priv->settings,
+            connection,
+            NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY_ONLY,
+            NM_SETTINGS_CONNECTION_ADD_REASON_NONE,
+            NM_SETTINGS_CONNECTION_INT_FLAGS_NM_GENERATED
+                | (known_network ? 0 : NM_SETTINGS_CONNECTION_INT_FLAGS_EXTERNAL),
+            &settings_connection,
+            &error)) {
+        _LOGW("failed to add a mirror NMConnection for IWD's Known Network '%s': %s",
+              id->name,
+              error->message);
+        return NULL;
+    }
+
+    return settings_connection;
+}
+
+static void
+mirror_connection_take_and_delete(NMSettingsConnection *sett_conn, KnownNetworkData *data)
+{
+    NMSettingsConnectionIntFlags flags;
+
+    if (!sett_conn)
+        return;
+
+    flags = nm_settings_connection_get_flags(sett_conn);
+
+    /* If connection has not been saved since we created it
+     * in interface_added it too can be removed now. */
+    if (NM_FLAGS_HAS(flags, NM_SETTINGS_CONNECTION_INT_FLAGS_NM_GENERATED))
+        nm_settings_connection_delete(sett_conn, FALSE);
+
+    g_signal_handlers_disconnect_by_data(sett_conn, data);
+    g_object_unref(sett_conn);
+}
+
+static void
+interface_added(GDBusObjectManager *object_manager,
+                GDBusObject *       object,
+                GDBusInterface *    interface,
+                gpointer            user_data)
+{
+    NMIwdManager *       self = user_data;
+    NMIwdManagerPrivate *priv = NM_IWD_MANAGER_GET_PRIVATE(self);
+    GDBusProxy *         proxy;
+    const char *         iface_name;
+
+    if (!priv->running)
+        return;
+
+    g_return_if_fail(G_IS_DBUS_PROXY(interface));
+
+    proxy      = G_DBUS_PROXY(interface);
+    iface_name = g_dbus_proxy_get_interface_name(proxy);
+
+    if (nm_streq(iface_name, NM_IWD_DEVICE_INTERFACE)) {
+        set_device_dbus_object(self, proxy, object);
+        return;
+    }
+
+    if (nm_streq(iface_name, NM_IWD_KNOWN_NETWORK_INTERFACE)) {
+        KnownNetworkId *      id;
+        KnownNetworkId *      orig_id;
+        KnownNetworkData *    data;
+        NMIwdNetworkSecurity  security;
+        const char *          type_str, *name;
+        NMSettingsConnection *sett_conn = NULL;
+
+        type_str = get_property_string_or_null(proxy, "Type");
+        name     = get_property_string_or_null(proxy, "Name");
+        if (!type_str || !name)
+            return;
+
+        if (nm_streq(type_str, "open"))
+            security = NM_IWD_NETWORK_SECURITY_OPEN;
+        else if (nm_streq(type_str, "psk"))
+            security = NM_IWD_NETWORK_SECURITY_PSK;
+        else if (nm_streq(type_str, "8021x"))
+            security = NM_IWD_NETWORK_SECURITY_8021X;
+        else
+            return;
+
+        id = known_network_id_new(name, security);
+
+        if (g_hash_table_lookup_extended(priv->known_networks,
+                                         id,
+                                         (void **) &orig_id,
+                                         (void **) &data)) {
+            _LOGW("DBus error: KnownNetwork already exists ('%s', %s)", name, type_str);
+            nm_g_object_ref_set(&data->known_network, proxy);
+            g_free(id);
+            id = orig_id;
+        } else {
+            data                = g_slice_new0(KnownNetworkData);
+            data->known_network = g_object_ref(proxy);
+            g_hash_table_insert(priv->known_networks, id, data);
+        }
+
+        sett_conn = mirror_connection(self, id, TRUE, proxy);
+
+        if (sett_conn && sett_conn != data->mirror_connection) {
+            NMSettingsConnection *sett_conn_old = data->mirror_connection;
+
+            data->mirror_connection = nm_g_object_ref(sett_conn);
+            mirror_connection_take_and_delete(sett_conn_old, data);
+
+            g_signal_connect(sett_conn,
+                             NM_SETTINGS_CONNECTION_UPDATED_INTERNAL,
+                             G_CALLBACK(sett_conn_changed),
+                             data);
+        }
+
+        return;
+    }
+
+    if (nm_streq(iface_name, NM_IWD_NETWORK_INTERFACE)) {
+        NMDeviceIwd *device = get_device_from_network(self, proxy);
+
+        if (device)
+            nm_device_iwd_network_add_remove(device, proxy, TRUE);
+
+        return;
+    }
+}
+
+static void
+interface_removed(GDBusObjectManager *object_manager,
+                  GDBusObject *       object,
+                  GDBusInterface *    interface,
+                  gpointer            user_data)
+{
+    NMIwdManager *       self = user_data;
+    NMIwdManagerPrivate *priv = NM_IWD_MANAGER_GET_PRIVATE(self);
+    GDBusProxy *         proxy;
+    const char *         iface_name;
+
+    g_return_if_fail(G_IS_DBUS_PROXY(interface));
+
+    proxy      = G_DBUS_PROXY(interface);
+    iface_name = g_dbus_proxy_get_interface_name(proxy);
+
+    if (nm_streq(iface_name, NM_IWD_DEVICE_INTERFACE)) {
+        set_device_dbus_object(self, proxy, NULL);
+        return;
+    }
+
+    if (nm_streq(iface_name, NM_IWD_KNOWN_NETWORK_INTERFACE)) {
+        KnownNetworkId id;
+        const char *   type_str;
+
+        type_str = get_property_string_or_null(proxy, "Type");
+        id.name  = get_property_string_or_null(proxy, "Name");
+        if (!type_str || !id.name)
+            return;
+
+        if (nm_streq(type_str, "open"))
+            id.security = NM_IWD_NETWORK_SECURITY_OPEN;
+        else if (nm_streq(type_str, "psk"))
+            id.security = NM_IWD_NETWORK_SECURITY_PSK;
+        else if (nm_streq(type_str, "8021x"))
+            id.security = NM_IWD_NETWORK_SECURITY_8021X;
+        else
+            return;
+
+        g_hash_table_remove(priv->known_networks, &id);
+        return;
+    }
+
+    if (nm_streq(iface_name, NM_IWD_NETWORK_INTERFACE)) {
+        NMDeviceIwd *device = get_device_from_network(self, proxy);
+
+        if (device)
+            nm_device_iwd_network_add_remove(device, proxy, FALSE);
+
+        return;
+    }
+}
+
+static void
+object_added(GDBusObjectManager *object_manager, GDBusObject *object, gpointer user_data)
+{
+    GList *interfaces, *iter;
+
+    interfaces = g_dbus_object_get_interfaces(object);
+
+    for (iter = interfaces; iter; iter = iter->next) {
+        GDBusInterface *interface = G_DBUS_INTERFACE(iter->data);
+
+        interface_added(NULL, object, interface, user_data);
+    }
+
+    g_list_free_full(interfaces, g_object_unref);
+}
+
+static void
+object_removed(GDBusObjectManager *object_manager, GDBusObject *object, gpointer user_data)
+{
+    GList *interfaces, *iter;
+
+    interfaces = g_dbus_object_get_interfaces(object);
+
+    for (iter = interfaces; iter; iter = iter->next) {
+        GDBusInterface *interface = G_DBUS_INTERFACE(iter->data);
+
+        interface_removed(NULL, object, interface, user_data);
+    }
+
+    g_list_free_full(interfaces, g_object_unref);
+}
+
+static void
+connection_removed(NMSettings *settings, NMSettingsConnection *sett_conn, gpointer user_data)
+{
+    NMIwdManager *        self = user_data;
+    NMIwdManagerPrivate * priv = NM_IWD_MANAGER_GET_PRIVATE(self);
+    NMConnection *        conn = nm_settings_connection_get_connection(sett_conn);
+    NMSettingWireless *   s_wireless;
+    KnownNetworkData *    data;
+    KnownNetworkId        id;
+    char                  ssid_buf[33];
+    const guint8 *        ssid_bytes;
+    gsize                 ssid_len;
+    NMSettingsConnection *new_mirror_conn;
+
+    if (!nm_wifi_connection_get_iwd_ssid_and_security(conn, NULL, &id.security))
+        return;
+
+    s_wireless = nm_connection_get_setting_wireless(conn);
+    if (!s_wireless)
+        return;
+
+    ssid_bytes = g_bytes_get_data(nm_setting_wireless_get_ssid(s_wireless), &ssid_len);
+    if (!ssid_bytes || ssid_len > 32 || memchr(ssid_bytes, 0, ssid_len))
+        return;
+
+    memcpy(ssid_buf, ssid_bytes, ssid_len);
+    ssid_buf[ssid_len] = '\0';
+    id.name            = ssid_buf;
+    data               = g_hash_table_lookup(priv->known_networks, &id);
+    if (!data)
+        return;
+
+    if (data->mirror_connection != sett_conn)
+        return;
+
+    g_clear_object(&data->mirror_connection);
+
+    /* Don't call Forget on the Known Network until there's no longer *any*
+     * matching NMSettingsConnection (debatable)
+     */
+    new_mirror_conn = mirror_connection(self, &id, FALSE, NULL);
+    if (new_mirror_conn) {
+        data->mirror_connection = g_object_ref(new_mirror_conn);
+        return;
+    }
+
+    if (!priv->running)
+        return;
+
+    g_dbus_proxy_call(data->known_network,
+                      "Forget",
+                      NULL,
+                      G_DBUS_CALL_FLAGS_NONE,
+                      -1,
+                      NULL,
+                      NULL,
+                      NULL);
+}
+
+static gboolean
+_om_has_name_owner(GDBusObjectManager *object_manager)
+{
+    gs_free char *name_owner = NULL;
+
+    nm_assert(G_IS_DBUS_OBJECT_MANAGER_CLIENT(object_manager));
+
+    name_owner =
+        g_dbus_object_manager_client_get_name_owner(G_DBUS_OBJECT_MANAGER_CLIENT(object_manager));
+    return !!name_owner;
+}
+
+static void
+release_object_manager(NMIwdManager *self)
+{
+    NMIwdManagerPrivate *priv = NM_IWD_MANAGER_GET_PRIVATE(self);
+
+    if (!priv->object_manager)
+        return;
+
+    g_signal_handlers_disconnect_by_data(priv->object_manager, self);
+
+    if (priv->agent_id) {
+        GDBusConnection *         agent_connection;
+        GDBusObjectManagerClient *omc = G_DBUS_OBJECT_MANAGER_CLIENT(priv->object_manager);
+
+        agent_connection = g_dbus_object_manager_client_get_connection(omc);
+
+        /* We're is called when we're shutting down (i.e. our DBus connection
+         * is being closed, and IWD will detect this) or IWD was stopped so
+         * in either case calling UnregisterAgent will not do anything.
+         */
+        g_dbus_connection_unregister_object(agent_connection, priv->agent_id);
+        priv->agent_id = 0;
+        nm_clear_g_free(&priv->agent_path);
+    }
+
+    g_clear_object(&priv->object_manager);
+}
+
+static void prepare_object_manager(NMIwdManager *self);
+
+static void
+name_owner_changed(GObject *object, GParamSpec *pspec, gpointer user_data)
+{
+    NMIwdManager *       self           = user_data;
+    NMIwdManagerPrivate *priv           = NM_IWD_MANAGER_GET_PRIVATE(self);
+    GDBusObjectManager * object_manager = G_DBUS_OBJECT_MANAGER(object);
+
+    nm_assert(object_manager == priv->object_manager);
+
+    if (_om_has_name_owner(object_manager)) {
+        release_object_manager(self);
+        prepare_object_manager(self);
+    } else {
+        const CList *tmp_lst;
+        NMDevice *   device;
+
+        if (!priv->running)
+            return;
+
+        priv->running = false;
+
+        nm_manager_for_each_device (priv->manager, device, tmp_lst) {
+            if (NM_IS_DEVICE_IWD(device)) {
+                nm_device_iwd_set_dbus_object(NM_DEVICE_IWD(device), NULL);
+            }
+        }
+    }
+}
+
+static void
+device_added(NMManager *manager, NMDevice *device, gpointer user_data)
+{
+    NMIwdManager *       self = user_data;
+    NMIwdManagerPrivate *priv = NM_IWD_MANAGER_GET_PRIVATE(self);
+    GList *              objects, *iter;
+
+    if (!NM_IS_DEVICE_IWD(device))
+        return;
+
+    if (!priv->running)
+        return;
+
+    /* Here we handle a potential scenario where IWD's DBus objects for the
+     * new device popped up before the NMDevice.  The
+     * interface_added/object_added signals have been received already and
+     * the handlers couldn't do much because the NMDevice wasn't there yet
+     * so now we go over the Network and Device interfaces again.  In this
+     * exact order for "object path" property consistency -- see reasoning
+     * in object_compare_interfaces.
+     */
+    objects = g_dbus_object_manager_get_objects(priv->object_manager);
+
+    for (iter = objects; iter; iter = iter->next) {
+        GDBusObject *   object                    = G_DBUS_OBJECT(iter->data);
+        gs_unref_object GDBusInterface *interface = NULL;
+
+        interface = g_dbus_object_get_interface(object, NM_IWD_NETWORK_INTERFACE);
+        if (!interface)
+            continue;
+
+        if (NM_DEVICE_IWD(device) == get_device_from_network(self, (GDBusProxy *) interface))
+            nm_device_iwd_network_add_remove(NM_DEVICE_IWD(device), (GDBusProxy *) interface, TRUE);
+    }
+
+    for (iter = objects; iter; iter = iter->next) {
+        GDBusObject *   object                    = G_DBUS_OBJECT(iter->data);
+        gs_unref_object GDBusInterface *interface = NULL;
+        const char *                    obj_ifname;
+
+        interface  = g_dbus_object_get_interface(object, NM_IWD_DEVICE_INTERFACE);
+        obj_ifname = get_property_string_or_null((GDBusProxy *) interface, "Name");
+
+        if (!obj_ifname || strcmp(nm_device_get_iface(device), obj_ifname))
+            continue;
+
+        nm_device_iwd_set_dbus_object(NM_DEVICE_IWD(device), object);
+        break;
+    }
+
+    g_list_free_full(objects, g_object_unref);
+}
+
+static void
+device_removed(NMManager *manager, NMDevice *device, gpointer user_data)
+{
+    NMIwdManager *       self = user_data;
+    NMIwdManagerPrivate *priv = NM_IWD_MANAGER_GET_PRIVATE(self);
+
+    if (!NM_IS_DEVICE_IWD(device))
+        return;
+
+    if (priv->last_agent_call_device == NM_DEVICE_IWD(device))
+        priv->last_agent_call_device = NULL;
+}
+
+/* This is used to sort the list of objects returned by GetManagedObjects()
+ * based on the DBus interfaces available on these objects in such a way that
+ * the interface_added calls happen in the right order.  The order is defined
+ * by how some DBus interfaces point to interfaces on other objects using
+ * DBus properties of the type "object path" ("o" signature).  This creates
+ * "dependencies" between objects.
+ *
+ * When NM and IWD are running, the InterfacesAdded signals should come in
+ * an order that ensures consistency of those object paths.  For example
+ * when a Network interface is added with a KnownNetwork property, or that
+ * property is assigned a new value, the KnownNetwork object pointed to by
+ * it will have been added in an earlier InterfacesAdded signal.  Similarly
+ * Station.ConnectedNetwork and Station.GetOrdereNetworks() only point to
+ * existing Network objects.  (There may be circular dependencies but during
+ * initialization we only need a subset of those properties that doesn't
+ * have this problem.)
+ *
+ * But GetManagedObjects doesn't guarantee this kind of consistency so we
+ * order the returned object list ourselves to simplify the job of
+ * interface_added().  Objects that don't have any interfaces listed in
+ * interface_order are moved to the end of the list.
+ */
+static int
+object_compare_interfaces(gconstpointer a, gconstpointer b)
+{
+    static const char *interface_order[] = {
+        NM_IWD_KNOWN_NETWORK_INTERFACE,
+        NM_IWD_NETWORK_INTERFACE,
+        NM_IWD_DEVICE_INTERFACE,
+    };
+    int   rank_a = G_N_ELEMENTS(interface_order);
+    int   rank_b = G_N_ELEMENTS(interface_order);
+    guint pos;
+
+    for (pos = 0; interface_order[pos]; pos++) {
+        GDBusInterface *iface_a;
+        GDBusInterface *iface_b;
+
+        if (rank_a == G_N_ELEMENTS(interface_order)
+            && (iface_a = g_dbus_object_get_interface(G_DBUS_OBJECT(a), interface_order[pos]))) {
+            rank_a = pos;
+            g_object_unref(iface_a);
+        }
+
+        if (rank_b == G_N_ELEMENTS(interface_order)
+            && (iface_b = g_dbus_object_get_interface(G_DBUS_OBJECT(b), interface_order[pos]))) {
+            rank_b = pos;
+            g_object_unref(iface_b);
+        }
+    }
+
+    return rank_a - rank_b;
+}
+
+static void
+got_object_manager(GObject *object, GAsyncResult *result, gpointer user_data)
+{
+    NMIwdManager *       self  = user_data;
+    NMIwdManagerPrivate *priv  = NM_IWD_MANAGER_GET_PRIVATE(self);
+    GError *             error = NULL;
+    GDBusObjectManager * object_manager;
+    GDBusConnection *    connection;
+
+    object_manager = g_dbus_object_manager_client_new_for_bus_finish(result, &error);
+    if (object_manager == NULL) {
+        _LOGE("failed to acquire IWD Object Manager: Wi-Fi will not be available (%s)",
+              error->message);
+        g_clear_error(&error);
+        return;
+    }
+
+    priv->object_manager = object_manager;
+
+    g_signal_connect(priv->object_manager,
+                     "notify::name-owner",
+                     G_CALLBACK(name_owner_changed),
+                     self);
+
+    nm_assert(G_IS_DBUS_OBJECT_MANAGER_CLIENT(object_manager));
+
+    connection =
+        g_dbus_object_manager_client_get_connection(G_DBUS_OBJECT_MANAGER_CLIENT(object_manager));
+
+    priv->agent_id = iwd_agent_export(connection, self, &priv->agent_path, &error);
+    if (!priv->agent_id) {
+        _LOGE("failed to export the IWD Agent: PSK/8021x Wi-Fi networks may not work: %s",
+              error->message);
+        g_clear_error(&error);
+    }
+
+    if (_om_has_name_owner(object_manager)) {
+        GList *objects, *iter;
+
+        priv->running = true;
+
+        g_signal_connect(priv->object_manager,
+                         "interface-added",
+                         G_CALLBACK(interface_added),
+                         self);
+        g_signal_connect(priv->object_manager,
+                         "interface-removed",
+                         G_CALLBACK(interface_removed),
+                         self);
+        g_signal_connect(priv->object_manager, "object-added", G_CALLBACK(object_added), self);
+        g_signal_connect(priv->object_manager, "object-removed", G_CALLBACK(object_removed), self);
+
+        g_hash_table_remove_all(priv->known_networks);
+
+        objects = g_dbus_object_manager_get_objects(object_manager);
+        objects = g_list_sort(objects, object_compare_interfaces);
+        for (iter = objects; iter; iter = iter->next)
+            object_added(NULL, G_DBUS_OBJECT(iter->data), self);
+
+        g_list_free_full(objects, g_object_unref);
+
+        if (priv->agent_id)
+            register_agent(self);
+    }
+}
+
+static void
+prepare_object_manager(NMIwdManager *self)
+{
+    NMIwdManagerPrivate *priv = NM_IWD_MANAGER_GET_PRIVATE(self);
+
+    g_dbus_object_manager_client_new_for_bus(NM_IWD_BUS_TYPE,
+                                             G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_NONE,
+                                             NM_IWD_SERVICE,
+                                             "/",
+                                             NULL,
+                                             NULL,
+                                             NULL,
+                                             priv->cancellable,
+                                             got_object_manager,
+                                             self);
+}
+
+gboolean
+nm_iwd_manager_is_known_network(NMIwdManager *self, const char *name, NMIwdNetworkSecurity security)
+{
+    NMIwdManagerPrivate *priv  = NM_IWD_MANAGER_GET_PRIVATE(self);
+    KnownNetworkId       kn_id = {name, security};
+
+    return g_hash_table_contains(priv->known_networks, &kn_id);
+}
+
+NMSettingsConnection *
+nm_iwd_manager_get_ap_mirror_connection(NMIwdManager *self, NMWifiAP *ap)
+{
+    NMIwdManagerPrivate *  priv = NM_IWD_MANAGER_GET_PRIVATE(self);
+    KnownNetworkData *     data;
+    char                   name_buf[33];
+    KnownNetworkId         kn_id = {name_buf, NM_IWD_NETWORK_SECURITY_OPEN};
+    const guint8 *         ssid_bytes;
+    gsize                  ssid_len;
+    NM80211ApFlags         flags     = nm_wifi_ap_get_flags(ap);
+    NM80211ApSecurityFlags sec_flags = nm_wifi_ap_get_wpa_flags(ap) | nm_wifi_ap_get_rsn_flags(ap);
+
+    ssid_bytes = g_bytes_get_data(nm_wifi_ap_get_ssid(ap), &ssid_len);
+    ssid_len   = MIN(ssid_len, 32);
+    memcpy(name_buf, ssid_bytes, ssid_len);
+    name_buf[ssid_len] = '\0';
+
+    if (flags & NM_802_11_AP_FLAGS_PRIVACY)
+        kn_id.security = NM_IWD_NETWORK_SECURITY_WEP;
+
+    if (sec_flags & NM_802_11_AP_SEC_KEY_MGMT_PSK)
+        kn_id.security = NM_IWD_NETWORK_SECURITY_PSK;
+    else if (sec_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X)
+        kn_id.security = NM_IWD_NETWORK_SECURITY_8021X;
+
+    /* Right now it's easier for us to do a name+security lookup than to use
+     * the Network.KnownNetwork property to look up by path.
+     */
+    data = g_hash_table_lookup(priv->known_networks, &kn_id);
+    if (data)
+        return data->mirror_connection;
+
+    /* We have no KnownNetwork for this AP, we're probably connecting to it for
+     * the first time.  This is not a usual/supported scenario so we don't need
+     * to bother too much about creating a great mirror connection, we don't
+     * even have any more information than the Name & Type properties on the
+     * Network interface.  This *should* never happen for an 8021x type network.
+     */
+    return mirror_connection(self, &kn_id, TRUE, NULL);
+}
+
+GDBusProxy *
+nm_iwd_manager_get_dbus_interface(NMIwdManager *self, const char *path, const char *name)
+{
+    NMIwdManagerPrivate *priv = NM_IWD_MANAGER_GET_PRIVATE(self);
+    GDBusInterface *     interface;
+
+    if (!priv->object_manager)
+        return NULL;
+
+    interface = g_dbus_object_manager_get_interface(priv->object_manager, path, name);
+
+    return interface ? G_DBUS_PROXY(interface) : NULL;
+}
+
+/*****************************************************************************/
+
+NM_DEFINE_SINGLETON_GETTER(NMIwdManager, nm_iwd_manager_get, NM_TYPE_IWD_MANAGER);
+
+static void
+nm_iwd_manager_init(NMIwdManager *self)
+{
+    NMIwdManagerPrivate *priv = NM_IWD_MANAGER_GET_PRIVATE(self);
+
+    priv->manager = g_object_ref(NM_MANAGER_GET);
+    g_signal_connect(priv->manager, NM_MANAGER_DEVICE_ADDED, G_CALLBACK(device_added), self);
+    g_signal_connect(priv->manager, NM_MANAGER_DEVICE_REMOVED, G_CALLBACK(device_removed), self);
+
+    priv->settings = g_object_ref(NM_SETTINGS_GET);
+    g_signal_connect(priv->settings,
+                     NM_SETTINGS_SIGNAL_CONNECTION_REMOVED,
+                     G_CALLBACK(connection_removed),
+                     self);
+
+    priv->cancellable = g_cancellable_new();
+
+    priv->known_networks = g_hash_table_new_full((GHashFunc) known_network_id_hash,
+                                                 (GEqualFunc) known_network_id_equal,
+                                                 g_free,
+                                                 (GDestroyNotify) known_network_data_free);
+
+    prepare_object_manager(self);
+}
+
+static void
+dispose(GObject *object)
+{
+    NMIwdManager *       self = (NMIwdManager *) object;
+    NMIwdManagerPrivate *priv = NM_IWD_MANAGER_GET_PRIVATE(self);
+
+    release_object_manager(self);
+
+    nm_clear_g_cancellable(&priv->cancellable);
+
+    if (priv->settings) {
+        g_signal_handlers_disconnect_by_data(priv->settings, self);
+        g_clear_object(&priv->settings);
+    }
+
+    /* This may trigger mirror connection removals so it happens
+     * after the g_signal_handlers_disconnect_by_data above.
+     */
+    nm_clear_pointer(&priv->known_networks, g_hash_table_destroy);
+
+    if (priv->manager) {
+        g_signal_handlers_disconnect_by_data(priv->manager, self);
+        g_clear_object(&priv->manager);
+    }
+
+    priv->last_agent_call_device = NULL;
+
+    G_OBJECT_CLASS(nm_iwd_manager_parent_class)->dispose(object);
+}
+
+static void
+nm_iwd_manager_class_init(NMIwdManagerClass *klass)
+{
+    GObjectClass *object_class = G_OBJECT_CLASS(klass);
+
+    object_class->dispose = dispose;
+}
diff --git a/src/core/devices/wifi/nm-iwd-manager.h b/src/core/devices/wifi/nm-iwd-manager.h
new file mode 100644
index 00000000..466f67c7
--- /dev/null
+++ b/src/core/devices/wifi/nm-iwd-manager.h
@@ -0,0 +1,53 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+/*
+ * Copyright (C) 2017 Intel Corporation
+ */
+
+#ifndef __NETWORKMANAGER_IWD_MANAGER_H__
+#define __NETWORKMANAGER_IWD_MANAGER_H__
+
+#include "devices/nm-device.h"
+#include "nm-wifi-utils.h"
+#include "nm-wifi-ap.h"
+
+#define NM_IWD_BUS_TYPE G_BUS_TYPE_SYSTEM
+#define NM_IWD_SERVICE  "net.connman.iwd"
+
+#define NM_IWD_AGENT_MANAGER_INTERFACE "net.connman.iwd.AgentManager"
+#define NM_IWD_WIPHY_INTERFACE         "net.connman.iwd.Adapter"
+#define NM_IWD_DEVICE_INTERFACE        "net.connman.iwd.Device"
+#define NM_IWD_NETWORK_INTERFACE       "net.connman.iwd.Network"
+#define NM_IWD_AGENT_INTERFACE         "net.connman.iwd.Agent"
+#define NM_IWD_WSC_INTERFACE           "net.connman.iwd.WiFiSimpleConfiguration"
+#define NM_IWD_KNOWN_NETWORK_INTERFACE "net.connman.iwd.KnownNetwork"
+#define NM_IWD_SIGNAL_AGENT_INTERFACE  "net.connman.iwd.SignalLevelAgent"
+#define NM_IWD_AP_INTERFACE            "net.connman.iwd.AccessPoint"
+#define NM_IWD_ADHOC_INTERFACE         "net.connman.iwd.AdHoc"
+#define NM_IWD_STATION_INTERFACE       "net.connman.iwd.Station"
+
+#define NM_TYPE_IWD_MANAGER (nm_iwd_manager_get_type())
+#define NM_IWD_MANAGER(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), NM_TYPE_IWD_MANAGER, NMIwdManager))
+#define NM_IWD_MANAGER_CLASS(klass) \
+    (G_TYPE_CHECK_CLASS_CAST((klass), NM_TYPE_IWD_MANAGER, NMIwdManagerClass))
+#define NM_IS_IWD_MANAGER(obj)         (G_TYPE_CHECK_INSTANCE_TYPE((obj), NM_TYPE_IWD_MANAGER))
+#define NM_IS_IWD_MANAGER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), NM_TYPE_IWD_MANAGER))
+#define NM_IWD_MANAGER_GET_CLASS(obj) \
+    (G_TYPE_INSTANCE_GET_CLASS((obj), NM_TYPE_IWD_MANAGER, NMIwdManagerClass))
+
+typedef struct _NMIwdManager      NMIwdManager;
+typedef struct _NMIwdManagerClass NMIwdManagerClass;
+
+GType nm_iwd_manager_get_type(void);
+
+NMIwdManager *nm_iwd_manager_get(void);
+
+gboolean nm_iwd_manager_is_known_network(NMIwdManager *       self,
+                                         const char *         name,
+                                         NMIwdNetworkSecurity security);
+
+NMSettingsConnection *nm_iwd_manager_get_ap_mirror_connection(NMIwdManager *self, NMWifiAP *ap);
+
+GDBusProxy *
+nm_iwd_manager_get_dbus_interface(NMIwdManager *self, const char *path, const char *name);
+
+#endif /* __NETWORKMANAGER_IWD_MANAGER_H__ */
diff --git a/src/core/devices/wifi/nm-wifi-ap.c b/src/core/devices/wifi/nm-wifi-ap.c
new file mode 100644
index 00000000..08fa10ec
--- /dev/null
+++ b/src/core/devices/wifi/nm-wifi-ap.c
@@ -0,0 +1,1051 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+/*
+ * Copyright (C) 2004 - 2017 Red Hat, Inc.
+ * Copyright (C) 2006 - 2008 Novell, Inc.
+ */
+
+#include "src/core/nm-default-daemon.h"
+
+#include "nm-wifi-ap.h"
+
+#include <stdlib.h>
+#include <linux/if_ether.h>
+
+#include "NetworkManagerUtils.h"
+#include "devices/nm-device.h"
+#include "nm-core-internal.h"
+#include "nm-dbus-manager.h"
+#include "nm-glib-aux/nm-ref-string.h"
+#include "nm-setting-wireless.h"
+#include "nm-utils.h"
+#include "nm-wifi-utils.h"
+#include "platform/nm-platform.h"
+#include "supplicant/nm-supplicant-interface.h"
+
+#define PROTO_WPA "wpa"
+#define PROTO_RSN "rsn"
+
+/*****************************************************************************/
+
+NM_GOBJECT_PROPERTIES_DEFINE(NMWifiAP,
+                             PROP_FLAGS,
+                             PROP_WPA_FLAGS,
+                             PROP_RSN_FLAGS,
+                             PROP_SSID,
+                             PROP_FREQUENCY,
+                             PROP_HW_ADDRESS,
+                             PROP_MODE,
+                             PROP_MAX_BITRATE,
+                             PROP_STRENGTH,
+                             PROP_LAST_SEEN, );
+
+struct _NMWifiAPPrivate {
+    /* Scanned or cached values */
+    GBytes *    ssid;
+    char *      address;
+    NM80211Mode mode;
+    guint8      strength;
+    guint32     freq;        /* Frequency in MHz; ie 2412 (== 2.412 GHz) */
+    guint32     max_bitrate; /* Maximum bitrate of the AP in Kbit/s (ie 54000 Kb/s == 54Mbit/s) */
+
+    gint64
+        last_seen_msec; /* Timestamp when the AP was seen lastly (in nm_utils_get_monotonic_timestamp_*() scale).
+                         * Note that this value might be negative! */
+
+    NM80211ApFlags         flags;     /* General flags */
+    NM80211ApSecurityFlags wpa_flags; /* WPA-related flags */
+    NM80211ApSecurityFlags rsn_flags; /* RSN (WPA2) -related flags */
+
+    bool metered : 1;
+
+    /* Non-scanned attributes */
+    bool fake : 1;    /* Whether or not the AP is from a scan */
+    bool hotspot : 1; /* Whether the AP is a local device's hotspot network */
+};
+
+typedef struct _NMWifiAPPrivate NMWifiAPPrivate;
+
+struct _NMWifiAPClass {
+    NMDBusObjectClass parent;
+};
+
+G_DEFINE_TYPE(NMWifiAP, nm_wifi_ap, NM_TYPE_DBUS_OBJECT)
+
+#define NM_WIFI_AP_GET_PRIVATE(self) _NM_GET_PRIVATE_PTR(self, NMWifiAP, NM_IS_WIFI_AP)
+
+/*****************************************************************************/
+
+GBytes *
+nm_wifi_ap_get_ssid(const NMWifiAP *ap)
+{
+    g_return_val_if_fail(NM_IS_WIFI_AP(ap), NULL);
+
+    return NM_WIFI_AP_GET_PRIVATE(ap)->ssid;
+}
+
+gboolean
+nm_wifi_ap_set_ssid(NMWifiAP *ap, GBytes *ssid)
+{
+    NMWifiAPPrivate *priv;
+    gsize            l;
+
+    g_return_val_if_fail(NM_IS_WIFI_AP(ap), FALSE);
+
+    if (!ssid) {
+        /* we don't clear the SSID, once we have it. We can only update
+         * it by a better value. */
+        return FALSE;
+    }
+
+    l = g_bytes_get_size(ssid);
+    if (l == 0 || l > 32)
+        g_return_val_if_reached(FALSE);
+
+    priv = NM_WIFI_AP_GET_PRIVATE(ap);
+
+    if (ssid == priv->ssid)
+        return FALSE;
+    if (priv->ssid && g_bytes_equal(ssid, priv->ssid))
+        return FALSE;
+
+    g_bytes_ref(ssid);
+    nm_clear_pointer(&priv->ssid, g_bytes_unref);
+    priv->ssid = ssid;
+
+    _notify(ap, PROP_SSID);
+    return TRUE;
+}
+
+static gboolean
+nm_wifi_ap_set_flags(NMWifiAP *ap, NM80211ApFlags flags)
+{
+    NMWifiAPPrivate *priv = NM_WIFI_AP_GET_PRIVATE(ap);
+
+    if (priv->flags != flags) {
+        priv->flags = flags;
+        _notify(ap, PROP_FLAGS);
+        return TRUE;
+    }
+    return FALSE;
+}
+
+static gboolean
+nm_wifi_ap_set_wpa_flags(NMWifiAP *ap, NM80211ApSecurityFlags flags)
+{
+    NMWifiAPPrivate *priv = NM_WIFI_AP_GET_PRIVATE(ap);
+
+    if (priv->wpa_flags != flags) {
+        priv->wpa_flags = flags;
+        _notify(ap, PROP_WPA_FLAGS);
+        return TRUE;
+    }
+    return FALSE;
+}
+
+static gboolean
+nm_wifi_ap_set_rsn_flags(NMWifiAP *ap, NM80211ApSecurityFlags flags)
+{
+    NMWifiAPPrivate *priv = NM_WIFI_AP_GET_PRIVATE(ap);
+
+    if (priv->rsn_flags != flags) {
+        priv->rsn_flags = flags;
+        _notify(ap, PROP_RSN_FLAGS);
+        return TRUE;
+    }
+    return FALSE;
+}
+
+const char *
+nm_wifi_ap_get_address(const NMWifiAP *ap)
+{
+    g_return_val_if_fail(NM_IS_WIFI_AP(ap), NULL);
+
+    return NM_WIFI_AP_GET_PRIVATE(ap)->address;
+}
+
+gboolean
+nm_wifi_ap_set_address_bin(NMWifiAP *ap, const NMEtherAddr *addr)
+{
+    NMWifiAPPrivate *priv = NM_WIFI_AP_GET_PRIVATE(ap);
+
+    nm_assert(addr);
+
+    if (!priv->address || !nm_utils_hwaddr_matches(addr, ETH_ALEN, priv->address, -1)) {
+        g_free(priv->address);
+        priv->address = nm_utils_hwaddr_ntoa(addr, ETH_ALEN);
+        _notify(ap, PROP_HW_ADDRESS);
+        return TRUE;
+    }
+    return FALSE;
+}
+
+gboolean
+nm_wifi_ap_set_address(NMWifiAP *ap, const char *addr)
+{
+    NMEtherAddr addr_buf;
+
+    g_return_val_if_fail(NM_IS_WIFI_AP(ap), FALSE);
+    if (!addr || !nm_utils_hwaddr_aton(addr, &addr_buf, sizeof(addr_buf)))
+        g_return_val_if_reached(FALSE);
+
+    return nm_wifi_ap_set_address_bin(ap, &addr_buf);
+}
+
+NM80211Mode
+nm_wifi_ap_get_mode(NMWifiAP *ap)
+{
+    g_return_val_if_fail(NM_IS_WIFI_AP(ap), NM_802_11_MODE_UNKNOWN);
+
+    return NM_WIFI_AP_GET_PRIVATE(ap)->mode;
+}
+
+static gboolean
+nm_wifi_ap_set_mode(NMWifiAP *ap, NM80211Mode mode)
+{
+    NMWifiAPPrivate *priv = NM_WIFI_AP_GET_PRIVATE(ap);
+
+    nm_assert(NM_IN_SET(mode,
+                        NM_802_11_MODE_UNKNOWN,
+                        NM_802_11_MODE_ADHOC,
+                        NM_802_11_MODE_INFRA,
+                        NM_802_11_MODE_MESH));
+
+    if (priv->mode != mode) {
+        priv->mode = mode;
+        _notify(ap, PROP_MODE);
+        return TRUE;
+    }
+    return FALSE;
+}
+
+gboolean
+nm_wifi_ap_is_hotspot(NMWifiAP *ap)
+{
+    g_return_val_if_fail(NM_IS_WIFI_AP(ap), FALSE);
+
+    return NM_WIFI_AP_GET_PRIVATE(ap)->hotspot;
+}
+
+gint8
+nm_wifi_ap_get_strength(NMWifiAP *ap)
+{
+    g_return_val_if_fail(NM_IS_WIFI_AP(ap), 0);
+
+    return NM_WIFI_AP_GET_PRIVATE(ap)->strength;
+}
+
+gboolean
+nm_wifi_ap_set_strength(NMWifiAP *ap, gint8 strength)
+{
+    NMWifiAPPrivate *priv = NM_WIFI_AP_GET_PRIVATE(ap);
+
+    if (priv->strength != strength) {
+        priv->strength = strength;
+        _notify(ap, PROP_STRENGTH);
+        return TRUE;
+    }
+    return FALSE;
+}
+
+guint32
+nm_wifi_ap_get_freq(NMWifiAP *ap)
+{
+    g_return_val_if_fail(NM_IS_WIFI_AP(ap), 0);
+
+    return NM_WIFI_AP_GET_PRIVATE(ap)->freq;
+}
+
+gboolean
+nm_wifi_ap_set_freq(NMWifiAP *ap, guint32 freq)
+{
+    NMWifiAPPrivate *priv = NM_WIFI_AP_GET_PRIVATE(ap);
+
+    if (priv->freq != freq) {
+        priv->freq = freq;
+        _notify(ap, PROP_FREQUENCY);
+        return TRUE;
+    }
+    return FALSE;
+}
+
+guint32
+nm_wifi_ap_get_max_bitrate(NMWifiAP *ap)
+{
+    g_return_val_if_fail(NM_IS_WIFI_AP(ap), 0);
+    g_return_val_if_fail(nm_dbus_object_is_exported(NM_DBUS_OBJECT(ap)), 0);
+
+    return NM_WIFI_AP_GET_PRIVATE(ap)->max_bitrate;
+}
+
+gboolean
+nm_wifi_ap_set_max_bitrate(NMWifiAP *ap, guint32 bitrate)
+{
+    NMWifiAPPrivate *priv;
+
+    g_return_val_if_fail(NM_IS_WIFI_AP(ap), FALSE);
+
+    priv = NM_WIFI_AP_GET_PRIVATE(ap);
+
+    if (priv->max_bitrate != bitrate) {
+        priv->max_bitrate = bitrate;
+        _notify(ap, PROP_MAX_BITRATE);
+        return TRUE;
+    }
+    return FALSE;
+}
+
+gboolean
+nm_wifi_ap_get_fake(const NMWifiAP *ap)
+{
+    g_return_val_if_fail(NM_IS_WIFI_AP(ap), FALSE);
+
+    return NM_WIFI_AP_GET_PRIVATE(ap)->fake;
+}
+
+gboolean
+nm_wifi_ap_set_fake(NMWifiAP *ap, gboolean fake)
+{
+    NMWifiAPPrivate *priv;
+
+    g_return_val_if_fail(NM_IS_WIFI_AP(ap), FALSE);
+
+    priv = NM_WIFI_AP_GET_PRIVATE(ap);
+
+    if (priv->fake != !!fake) {
+        priv->fake = fake;
+        return TRUE;
+    }
+    return FALSE;
+}
+
+NM80211ApFlags
+nm_wifi_ap_get_flags(const NMWifiAP *ap)
+{
+    g_return_val_if_fail(NM_IS_WIFI_AP(ap), NM_802_11_AP_FLAGS_NONE);
+
+    return NM_WIFI_AP_GET_PRIVATE(ap)->flags;
+}
+
+static gboolean
+nm_wifi_ap_set_last_seen(NMWifiAP *ap, gint32 last_seen_msec)
+{
+    NMWifiAPPrivate *priv = NM_WIFI_AP_GET_PRIVATE(ap);
+
+    if (priv->last_seen_msec != last_seen_msec) {
+        priv->last_seen_msec = last_seen_msec;
+        _notify(ap, PROP_LAST_SEEN);
+        return TRUE;
+    }
+    return FALSE;
+}
+
+gboolean
+nm_wifi_ap_get_metered(const NMWifiAP *self)
+{
+    return NM_WIFI_AP_GET_PRIVATE(self)->metered;
+}
+
+NM80211ApSecurityFlags
+nm_wifi_ap_get_wpa_flags(const NMWifiAP *self)
+{
+    return NM_WIFI_AP_GET_PRIVATE(self)->wpa_flags;
+}
+
+NM80211ApSecurityFlags
+nm_wifi_ap_get_rsn_flags(const NMWifiAP *self)
+{
+    return NM_WIFI_AP_GET_PRIVATE(self)->rsn_flags;
+}
+
+/*****************************************************************************/
+
+gboolean
+nm_wifi_ap_update_from_properties(NMWifiAP *ap, const NMSupplicantBssInfo *bss_info)
+{
+    NMWifiAPPrivate *priv;
+    gboolean         changed = FALSE;
+
+    g_return_val_if_fail(NM_IS_WIFI_AP(ap), FALSE);
+    g_return_val_if_fail(bss_info, FALSE);
+    nm_assert(NM_IS_REF_STRING(bss_info->bss_path));
+
+    priv = NM_WIFI_AP_GET_PRIVATE(ap);
+
+    nm_assert(!ap->_supplicant_path || ap->_supplicant_path == bss_info->bss_path);
+
+    g_object_freeze_notify(G_OBJECT(ap));
+
+    if (!ap->_supplicant_path) {
+        ap->_supplicant_path = nm_ref_string_ref(bss_info->bss_path);
+        changed              = TRUE;
+    }
+
+    changed |= nm_wifi_ap_set_flags(ap, bss_info->ap_flags);
+    changed |= nm_wifi_ap_set_mode(ap, bss_info->mode);
+    changed |= nm_wifi_ap_set_strength(ap, bss_info->signal_percent);
+    changed |= nm_wifi_ap_set_freq(ap, bss_info->frequency);
+    changed |= nm_wifi_ap_set_ssid(ap, bss_info->ssid);
+
+    if (bss_info->bssid_valid)
+        changed |= nm_wifi_ap_set_address_bin(ap, &bss_info->bssid);
+    else {
+        /* we don't actually clear the value. */
+    }
+
+    changed |= nm_wifi_ap_set_max_bitrate(ap, bss_info->max_rate);
+
+    if (priv->metered != bss_info->metered) {
+        priv->metered = bss_info->metered;
+        changed       = TRUE;
+    }
+
+    changed |= nm_wifi_ap_set_wpa_flags(ap, bss_info->wpa_flags);
+    changed |= nm_wifi_ap_set_rsn_flags(ap, bss_info->rsn_flags);
+
+    changed |= nm_wifi_ap_set_last_seen(ap, bss_info->last_seen_msec);
+
+    changed |= nm_wifi_ap_set_fake(ap, FALSE);
+
+    g_object_thaw_notify(G_OBJECT(ap));
+
+    return changed;
+}
+
+static gboolean
+has_proto(NMSettingWirelessSecurity *sec, const char *proto)
+{
+    guint32 num_protos = nm_setting_wireless_security_get_num_protos(sec);
+    guint32 i;
+
+    if (num_protos == 0)
+        return TRUE; /* interpret no protos as "all" */
+
+    for (i = 0; i < num_protos; i++) {
+        if (!strcmp(nm_setting_wireless_security_get_proto(sec, i), proto))
+            return TRUE;
+    }
+    return FALSE;
+}
+
+static void
+add_pair_ciphers(NMWifiAP *ap, NMSettingWirelessSecurity *sec)
+{
+    NMWifiAPPrivate *      priv  = NM_WIFI_AP_GET_PRIVATE(ap);
+    guint32                num   = nm_setting_wireless_security_get_num_pairwise(sec);
+    NM80211ApSecurityFlags flags = NM_802_11_AP_SEC_NONE;
+    guint32                i;
+
+    /* If no ciphers are specified, that means "all" WPA ciphers */
+    if (num == 0) {
+        flags |= NM_802_11_AP_SEC_PAIR_TKIP | NM_802_11_AP_SEC_PAIR_CCMP;
+    } else {
+        for (i = 0; i < num; i++) {
+            const char *cipher = nm_setting_wireless_security_get_pairwise(sec, i);
+
+            if (!strcmp(cipher, "tkip"))
+                flags |= NM_802_11_AP_SEC_PAIR_TKIP;
+            else if (!strcmp(cipher, "ccmp"))
+                flags |= NM_802_11_AP_SEC_PAIR_CCMP;
+        }
+    }
+
+    if (has_proto(sec, PROTO_WPA))
+        nm_wifi_ap_set_wpa_flags(ap, priv->wpa_flags | flags);
+    if (has_proto(sec, PROTO_RSN))
+        nm_wifi_ap_set_rsn_flags(ap, priv->rsn_flags | flags);
+}
+
+static void
+add_group_ciphers(NMWifiAP *ap, NMSettingWirelessSecurity *sec)
+{
+    NMWifiAPPrivate *      priv  = NM_WIFI_AP_GET_PRIVATE(ap);
+    guint32                num   = nm_setting_wireless_security_get_num_groups(sec);
+    NM80211ApSecurityFlags flags = NM_802_11_AP_SEC_NONE;
+    guint32                i;
+
+    /* If no ciphers are specified, that means "all" WPA ciphers */
+    if (num == 0) {
+        flags |= NM_802_11_AP_SEC_GROUP_TKIP | NM_802_11_AP_SEC_GROUP_CCMP;
+    } else {
+        for (i = 0; i < num; i++) {
+            const char *cipher = nm_setting_wireless_security_get_group(sec, i);
+
+            if (!strcmp(cipher, "wep40"))
+                flags |= NM_802_11_AP_SEC_GROUP_WEP40;
+            else if (!strcmp(cipher, "wep104"))
+                flags |= NM_802_11_AP_SEC_GROUP_WEP104;
+            else if (!strcmp(cipher, "tkip"))
+                flags |= NM_802_11_AP_SEC_GROUP_TKIP;
+            else if (!strcmp(cipher, "ccmp"))
+                flags |= NM_802_11_AP_SEC_GROUP_CCMP;
+        }
+    }
+
+    if (has_proto(sec, PROTO_WPA))
+        nm_wifi_ap_set_wpa_flags(ap, priv->wpa_flags | flags);
+    if (has_proto(sec, PROTO_RSN))
+        nm_wifi_ap_set_rsn_flags(ap, priv->rsn_flags | flags);
+}
+
+const char *
+nm_wifi_ap_to_string(const NMWifiAP *self, char *str_buf, gulong buf_len, gint64 now_msec)
+{
+    const NMWifiAPPrivate *priv;
+    const char *           supplicant_id = "-";
+    const char *           export_path;
+    guint32                chan;
+    gs_free char *         ssid_to_free = NULL;
+    char                   str_buf_ts[100];
+
+    g_return_val_if_fail(NM_IS_WIFI_AP(self), NULL);
+
+    priv = NM_WIFI_AP_GET_PRIVATE(self);
+
+    chan = nm_utils_wifi_freq_to_channel(priv->freq);
+    if (self->_supplicant_path)
+        supplicant_id = strrchr(self->_supplicant_path->str, '/') ?: supplicant_id;
+
+    export_path = nm_dbus_object_get_path(NM_DBUS_OBJECT(self));
+    if (export_path)
+        export_path = strrchr(export_path, '/') ?: export_path;
+    else
+        export_path = "/";
+
+    nm_utils_get_monotonic_timestamp_msec_cached(&now_msec);
+
+    g_snprintf(str_buf,
+               buf_len,
+               "%17s %-35s [ %c %3u %3u%% %c%c %c%c W:%04X R:%04X ] %s sup:%s [nm:%s]",
+               priv->address ?: "(none)",
+               (ssid_to_free = _nm_utils_ssid_to_string(priv->ssid)),
+               (priv->mode == NM_802_11_MODE_ADHOC
+                    ? '*'
+                    : (priv->hotspot
+                           ? '#'
+                           : (priv->fake ? 'f' : (priv->mode == NM_802_11_MODE_MESH ? 'm' : 'a')))),
+               chan,
+               priv->strength,
+               priv->flags & NM_802_11_AP_FLAGS_PRIVACY ? 'P' : '_',
+               priv->metered ? 'M' : '_',
+               priv->flags & NM_802_11_AP_FLAGS_WPS ? 'W' : '_',
+               priv->flags & NM_802_11_AP_FLAGS_WPS_PIN
+                   ? 'p'
+                   : (priv->flags & NM_802_11_AP_FLAGS_WPS_PBC ? '#' : '_'),
+               priv->wpa_flags & 0xFFFF,
+               priv->rsn_flags & 0xFFFF,
+               priv->last_seen_msec != G_MININT64
+                   ? nm_sprintf_buf(str_buf_ts,
+                                    "%3u.%03us",
+                                    (guint)((now_msec - priv->last_seen_msec) / 1000),
+                                    (guint)((now_msec - priv->last_seen_msec) % 1000))
+                   : "        ",
+               supplicant_id,
+               export_path);
+    return str_buf;
+}
+
+static guint
+freq_to_band(guint32 freq)
+{
+    if (freq >= 4915 && freq <= 5825)
+        return 5;
+    else if (freq >= 2412 && freq <= 2484)
+        return 2;
+    return 0;
+}
+
+gboolean
+nm_wifi_ap_check_compatible(NMWifiAP *self, NMConnection *connection)
+{
+    NMWifiAPPrivate *          priv;
+    NMSettingWireless *        s_wireless;
+    NMSettingWirelessSecurity *s_wireless_sec;
+    GBytes *                   ssid;
+    const char *               mode;
+    const char *               band;
+    const char *               bssid;
+    guint32                    channel;
+
+    g_return_val_if_fail(NM_IS_WIFI_AP(self), FALSE);
+    g_return_val_if_fail(NM_IS_CONNECTION(connection), FALSE);
+
+    priv = NM_WIFI_AP_GET_PRIVATE(self);
+
+    s_wireless = nm_connection_get_setting_wireless(connection);
+    if (s_wireless == NULL)
+        return FALSE;
+
+    ssid = nm_setting_wireless_get_ssid(s_wireless);
+    if (ssid != priv->ssid) {
+        if (!ssid || !priv->ssid)
+            return FALSE;
+        if (!g_bytes_equal(ssid, priv->ssid))
+            return FALSE;
+    }
+
+    bssid = nm_setting_wireless_get_bssid(s_wireless);
+    if (bssid && (!priv->address || !nm_utils_hwaddr_matches(bssid, -1, priv->address, -1)))
+        return FALSE;
+
+    mode = nm_setting_wireless_get_mode(s_wireless);
+    if (mode) {
+        if (!strcmp(mode, "infrastructure") && (priv->mode != NM_802_11_MODE_INFRA))
+            return FALSE;
+        if (!strcmp(mode, "adhoc") && (priv->mode != NM_802_11_MODE_ADHOC))
+            return FALSE;
+        if (!strcmp(mode, "ap") && (priv->mode != NM_802_11_MODE_INFRA || priv->hotspot != TRUE))
+            return FALSE;
+        if (!strcmp(mode, "mesh") && (priv->mode != NM_802_11_MODE_MESH))
+            return FALSE;
+    }
+
+    band = nm_setting_wireless_get_band(s_wireless);
+    if (band) {
+        guint ap_band = freq_to_band(priv->freq);
+
+        if (!strcmp(band, "a") && ap_band != 5)
+            return FALSE;
+        else if (!strcmp(band, "bg") && ap_band != 2)
+            return FALSE;
+    }
+
+    channel = nm_setting_wireless_get_channel(s_wireless);
+    if (channel) {
+        guint32 ap_chan = nm_utils_wifi_freq_to_channel(priv->freq);
+
+        if (channel != ap_chan)
+            return FALSE;
+    }
+
+    s_wireless_sec = nm_connection_get_setting_wireless_security(connection);
+
+    return nm_setting_wireless_ap_security_compatible(s_wireless,
+                                                      s_wireless_sec,
+                                                      priv->flags,
+                                                      priv->wpa_flags,
+                                                      priv->rsn_flags,
+                                                      priv->mode);
+}
+
+gboolean
+nm_wifi_ap_complete_connection(NMWifiAP *    self,
+                               NMConnection *connection,
+                               gboolean      lock_bssid,
+                               GError **     error)
+{
+    NMWifiAPPrivate *priv = NM_WIFI_AP_GET_PRIVATE(self);
+
+    g_return_val_if_fail(connection != NULL, FALSE);
+
+    return nm_wifi_utils_complete_connection(priv->ssid,
+                                             priv->address,
+                                             priv->mode,
+                                             priv->freq,
+                                             priv->flags,
+                                             priv->wpa_flags,
+                                             priv->rsn_flags,
+                                             connection,
+                                             lock_bssid,
+                                             error);
+}
+
+/*****************************************************************************/
+
+static void
+get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec)
+{
+    NMWifiAP *       self = NM_WIFI_AP(object);
+    NMWifiAPPrivate *priv = NM_WIFI_AP_GET_PRIVATE(self);
+
+    switch (prop_id) {
+    case PROP_FLAGS:
+        g_value_set_uint(value, priv->flags);
+        break;
+    case PROP_WPA_FLAGS:
+        g_value_set_uint(value, priv->wpa_flags);
+        break;
+    case PROP_RSN_FLAGS:
+        g_value_set_uint(value, priv->rsn_flags);
+        break;
+    case PROP_SSID:
+        g_value_take_variant(value, nm_utils_gbytes_to_variant_ay(priv->ssid));
+        break;
+    case PROP_FREQUENCY:
+        g_value_set_uint(value, priv->freq);
+        break;
+    case PROP_HW_ADDRESS:
+        g_value_set_string(value, priv->address);
+        break;
+    case PROP_MODE:
+        g_value_set_uint(value, priv->mode);
+        break;
+    case PROP_MAX_BITRATE:
+        g_value_set_uint(value, priv->max_bitrate);
+        break;
+    case PROP_STRENGTH:
+        g_value_set_uchar(value, priv->strength);
+        break;
+    case PROP_LAST_SEEN:
+        g_value_set_int(value,
+                        priv->last_seen_msec != G_MININT64 ? (int) NM_MAX(
+                            nm_utils_monotonic_timestamp_as_boottime(priv->last_seen_msec,
+                                                                     NM_UTILS_NSEC_PER_MSEC)
+                                / 1000,
+                            1)
+                                                           : -1);
+        break;
+    default:
+        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
+        break;
+    }
+}
+
+/*****************************************************************************/
+
+static void
+nm_wifi_ap_init(NMWifiAP *self)
+{
+    NMWifiAPPrivate *priv;
+
+    priv = G_TYPE_INSTANCE_GET_PRIVATE(self, NM_TYPE_WIFI_AP, NMWifiAPPrivate);
+
+    self->_priv = priv;
+
+    c_list_init(&self->aps_lst);
+
+    priv->mode           = NM_802_11_MODE_INFRA;
+    priv->flags          = NM_802_11_AP_FLAGS_NONE;
+    priv->wpa_flags      = NM_802_11_AP_SEC_NONE;
+    priv->rsn_flags      = NM_802_11_AP_SEC_NONE;
+    priv->last_seen_msec = G_MININT64;
+}
+
+NMWifiAP *
+nm_wifi_ap_new_from_properties(const NMSupplicantBssInfo *bss_info)
+{
+    NMWifiAP *ap;
+
+    ap = g_object_new(NM_TYPE_WIFI_AP, NULL);
+    nm_wifi_ap_update_from_properties(ap, bss_info);
+    return ap;
+}
+
+NMWifiAP *
+nm_wifi_ap_new_fake_from_connection(NMConnection *connection)
+{
+    NMWifiAP *                 ap;
+    NMWifiAPPrivate *          priv;
+    NMSettingWireless *        s_wireless;
+    NMSettingWirelessSecurity *s_wireless_sec;
+    const char *               mode, *band, *key_mgmt;
+    guint32                    channel;
+    NM80211ApSecurityFlags     flags;
+    gboolean                   psk = FALSE, eap = FALSE, adhoc = FALSE;
+
+    g_return_val_if_fail(connection != NULL, NULL);
+
+    s_wireless = nm_connection_get_setting_wireless(connection);
+    g_return_val_if_fail(s_wireless != NULL, NULL);
+
+    ap         = g_object_new(NM_TYPE_WIFI_AP, NULL);
+    priv       = NM_WIFI_AP_GET_PRIVATE(ap);
+    priv->fake = TRUE;
+
+    nm_wifi_ap_set_ssid(ap, nm_setting_wireless_get_ssid(s_wireless));
+
+    // FIXME: bssid too?
+
+    mode = nm_setting_wireless_get_mode(s_wireless);
+    if (mode) {
+        if (!strcmp(mode, "infrastructure"))
+            nm_wifi_ap_set_mode(ap, NM_802_11_MODE_INFRA);
+        else if (!strcmp(mode, "adhoc")) {
+            nm_wifi_ap_set_mode(ap, NM_802_11_MODE_ADHOC);
+            adhoc = TRUE;
+        } else if (!strcmp(mode, "mesh"))
+            nm_wifi_ap_set_mode(ap, NM_802_11_MODE_MESH);
+        else if (!strcmp(mode, "ap")) {
+            nm_wifi_ap_set_mode(ap, NM_802_11_MODE_INFRA);
+            NM_WIFI_AP_GET_PRIVATE(ap)->hotspot = TRUE;
+        } else
+            goto error;
+    } else {
+        nm_wifi_ap_set_mode(ap, NM_802_11_MODE_INFRA);
+    }
+
+    band    = nm_setting_wireless_get_band(s_wireless);
+    channel = nm_setting_wireless_get_channel(s_wireless);
+
+    if (band && channel) {
+        guint32 freq = nm_utils_wifi_channel_to_freq(channel, band);
+
+        if (freq == 0)
+            goto error;
+
+        nm_wifi_ap_set_freq(ap, freq);
+    }
+
+    s_wireless_sec = nm_connection_get_setting_wireless_security(connection);
+    /* Assume presence of a security setting means the AP is encrypted */
+    if (!s_wireless_sec)
+        goto done;
+
+    key_mgmt = nm_setting_wireless_security_get_key_mgmt(s_wireless_sec);
+
+    /* Everything below here uses encryption */
+    nm_wifi_ap_set_flags(ap, priv->flags | NM_802_11_AP_FLAGS_PRIVACY);
+
+    /* Static & Dynamic WEP */
+    if (!strcmp(key_mgmt, "none") || !strcmp(key_mgmt, "ieee8021x"))
+        goto done;
+
+    psk = nm_streq(key_mgmt, "wpa-psk");
+    eap = nm_streq(key_mgmt, "wpa-eap") || nm_streq(key_mgmt, "wpa-eap-suite-b-192");
+    if (!adhoc && (psk || eap)) {
+        if (has_proto(s_wireless_sec, PROTO_WPA)) {
+            flags = priv->wpa_flags
+                    | (eap ? NM_802_11_AP_SEC_KEY_MGMT_802_1X : NM_802_11_AP_SEC_KEY_MGMT_PSK);
+            nm_wifi_ap_set_wpa_flags(ap, flags);
+        }
+        if (has_proto(s_wireless_sec, PROTO_RSN)) {
+            flags = priv->rsn_flags
+                    | (eap ? NM_802_11_AP_SEC_KEY_MGMT_802_1X : NM_802_11_AP_SEC_KEY_MGMT_PSK);
+            nm_wifi_ap_set_rsn_flags(ap, flags);
+        }
+
+        add_pair_ciphers(ap, s_wireless_sec);
+        add_group_ciphers(ap, s_wireless_sec);
+    } else if (adhoc && psk) {
+        /* Ad-Hoc has special requirements: proto=RSN, pairwise=CCMP and
+         * group=CCMP.
+         */
+        flags = priv->wpa_flags | NM_802_11_AP_SEC_KEY_MGMT_PSK;
+
+        /* Clear ciphers; only CCMP is supported */
+        flags &= ~(NM_802_11_AP_SEC_PAIR_WEP40 | NM_802_11_AP_SEC_PAIR_WEP104
+                   | NM_802_11_AP_SEC_PAIR_TKIP | NM_802_11_AP_SEC_GROUP_WEP40
+                   | NM_802_11_AP_SEC_GROUP_WEP104 | NM_802_11_AP_SEC_GROUP_TKIP);
+
+        flags |= NM_802_11_AP_SEC_PAIR_CCMP;
+        flags |= NM_802_11_AP_SEC_GROUP_CCMP;
+        nm_wifi_ap_set_rsn_flags(ap, flags);
+
+        /* Don't use Ad-Hoc WPA (WPA-none) anymore */
+        nm_wifi_ap_set_wpa_flags(ap, NM_802_11_AP_SEC_NONE);
+    }
+done:
+    return ap;
+
+error:
+    g_object_unref(ap);
+    return NULL;
+}
+
+static void
+finalize(GObject *object)
+{
+    NMWifiAP *       self = NM_WIFI_AP(object);
+    NMWifiAPPrivate *priv = NM_WIFI_AP_GET_PRIVATE(self);
+
+    nm_assert(!self->wifi_device);
+    nm_assert(c_list_is_empty(&self->aps_lst));
+
+    nm_ref_string_unref(self->_supplicant_path);
+    if (priv->ssid)
+        g_bytes_unref(priv->ssid);
+    g_free(priv->address);
+
+    G_OBJECT_CLASS(nm_wifi_ap_parent_class)->finalize(object);
+}
+
+static const NMDBusInterfaceInfoExtended interface_info_access_point = {
+    .parent = NM_DEFINE_GDBUS_INTERFACE_INFO_INIT(
+        NM_DBUS_INTERFACE_ACCESS_POINT,
+        .signals    = NM_DEFINE_GDBUS_SIGNAL_INFOS(&nm_signal_info_property_changed_legacy, ),
+        .properties = NM_DEFINE_GDBUS_PROPERTY_INFOS(
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("Flags", "u", NM_WIFI_AP_FLAGS),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("WpaFlags", "u", NM_WIFI_AP_WPA_FLAGS),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("RsnFlags", "u", NM_WIFI_AP_RSN_FLAGS),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("Ssid", "ay", NM_WIFI_AP_SSID),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("Frequency",
+                                                             "u",
+                                                             NM_WIFI_AP_FREQUENCY),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("HwAddress",
+                                                             "s",
+                                                             NM_WIFI_AP_HW_ADDRESS),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("Mode", "u", NM_WIFI_AP_MODE),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("MaxBitrate",
+                                                             "u",
+                                                             NM_WIFI_AP_MAX_BITRATE),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("Strength", "y", NM_WIFI_AP_STRENGTH),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("LastSeen",
+                                                             "i",
+                                                             NM_WIFI_AP_LAST_SEEN), ), ),
+    .legacy_property_changed = TRUE,
+};
+
+static void
+nm_wifi_ap_class_init(NMWifiAPClass *ap_class)
+{
+#define ALL_SEC_FLAGS                                                                            \
+    (NM_802_11_AP_SEC_NONE | NM_802_11_AP_SEC_PAIR_WEP40 | NM_802_11_AP_SEC_PAIR_WEP104          \
+     | NM_802_11_AP_SEC_PAIR_TKIP | NM_802_11_AP_SEC_PAIR_CCMP | NM_802_11_AP_SEC_GROUP_WEP40    \
+     | NM_802_11_AP_SEC_GROUP_WEP104 | NM_802_11_AP_SEC_GROUP_TKIP | NM_802_11_AP_SEC_GROUP_CCMP \
+     | NM_802_11_AP_SEC_KEY_MGMT_PSK | NM_802_11_AP_SEC_KEY_MGMT_802_1X                          \
+     | NM_802_11_AP_SEC_KEY_MGMT_SAE | NM_802_11_AP_SEC_KEY_MGMT_OWE                             \
+     | NM_802_11_AP_SEC_KEY_MGMT_OWE_TM | NM_802_11_AP_SEC_KEY_MGMT_EAP_SUITE_B_192)
+
+    GObjectClass *     object_class      = G_OBJECT_CLASS(ap_class);
+    NMDBusObjectClass *dbus_object_class = NM_DBUS_OBJECT_CLASS(ap_class);
+
+    g_type_class_add_private(object_class, sizeof(NMWifiAPPrivate));
+
+    dbus_object_class->export_path     = NM_DBUS_EXPORT_PATH_NUMBERED(NM_DBUS_PATH_ACCESS_POINT);
+    dbus_object_class->interface_infos = NM_DBUS_INTERFACE_INFOS(&interface_info_access_point);
+
+    object_class->get_property = get_property;
+    object_class->finalize     = finalize;
+
+    obj_properties[PROP_FLAGS] = g_param_spec_uint(NM_WIFI_AP_FLAGS,
+                                                   "",
+                                                   "",
+                                                   NM_802_11_AP_FLAGS_NONE,
+                                                   NM_802_11_AP_FLAGS_PRIVACY,
+                                                   NM_802_11_AP_FLAGS_NONE,
+                                                   G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_WPA_FLAGS] = g_param_spec_uint(NM_WIFI_AP_WPA_FLAGS,
+                                                       "",
+                                                       "",
+                                                       NM_802_11_AP_SEC_NONE,
+                                                       ALL_SEC_FLAGS,
+                                                       NM_802_11_AP_SEC_NONE,
+                                                       G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_RSN_FLAGS] = g_param_spec_uint(NM_WIFI_AP_RSN_FLAGS,
+                                                       "",
+                                                       "",
+                                                       NM_802_11_AP_SEC_NONE,
+                                                       ALL_SEC_FLAGS,
+                                                       NM_802_11_AP_SEC_NONE,
+                                                       G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_SSID] = g_param_spec_variant(NM_WIFI_AP_SSID,
+                                                     "",
+                                                     "",
+                                                     G_VARIANT_TYPE("ay"),
+                                                     NULL,
+                                                     G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_FREQUENCY] = g_param_spec_uint(NM_WIFI_AP_FREQUENCY,
+                                                       "",
+                                                       "",
+                                                       0,
+                                                       10000,
+                                                       0,
+                                                       G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_HW_ADDRESS] =
+        g_param_spec_string(NM_WIFI_AP_HW_ADDRESS,
+                            "",
+                            "",
+                            NULL,
+                            G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_MODE] = g_param_spec_uint(NM_WIFI_AP_MODE,
+                                                  "",
+                                                  "",
+                                                  NM_802_11_MODE_ADHOC,
+                                                  NM_802_11_MODE_INFRA,
+                                                  NM_802_11_MODE_INFRA,
+                                                  G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_MAX_BITRATE] = g_param_spec_uint(NM_WIFI_AP_MAX_BITRATE,
+                                                         "",
+                                                         "",
+                                                         0,
+                                                         G_MAXUINT16,
+                                                         0,
+                                                         G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_STRENGTH] = g_param_spec_uchar(NM_WIFI_AP_STRENGTH,
+                                                       "",
+                                                       "",
+                                                       0,
+                                                       G_MAXINT8,
+                                                       0,
+                                                       G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_LAST_SEEN] = g_param_spec_int(NM_WIFI_AP_LAST_SEEN,
+                                                      "",
+                                                      "",
+                                                      -1,
+                                                      G_MAXINT,
+                                                      -1,
+                                                      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    g_object_class_install_properties(object_class, _PROPERTY_ENUMS_LAST, obj_properties);
+}
+
+/*****************************************************************************/
+
+const char **
+nm_wifi_aps_get_paths(const CList *aps_lst_head, gboolean include_without_ssid)
+{
+    NMWifiAP *   ap;
+    gsize        i, n;
+    const char **list;
+    const char * path;
+
+    n    = c_list_length(aps_lst_head);
+    list = g_new(const char *, n + 1);
+
+    i = 0;
+    if (n > 0) {
+        c_list_for_each_entry (ap, aps_lst_head, aps_lst) {
+            nm_assert(i < n);
+            if (!include_without_ssid && !nm_wifi_ap_get_ssid(ap))
+                continue;
+
+            path = nm_dbus_object_get_path(NM_DBUS_OBJECT(ap));
+            nm_assert(path);
+
+            list[i++] = path;
+        }
+        nm_assert(i <= n);
+        nm_assert(!include_without_ssid || i == n);
+    }
+    list[i] = NULL;
+    return list;
+}
+
+NMWifiAP *
+nm_wifi_aps_find_first_compatible(const CList *aps_lst_head, NMConnection *connection)
+{
+    NMWifiAP *ap;
+
+    g_return_val_if_fail(connection, NULL);
+
+    c_list_for_each_entry (ap, aps_lst_head, aps_lst) {
+        if (nm_wifi_ap_check_compatible(ap, connection))
+            return ap;
+    }
+    return NULL;
+}
+
+/*****************************************************************************/
+
+NMWifiAP *
+nm_wifi_ap_lookup_for_device(NMDevice *device, const char *exported_path)
+{
+    NMWifiAP *ap;
+
+    g_return_val_if_fail(NM_IS_DEVICE(device), NULL);
+
+    ap = nm_dbus_manager_lookup_object(nm_dbus_object_get_manager(NM_DBUS_OBJECT(device)),
+                                       exported_path);
+    if (!ap || !NM_IS_WIFI_AP(ap) || ap->wifi_device != device)
+        return NULL;
+
+    return ap;
+}
diff --git a/src/core/devices/wifi/nm-wifi-ap.h b/src/core/devices/wifi/nm-wifi-ap.h
new file mode 100644
index 00000000..bdd72415
--- /dev/null
+++ b/src/core/devices/wifi/nm-wifi-ap.h
@@ -0,0 +1,96 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+/*
+ * Copyright (C) 2004 - 2017 Red Hat, Inc.
+ * Copyright (C) 2006 - 2008 Novell, Inc.
+ */
+
+#ifndef __NM_WIFI_AP_H__
+#define __NM_WIFI_AP_H__
+
+#include "nm-dbus-object.h"
+#include "nm-dbus-interface.h"
+#include "nm-connection.h"
+
+#define NM_TYPE_WIFI_AP            (nm_wifi_ap_get_type())
+#define NM_WIFI_AP(obj)            (G_TYPE_CHECK_INSTANCE_CAST((obj), NM_TYPE_WIFI_AP, NMWifiAP))
+#define NM_WIFI_AP_CLASS(klass)    (G_TYPE_CHECK_CLASS_CAST((klass), NM_TYPE_WIFI_AP, NMWifiAPClass))
+#define NM_IS_WIFI_AP(obj)         (G_TYPE_CHECK_INSTANCE_TYPE((obj), NM_TYPE_WIFI_AP))
+#define NM_IS_WIFI_AP_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), NM_TYPE_WIFI_AP))
+#define NM_WIFI_AP_GET_CLASS(obj)  (G_TYPE_INSTANCE_GET_CLASS((obj), NM_TYPE_WIFI_AP, NMWifiAPClass))
+
+#define NM_WIFI_AP_FLAGS       "flags"
+#define NM_WIFI_AP_WPA_FLAGS   "wpa-flags"
+#define NM_WIFI_AP_RSN_FLAGS   "rsn-flags"
+#define NM_WIFI_AP_SSID        "ssid"
+#define NM_WIFI_AP_FREQUENCY   "frequency"
+#define NM_WIFI_AP_HW_ADDRESS  "hw-address"
+#define NM_WIFI_AP_MODE        "mode"
+#define NM_WIFI_AP_MAX_BITRATE "max-bitrate"
+#define NM_WIFI_AP_STRENGTH    "strength"
+#define NM_WIFI_AP_LAST_SEEN   "last-seen"
+
+typedef struct {
+    NMDBusObject             parent;
+    NMDevice *               wifi_device;
+    CList                    aps_lst;
+    NMRefString *            _supplicant_path;
+    struct _NMWifiAPPrivate *_priv;
+} NMWifiAP;
+
+struct _NMSupplicantBssInfo;
+
+typedef struct _NMWifiAPClass NMWifiAPClass;
+
+GType nm_wifi_ap_get_type(void);
+
+NMWifiAP *nm_wifi_ap_new_from_properties(const struct _NMSupplicantBssInfo *bss_info);
+NMWifiAP *nm_wifi_ap_new_fake_from_connection(NMConnection *connection);
+
+gboolean nm_wifi_ap_update_from_properties(NMWifiAP *                         ap,
+                                           const struct _NMSupplicantBssInfo *bss_info);
+
+gboolean nm_wifi_ap_check_compatible(NMWifiAP *self, NMConnection *connection);
+
+gboolean nm_wifi_ap_complete_connection(NMWifiAP *    self,
+                                        NMConnection *connection,
+                                        gboolean      lock_bssid,
+                                        GError **     error);
+
+static inline NMRefString *
+nm_wifi_ap_get_supplicant_path(NMWifiAP *ap)
+{
+    g_return_val_if_fail(NM_IS_WIFI_AP(ap), NULL);
+
+    return ap->_supplicant_path;
+}
+
+GBytes *               nm_wifi_ap_get_ssid(const NMWifiAP *ap);
+gboolean               nm_wifi_ap_set_ssid(NMWifiAP *ap, GBytes *ssid);
+const char *           nm_wifi_ap_get_address(const NMWifiAP *ap);
+gboolean               nm_wifi_ap_set_address(NMWifiAP *ap, const char *addr);
+gboolean               nm_wifi_ap_set_address_bin(NMWifiAP *ap, const NMEtherAddr *addr);
+NM80211Mode            nm_wifi_ap_get_mode(NMWifiAP *ap);
+gboolean               nm_wifi_ap_is_hotspot(NMWifiAP *ap);
+gint8                  nm_wifi_ap_get_strength(NMWifiAP *ap);
+gboolean               nm_wifi_ap_set_strength(NMWifiAP *ap, gint8 strength);
+guint32                nm_wifi_ap_get_freq(NMWifiAP *ap);
+gboolean               nm_wifi_ap_set_freq(NMWifiAP *ap, guint32 freq);
+guint32                nm_wifi_ap_get_max_bitrate(NMWifiAP *ap);
+gboolean               nm_wifi_ap_set_max_bitrate(NMWifiAP *ap, guint32 bitrate);
+gboolean               nm_wifi_ap_get_fake(const NMWifiAP *ap);
+gboolean               nm_wifi_ap_set_fake(NMWifiAP *ap, gboolean fake);
+NM80211ApFlags         nm_wifi_ap_get_flags(const NMWifiAP *self);
+gboolean               nm_wifi_ap_get_metered(const NMWifiAP *self);
+NM80211ApSecurityFlags nm_wifi_ap_get_wpa_flags(const NMWifiAP *self);
+NM80211ApSecurityFlags nm_wifi_ap_get_rsn_flags(const NMWifiAP *self);
+
+const char *
+nm_wifi_ap_to_string(const NMWifiAP *self, char *str_buf, gulong buf_len, gint64 now_msec);
+
+const char **nm_wifi_aps_get_paths(const CList *aps_lst_head, gboolean include_without_ssid);
+
+NMWifiAP *nm_wifi_aps_find_first_compatible(const CList *aps_lst_head, NMConnection *connection);
+
+NMWifiAP *nm_wifi_ap_lookup_for_device(NMDevice *device, const char *exported_path);
+
+#endif /* __NM_WIFI_AP_H__ */
diff --git a/src/core/devices/wifi/nm-wifi-common.c b/src/core/devices/wifi/nm-wifi-common.c
new file mode 100644
index 00000000..c715c07c
--- /dev/null
+++ b/src/core/devices/wifi/nm-wifi-common.c
@@ -0,0 +1,176 @@
+/* SPDX-License-Identifier: LGPL-2.1-or-later */
+/*
+ * Copyright (C) 2018 Red Hat, Inc.
+ */
+
+#include "src/core/nm-default-daemon.h"
+
+#include "nm-wifi-common.h"
+
+#include "devices/nm-device.h"
+#include "nm-wifi-ap.h"
+#include "nm-device-wifi.h"
+#include "nm-dbus-manager.h"
+
+#if WITH_IWD
+    #include "nm-device-iwd.h"
+#endif
+
+/*****************************************************************************/
+
+void
+nm_device_wifi_emit_signal_access_point(NMDevice *device,
+                                        NMWifiAP *ap,
+                                        gboolean  is_added /* or else is_removed */)
+{
+    nm_dbus_object_emit_signal(NM_DBUS_OBJECT(device),
+                               &nm_interface_info_device_wireless,
+                               is_added ? &nm_signal_info_wireless_access_point_added
+                                        : &nm_signal_info_wireless_access_point_removed,
+                               "(o)",
+                               nm_dbus_object_get_path(NM_DBUS_OBJECT(ap)));
+}
+
+/*****************************************************************************/
+
+static const CList *
+_dispatch_get_aps(NMDevice *device)
+{
+#if WITH_IWD
+    if (NM_IS_DEVICE_IWD(device))
+        return _nm_device_iwd_get_aps(NM_DEVICE_IWD(device));
+#endif
+    return _nm_device_wifi_get_aps(NM_DEVICE_WIFI(device));
+}
+
+static void
+_dispatch_request_scan(NMDevice *device, GVariant *options, GDBusMethodInvocation *invocation)
+{
+#if WITH_IWD
+    if (NM_IS_DEVICE_IWD(device)) {
+        _nm_device_iwd_request_scan(NM_DEVICE_IWD(device), options, invocation);
+        return;
+    }
+#endif
+    _nm_device_wifi_request_scan(NM_DEVICE_WIFI(device), options, invocation);
+}
+
+static void
+impl_device_wifi_get_access_points(NMDBusObject *                     obj,
+                                   const NMDBusInterfaceInfoExtended *interface_info,
+                                   const NMDBusMethodInfoExtended *   method_info,
+                                   GDBusConnection *                  connection,
+                                   const char *                       sender,
+                                   GDBusMethodInvocation *            invocation,
+                                   GVariant *                         parameters)
+{
+    gs_free const char **list = NULL;
+    GVariant *           v;
+    const CList *        all_aps;
+
+    /* NOTE: this handler is called both for NMDevicwWifi and NMDeviceIwd. */
+
+    all_aps = _dispatch_get_aps(NM_DEVICE(obj));
+    list    = nm_wifi_aps_get_paths(all_aps, FALSE);
+    v       = g_variant_new_objv(list, -1);
+    g_dbus_method_invocation_return_value(invocation, g_variant_new_tuple(&v, 1));
+}
+
+static void
+impl_device_wifi_get_all_access_points(NMDBusObject *                     obj,
+                                       const NMDBusInterfaceInfoExtended *interface_info,
+                                       const NMDBusMethodInfoExtended *   method_info,
+                                       GDBusConnection *                  connection,
+                                       const char *                       sender,
+                                       GDBusMethodInvocation *            invocation,
+                                       GVariant *                         parameters)
+{
+    gs_free const char **list = NULL;
+    GVariant *           v;
+    const CList *        all_aps;
+
+    /* NOTE: this handler is called both for NMDevicwWifi and NMDeviceIwd. */
+
+    all_aps = _dispatch_get_aps(NM_DEVICE(obj));
+    list    = nm_wifi_aps_get_paths(all_aps, TRUE);
+    v       = g_variant_new_objv(list, -1);
+    g_dbus_method_invocation_return_value(invocation, g_variant_new_tuple(&v, 1));
+}
+
+static void
+impl_device_wifi_request_scan(NMDBusObject *                     obj,
+                              const NMDBusInterfaceInfoExtended *interface_info,
+                              const NMDBusMethodInfoExtended *   method_info,
+                              GDBusConnection *                  connection,
+                              const char *                       sender,
+                              GDBusMethodInvocation *            invocation,
+                              GVariant *                         parameters)
+{
+    gs_unref_variant GVariant *options = NULL;
+
+    /* NOTE: this handler is called both for NMDevicwWifi and NMDeviceIwd. */
+
+    g_variant_get(parameters, "(@a{sv})", &options);
+
+    _dispatch_request_scan(NM_DEVICE(obj), options, invocation);
+}
+
+const GDBusSignalInfo nm_signal_info_wireless_access_point_added = NM_DEFINE_GDBUS_SIGNAL_INFO_INIT(
+    "AccessPointAdded",
+    .args = NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("access_point", "o"), ), );
+
+const GDBusSignalInfo nm_signal_info_wireless_access_point_removed =
+    NM_DEFINE_GDBUS_SIGNAL_INFO_INIT(
+        "AccessPointRemoved",
+        .args = NM_DEFINE_GDBUS_ARG_INFOS(NM_DEFINE_GDBUS_ARG_INFO("access_point", "o"), ), );
+
+const NMDBusInterfaceInfoExtended nm_interface_info_device_wireless = {
+    .parent = NM_DEFINE_GDBUS_INTERFACE_INFO_INIT(
+        NM_DBUS_INTERFACE_DEVICE_WIRELESS,
+        .methods = NM_DEFINE_GDBUS_METHOD_INFOS(
+            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(
+                NM_DEFINE_GDBUS_METHOD_INFO_INIT(
+                    "GetAccessPoints",
+                    .out_args = NM_DEFINE_GDBUS_ARG_INFOS(
+                        NM_DEFINE_GDBUS_ARG_INFO("access_points", "ao"), ), ),
+                .handle = impl_device_wifi_get_access_points, ),
+            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(
+                NM_DEFINE_GDBUS_METHOD_INFO_INIT(
+                    "GetAllAccessPoints",
+                    .out_args = NM_DEFINE_GDBUS_ARG_INFOS(
+                        NM_DEFINE_GDBUS_ARG_INFO("access_points", "ao"), ), ),
+                .handle = impl_device_wifi_get_all_access_points, ),
+            NM_DEFINE_DBUS_METHOD_INFO_EXTENDED(
+                NM_DEFINE_GDBUS_METHOD_INFO_INIT(
+                    "RequestScan",
+                    .in_args = NM_DEFINE_GDBUS_ARG_INFOS(
+                        NM_DEFINE_GDBUS_ARG_INFO("options", "a{sv}"), ), ),
+                .handle = impl_device_wifi_request_scan, ), ),
+        .signals    = NM_DEFINE_GDBUS_SIGNAL_INFOS(&nm_signal_info_property_changed_legacy,
+                                                &nm_signal_info_wireless_access_point_added,
+                                                &nm_signal_info_wireless_access_point_removed, ),
+        .properties = NM_DEFINE_GDBUS_PROPERTY_INFOS(
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("HwAddress",
+                                                             "s",
+                                                             NM_DEVICE_HW_ADDRESS),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("PermHwAddress",
+                                                             "s",
+                                                             NM_DEVICE_PERM_HW_ADDRESS),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("Mode", "u", NM_DEVICE_WIFI_MODE),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("Bitrate",
+                                                             "u",
+                                                             NM_DEVICE_WIFI_BITRATE),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("AccessPoints",
+                                                             "ao",
+                                                             NM_DEVICE_WIFI_ACCESS_POINTS),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("ActiveAccessPoint",
+                                                             "o",
+                                                             NM_DEVICE_WIFI_ACTIVE_ACCESS_POINT),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L("WirelessCapabilities",
+                                                             "u",
+                                                             NM_DEVICE_WIFI_CAPABILITIES),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE("LastScan",
+                                                           "x",
+                                                           NM_DEVICE_WIFI_LAST_SCAN), ), ),
+    .legacy_property_changed = TRUE,
+};
diff --git a/src/core/devices/wifi/nm-wifi-common.h b/src/core/devices/wifi/nm-wifi-common.h
new file mode 100644
index 00000000..fd6f47ed
--- /dev/null
+++ b/src/core/devices/wifi/nm-wifi-common.h
@@ -0,0 +1,22 @@
+/* SPDX-License-Identifier: LGPL-2.1-or-later */
+/*
+ * Copyright (C) 2018 Red Hat, Inc.
+ */
+
+#ifndef __NM_WIFI_COMMON_H__
+#define __NM_WIFI_COMMON_H__
+
+#include "nm-dbus-utils.h"
+#include "nm-wifi-ap.h"
+
+/*****************************************************************************/
+
+void nm_device_wifi_emit_signal_access_point(NMDevice *device,
+                                             NMWifiAP *ap,
+                                             gboolean  is_added /* or else is_removed */);
+
+extern const NMDBusInterfaceInfoExtended nm_interface_info_device_wireless;
+extern const GDBusSignalInfo             nm_signal_info_wireless_access_point_added;
+extern const GDBusSignalInfo             nm_signal_info_wireless_access_point_removed;
+
+#endif /* __NM_WIFI_COMMON_H__ */
diff --git a/src/core/devices/wifi/nm-wifi-factory.c b/src/core/devices/wifi/nm-wifi-factory.c
new file mode 100644
index 00000000..40375e1c
--- /dev/null
+++ b/src/core/devices/wifi/nm-wifi-factory.c
@@ -0,0 +1,157 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+/*
+ * Copyright (C) 2011 - 2014 Red Hat, Inc.
+ */
+
+#include "src/core/nm-default-daemon.h"
+
+#include <gmodule.h>
+
+#include "devices/nm-device-factory.h"
+#include "nm-setting-wireless.h"
+#include "nm-setting-olpc-mesh.h"
+#include "nm-device-wifi.h"
+#include "nm-device-wifi-p2p.h"
+#include "nm-device-olpc-mesh.h"
+#include "nm-device-iwd.h"
+#include "settings/nm-settings-connection.h"
+#include "platform/nm-platform.h"
+#include "nm-config.h"
+
+/*****************************************************************************/
+
+#define NM_TYPE_WIFI_FACTORY (nm_wifi_factory_get_type())
+#define NM_WIFI_FACTORY(obj) \
+    (G_TYPE_CHECK_INSTANCE_CAST((obj), NM_TYPE_WIFI_FACTORY, NMWifiFactory))
+#define NM_WIFI_FACTORY_CLASS(klass) \
+    (G_TYPE_CHECK_CLASS_CAST((klass), NM_TYPE_WIFI_FACTORY, NMWifiFactoryClass))
+#define NM_IS_WIFI_FACTORY(obj)         (G_TYPE_CHECK_INSTANCE_TYPE((obj), NM_TYPE_WIFI_FACTORY))
+#define NM_IS_WIFI_FACTORY_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), NM_TYPE_WIFI_FACTORY))
+#define NM_WIFI_FACTORY_GET_CLASS(obj) \
+    (G_TYPE_INSTANCE_GET_CLASS((obj), NM_TYPE_WIFI_FACTORY, NMWifiFactoryClass))
+
+typedef struct {
+    NMDeviceFactory parent;
+} NMWifiFactory;
+
+typedef struct {
+    NMDeviceFactoryClass parent;
+} NMWifiFactoryClass;
+
+static GType nm_wifi_factory_get_type(void);
+
+G_DEFINE_TYPE(NMWifiFactory, nm_wifi_factory, NM_TYPE_DEVICE_FACTORY)
+
+/*****************************************************************************/
+
+NM_DEVICE_FACTORY_DECLARE_TYPES(
+    NM_DEVICE_FACTORY_DECLARE_LINK_TYPES(NM_LINK_TYPE_WIFI, NM_LINK_TYPE_OLPC_MESH)
+        NM_DEVICE_FACTORY_DECLARE_SETTING_TYPES(NM_SETTING_WIRELESS_SETTING_NAME,
+                                                NM_SETTING_OLPC_MESH_SETTING_NAME))
+
+G_MODULE_EXPORT NMDeviceFactory *
+                nm_device_factory_create(GError **error)
+{
+    return g_object_new(NM_TYPE_WIFI_FACTORY, NULL);
+}
+
+/*****************************************************************************/
+
+static void
+p2p_device_created(NMDeviceWifi *device, NMDeviceWifiP2P *p2p_device, NMDeviceFactory *self)
+{
+    nm_log_info(LOGD_PLATFORM | LOGD_WIFI,
+                "Wi-Fi P2P device controlled by interface %s created",
+                nm_device_get_iface(NM_DEVICE(device)));
+
+    g_signal_emit_by_name(self, NM_DEVICE_FACTORY_DEVICE_ADDED, p2p_device);
+}
+
+static NMDevice *
+create_device(NMDeviceFactory *     factory,
+              const char *          iface,
+              const NMPlatformLink *plink,
+              NMConnection *        connection,
+              gboolean *            out_ignore)
+{
+    gs_free char *backend = NULL;
+
+    g_return_val_if_fail(iface != NULL, NULL);
+    g_return_val_if_fail(plink != NULL, NULL);
+    g_return_val_if_fail(g_strcmp0(iface, plink->name) == 0, NULL);
+    g_return_val_if_fail(NM_IN_SET(plink->type, NM_LINK_TYPE_WIFI, NM_LINK_TYPE_OLPC_MESH), NULL);
+
+    if (plink->type != NM_LINK_TYPE_WIFI)
+        return nm_device_olpc_mesh_new(iface);
+
+    backend = nm_config_data_get_device_config_by_pllink(NM_CONFIG_GET_DATA,
+                                                         NM_CONFIG_KEYFILE_KEY_DEVICE_WIFI_BACKEND,
+                                                         plink,
+                                                         "wifi",
+                                                         NULL);
+    nm_strstrip(backend);
+
+    nm_log_dbg(LOGD_PLATFORM | LOGD_WIFI,
+               "(%s) config: backend is %s%s%s%s",
+               iface,
+               NM_PRINT_FMT_QUOTE_STRING(backend),
+               WITH_IWD ? " (iwd support enabled)" : "");
+    if (!backend || !g_ascii_strcasecmp(backend, "wpa_supplicant")) {
+        NMDevice *               device;
+        NMDeviceWifiCapabilities capabilities;
+        NM80211Mode              mode;
+
+        if (!nm_platform_wifi_get_capabilities(NM_PLATFORM_GET, plink->ifindex, &capabilities)) {
+            nm_log_warn(LOGD_PLATFORM | LOGD_WIFI,
+                        "(%s) failed to initialize Wi-Fi driver for ifindex %d",
+                        iface,
+                        plink->ifindex);
+            return NULL;
+        }
+
+        /* Ignore monitor-mode and other unhandled interface types.
+         * FIXME: keep TYPE_MONITOR devices in UNAVAILABLE state and manage
+         * them if/when they change to a handled type.
+         */
+        mode = nm_platform_wifi_get_mode(NM_PLATFORM_GET, plink->ifindex);
+        if (mode == NM_802_11_MODE_UNKNOWN) {
+            *out_ignore = TRUE;
+            return NULL;
+        }
+
+        device = nm_device_wifi_new(iface, capabilities);
+
+        g_signal_connect_object(device,
+                                NM_DEVICE_WIFI_P2P_DEVICE_CREATED,
+                                G_CALLBACK(p2p_device_created),
+                                factory,
+                                0);
+
+        return device;
+    }
+#if WITH_IWD
+    else if (!g_ascii_strcasecmp(backend, "iwd"))
+        return nm_device_iwd_new(iface);
+#endif
+
+    nm_log_warn(LOGD_PLATFORM | LOGD_WIFI,
+                "(%s) config: unknown or unsupported wifi-backend %s",
+                iface,
+                backend);
+    return NULL;
+}
+
+/*****************************************************************************/
+
+static void
+nm_wifi_factory_init(NMWifiFactory *self)
+{}
+
+static void
+nm_wifi_factory_class_init(NMWifiFactoryClass *klass)
+{
+    NMDeviceFactoryClass *factory_class = NM_DEVICE_FACTORY_CLASS(klass);
+
+    factory_class->create_device       = create_device;
+    factory_class->get_supported_types = get_supported_types;
+}
diff --git a/src/core/devices/wifi/nm-wifi-p2p-peer.c b/src/core/devices/wifi/nm-wifi-p2p-peer.c
new file mode 100644
index 00000000..8488f32d
--- /dev/null
+++ b/src/core/devices/wifi/nm-wifi-p2p-peer.c
@@ -0,0 +1,699 @@
+/* SPDX-License-Identifier: LGPL-2.1-or-later */
+/*
+ * Copyright (C) 2018 Red Hat, Inc.
+ */
+
+#include "src/core/nm-default-daemon.h"
+
+#include "nm-wifi-p2p-peer.h"
+
+#include <stdlib.h>
+#include <linux/if_ether.h>
+
+#include "NetworkManagerUtils.h"
+#include "devices/nm-device.h"
+#include "nm-core-internal.h"
+#include "nm-dbus-manager.h"
+#include "nm-glib-aux/nm-ref-string.h"
+#include "nm-setting-wireless.h"
+#include "nm-utils.h"
+#include "nm-wifi-utils.h"
+#include "platform/nm-platform.h"
+#include "supplicant/nm-supplicant-types.h"
+
+/*****************************************************************************/
+
+NM_GOBJECT_PROPERTIES_DEFINE(NMWifiP2PPeer,
+                             PROP_NAME,
+                             PROP_MANUFACTURER,
+                             PROP_MODEL,
+                             PROP_MODEL_NUMBER,
+                             PROP_SERIAL,
+                             PROP_WFD_IES,
+                             PROP_HW_ADDRESS,
+                             PROP_STRENGTH,
+                             PROP_LAST_SEEN,
+                             PROP_FLAGS, );
+
+struct _NMWifiP2PPeerPrivate {
+    NMRefString *supplicant_path; /* D-Bus object path of this Peer from wpa_supplicant */
+
+    /* Scanned or cached values */
+    char *name;
+    char *manufacturer;
+    char *model;
+    char *model_number;
+    char *serial;
+
+    char *address;
+
+    GBytes *wfd_ies;
+
+    const char **groups;
+
+    guint8 strength;
+
+    NM80211ApFlags flags; /* General flags */
+
+    /* Non-scanned attributes */
+    gint32
+        last_seen; /* Timestamp when the Peer was seen lastly (obtained via nm_utils_get_monotonic_timestamp_sec()) */
+};
+
+typedef struct _NMWifiP2PPeerPrivate NMWifiP2PPeerPrivate;
+
+struct _NMWifiP2PPeerClass {
+    NMDBusObjectClass parent;
+};
+
+G_DEFINE_TYPE(NMWifiP2PPeer, nm_wifi_p2p_peer, NM_TYPE_DBUS_OBJECT)
+
+#define NM_WIFI_P2P_PEER_GET_PRIVATE(self) \
+    _NM_GET_PRIVATE_PTR(self, NMWifiP2PPeer, NM_IS_WIFI_P2P_PEER)
+
+/*****************************************************************************/
+
+const char **
+nm_wifi_p2p_peers_get_paths(const CList *peers_lst_head)
+{
+    NMWifiP2PPeer *peer;
+    const char **  list;
+    const char *   path;
+    gsize          i, n;
+
+    n    = c_list_length(peers_lst_head);
+    list = g_new(const char *, n + 1);
+
+    i = 0;
+    if (n > 0) {
+        c_list_for_each_entry (peer, peers_lst_head, peers_lst) {
+            nm_assert(i < n);
+            path = nm_dbus_object_get_path(NM_DBUS_OBJECT(peer));
+            nm_assert(path);
+
+            list[i++] = path;
+        }
+        nm_assert(i <= n);
+    }
+    list[i] = NULL;
+    return list;
+}
+
+NMWifiP2PPeer *
+nm_wifi_p2p_peers_find_first_compatible(const CList *peers_lst_head, NMConnection *connection)
+{
+    NMWifiP2PPeer *peer;
+
+    g_return_val_if_fail(connection, NULL);
+
+    c_list_for_each_entry (peer, peers_lst_head, peers_lst) {
+        if (nm_wifi_p2p_peer_check_compatible(peer, connection))
+            return peer;
+    }
+    return NULL;
+}
+
+NMWifiP2PPeer *
+nm_wifi_p2p_peers_find_by_supplicant_path(const CList *peers_lst_head, const char *path)
+{
+    NMWifiP2PPeer *peer;
+
+    g_return_val_if_fail(path != NULL, NULL);
+
+    c_list_for_each_entry (peer, peers_lst_head, peers_lst) {
+        if (nm_streq0(path, nm_wifi_p2p_peer_get_supplicant_path(peer)))
+            return peer;
+    }
+    return NULL;
+}
+
+/*****************************************************************************/
+
+NMWifiP2PPeer *
+nm_wifi_p2p_peer_lookup_for_device(NMDevice *device, const char *exported_path)
+{
+    NMWifiP2PPeer *peer;
+
+    g_return_val_if_fail(NM_IS_DEVICE(device), NULL);
+
+    peer = (NMWifiP2PPeer *) nm_dbus_manager_lookup_object(
+        nm_dbus_object_get_manager(NM_DBUS_OBJECT(device)),
+        exported_path);
+    if (!peer || !NM_IS_WIFI_P2P_PEER(peer) || peer->wifi_device != device)
+        return NULL;
+
+    return peer;
+}
+
+/*****************************************************************************/
+
+const char *
+nm_wifi_p2p_peer_get_supplicant_path(NMWifiP2PPeer *peer)
+{
+    g_return_val_if_fail(NM_IS_WIFI_P2P_PEER(peer), NULL);
+
+    return nm_ref_string_get_str(NM_WIFI_P2P_PEER_GET_PRIVATE(peer)->supplicant_path);
+}
+
+const char *
+nm_wifi_p2p_peer_get_name(const NMWifiP2PPeer *peer)
+{
+    g_return_val_if_fail(NM_IS_WIFI_P2P_PEER(peer), NULL);
+
+    return NM_WIFI_P2P_PEER_GET_PRIVATE(peer)->name;
+}
+
+gboolean
+nm_wifi_p2p_peer_set_name(NMWifiP2PPeer *peer, const char *str)
+{
+    NMWifiP2PPeerPrivate *priv = NM_WIFI_P2P_PEER_GET_PRIVATE(peer);
+
+    if (!nm_utils_strdup_reset(&priv->name, str))
+        return FALSE;
+    _notify(peer, PROP_NAME);
+    return TRUE;
+}
+
+const char *
+nm_wifi_p2p_peer_get_manufacturer(const NMWifiP2PPeer *peer)
+{
+    g_return_val_if_fail(NM_IS_WIFI_P2P_PEER(peer), NULL);
+
+    return NM_WIFI_P2P_PEER_GET_PRIVATE(peer)->manufacturer;
+}
+
+gboolean
+nm_wifi_p2p_peer_set_manufacturer(NMWifiP2PPeer *peer, const char *str)
+{
+    NMWifiP2PPeerPrivate *priv = NM_WIFI_P2P_PEER_GET_PRIVATE(peer);
+
+    if (!nm_utils_strdup_reset(&priv->manufacturer, str))
+        return FALSE;
+    _notify(peer, PROP_MANUFACTURER);
+    return TRUE;
+}
+
+const char *
+nm_wifi_p2p_peer_get_model(const NMWifiP2PPeer *peer)
+{
+    g_return_val_if_fail(NM_IS_WIFI_P2P_PEER(peer), NULL);
+
+    return NM_WIFI_P2P_PEER_GET_PRIVATE(peer)->model;
+}
+
+gboolean
+nm_wifi_p2p_peer_set_model(NMWifiP2PPeer *peer, const char *str)
+{
+    NMWifiP2PPeerPrivate *priv = NM_WIFI_P2P_PEER_GET_PRIVATE(peer);
+
+    if (!nm_utils_strdup_reset(&priv->model, str))
+        return FALSE;
+    _notify(peer, PROP_MODEL);
+    return TRUE;
+}
+
+const char *
+nm_wifi_p2p_peer_get_model_number(const NMWifiP2PPeer *peer)
+{
+    g_return_val_if_fail(NM_IS_WIFI_P2P_PEER(peer), NULL);
+
+    return NM_WIFI_P2P_PEER_GET_PRIVATE(peer)->model_number;
+}
+
+gboolean
+nm_wifi_p2p_peer_set_model_number(NMWifiP2PPeer *peer, const char *str)
+{
+    NMWifiP2PPeerPrivate *priv = NM_WIFI_P2P_PEER_GET_PRIVATE(peer);
+
+    if (!nm_utils_strdup_reset(&priv->model_number, str))
+        return FALSE;
+    _notify(peer, PROP_MODEL_NUMBER);
+    return TRUE;
+}
+
+const char *
+nm_wifi_p2p_peer_get_serial(const NMWifiP2PPeer *peer)
+{
+    g_return_val_if_fail(NM_IS_WIFI_P2P_PEER(peer), NULL);
+
+    return NM_WIFI_P2P_PEER_GET_PRIVATE(peer)->serial;
+}
+
+gboolean
+nm_wifi_p2p_peer_set_serial(NMWifiP2PPeer *peer, const char *str)
+{
+    NMWifiP2PPeerPrivate *priv = NM_WIFI_P2P_PEER_GET_PRIVATE(peer);
+
+    if (!nm_utils_strdup_reset(&priv->serial, str))
+        return FALSE;
+    _notify(peer, PROP_SERIAL);
+    return TRUE;
+}
+
+GBytes *
+nm_wifi_p2p_peer_get_wfd_ies(const NMWifiP2PPeer *peer)
+{
+    g_return_val_if_fail(NM_IS_WIFI_P2P_PEER(peer), NULL);
+
+    return NM_WIFI_P2P_PEER_GET_PRIVATE(peer)->wfd_ies;
+}
+
+gboolean
+nm_wifi_p2p_peer_set_wfd_ies(NMWifiP2PPeer *peer, GBytes *wfd_ies)
+{
+    NMWifiP2PPeerPrivate *priv;
+    gs_unref_bytes GBytes *wfd_ies_old = NULL;
+
+    g_return_val_if_fail(NM_IS_WIFI_P2P_PEER(peer), FALSE);
+
+    priv = NM_WIFI_P2P_PEER_GET_PRIVATE(peer);
+
+    if (nm_gbytes_equal0(priv->wfd_ies, wfd_ies))
+        return FALSE;
+
+    wfd_ies_old   = g_steal_pointer(&priv->wfd_ies);
+    priv->wfd_ies = wfd_ies ? g_bytes_ref(wfd_ies) : NULL;
+
+    _notify(peer, PROP_WFD_IES);
+    return TRUE;
+}
+
+const char *const *
+nm_wifi_p2p_peer_get_groups(const NMWifiP2PPeer *peer)
+{
+    g_return_val_if_fail(NM_IS_WIFI_P2P_PEER(peer), NULL);
+
+    return NM_WIFI_P2P_PEER_GET_PRIVATE(peer)->groups;
+}
+
+const char *
+nm_wifi_p2p_peer_get_address(const NMWifiP2PPeer *peer)
+{
+    g_return_val_if_fail(NM_IS_WIFI_P2P_PEER(peer), NULL);
+
+    return NM_WIFI_P2P_PEER_GET_PRIVATE(peer)->address;
+}
+
+static gboolean
+nm_wifi_p2p_peer_set_address_bin(NMWifiP2PPeer *peer, const guint8 addr[static ETH_ALEN])
+{
+    NMWifiP2PPeerPrivate *priv = NM_WIFI_P2P_PEER_GET_PRIVATE(peer);
+
+    if (priv->address && nm_utils_hwaddr_matches(addr, ETH_ALEN, priv->address, -1))
+        return FALSE;
+
+    g_free(priv->address);
+    priv->address = nm_utils_hwaddr_ntoa(addr, ETH_ALEN);
+    _notify(peer, PROP_HW_ADDRESS);
+    return TRUE;
+}
+
+gboolean
+nm_wifi_p2p_peer_set_address(NMWifiP2PPeer *peer, const char *addr)
+{
+    guint8 addr_buf[ETH_ALEN];
+
+    g_return_val_if_fail(NM_IS_WIFI_P2P_PEER(peer), FALSE);
+
+    if (!addr || !nm_utils_hwaddr_aton(addr, addr_buf, sizeof(addr_buf)))
+        g_return_val_if_reached(FALSE);
+
+    return nm_wifi_p2p_peer_set_address_bin(peer, addr_buf);
+}
+
+gint8
+nm_wifi_p2p_peer_get_strength(NMWifiP2PPeer *peer)
+{
+    g_return_val_if_fail(NM_IS_WIFI_P2P_PEER(peer), 0);
+
+    return NM_WIFI_P2P_PEER_GET_PRIVATE(peer)->strength;
+}
+
+gboolean
+nm_wifi_p2p_peer_set_strength(NMWifiP2PPeer *peer, const gint8 strength)
+{
+    NMWifiP2PPeerPrivate *priv = NM_WIFI_P2P_PEER_GET_PRIVATE(peer);
+
+    if (priv->strength != strength) {
+        priv->strength = strength;
+        _notify(peer, PROP_STRENGTH);
+        return TRUE;
+    }
+    return FALSE;
+}
+
+NM80211ApFlags
+nm_wifi_p2p_peer_get_flags(const NMWifiP2PPeer *peer)
+{
+    g_return_val_if_fail(NM_IS_WIFI_P2P_PEER(peer), NM_802_11_AP_FLAGS_NONE);
+
+    return NM_WIFI_P2P_PEER_GET_PRIVATE(peer)->flags;
+}
+
+static gboolean
+nm_wifi_p2p_peer_set_last_seen(NMWifiP2PPeer *peer, gint32 last_seen)
+{
+    NMWifiP2PPeerPrivate *priv;
+
+    g_return_val_if_fail(NM_IS_WIFI_P2P_PEER(peer), FALSE);
+
+    priv = NM_WIFI_P2P_PEER_GET_PRIVATE(peer);
+
+    if (priv->last_seen != last_seen) {
+        priv->last_seen = last_seen;
+        _notify(peer, PROP_LAST_SEEN);
+        return TRUE;
+    }
+    return FALSE;
+}
+
+/*****************************************************************************/
+
+gboolean
+nm_wifi_p2p_peer_update_from_properties(NMWifiP2PPeer *peer, const NMSupplicantPeerInfo *peer_info)
+{
+    NMWifiP2PPeerPrivate *priv;
+    gboolean              changed = FALSE;
+
+    g_return_val_if_fail(NM_IS_WIFI_P2P_PEER(peer), FALSE);
+    g_return_val_if_fail(peer_info, FALSE);
+    nm_assert(NM_IS_REF_STRING(peer_info->peer_path));
+
+    priv = NM_WIFI_P2P_PEER_GET_PRIVATE(peer);
+
+    nm_assert(!priv->supplicant_path || priv->supplicant_path == peer_info->peer_path);
+
+    g_object_freeze_notify(G_OBJECT(peer));
+
+    if (!priv->supplicant_path) {
+        priv->supplicant_path = nm_ref_string_ref(peer_info->peer_path);
+        changed               = TRUE;
+    }
+
+    changed |= nm_wifi_p2p_peer_set_strength(peer, peer_info->signal_percent);
+    changed |= nm_wifi_p2p_peer_set_name(peer, peer_info->device_name);
+    changed |= nm_wifi_p2p_peer_set_manufacturer(peer, peer_info->manufacturer);
+    changed |= nm_wifi_p2p_peer_set_model(peer, peer_info->model);
+    changed |= nm_wifi_p2p_peer_set_model_number(peer, peer_info->model_number);
+    changed |= nm_wifi_p2p_peer_set_serial(peer, peer_info->serial);
+
+    if (peer_info->address_valid)
+        changed |= nm_wifi_p2p_peer_set_address_bin(peer, peer_info->address);
+    else {
+        /* we don't reset the address. */
+    }
+
+    changed |= nm_wifi_p2p_peer_set_wfd_ies(peer, peer_info->ies);
+    changed |= nm_wifi_p2p_peer_set_last_seen(peer, peer_info->last_seen_msec / 1000u);
+
+    /* We currently only use the groups information internally to check if
+     * the peer is still joined. */
+    if (!nm_utils_strv_equal(priv->groups, peer_info->groups)) {
+        g_free(priv->groups);
+        priv->groups = nm_utils_strv_dup_packed(peer_info->groups, -1);
+        changed |= TRUE;
+    }
+
+    g_object_thaw_notify(G_OBJECT(peer));
+
+    return changed;
+}
+
+const char *
+nm_wifi_p2p_peer_to_string(const NMWifiP2PPeer *self, char *str_buf, gsize buf_len, gint32 now_s)
+{
+    const NMWifiP2PPeerPrivate *priv;
+    const char *                supplicant_id = "-";
+    const char *                export_path;
+
+    g_return_val_if_fail(NM_IS_WIFI_P2P_PEER(self), NULL);
+
+    priv = NM_WIFI_P2P_PEER_GET_PRIVATE(self);
+
+    if (priv->supplicant_path)
+        supplicant_id = strrchr(priv->supplicant_path->str, '/') ?: supplicant_id;
+
+    export_path = nm_dbus_object_get_path(NM_DBUS_OBJECT(self));
+    if (export_path)
+        export_path = strrchr(export_path, '/') ?: export_path;
+    else
+        export_path = "/";
+
+    g_snprintf(str_buf,
+               buf_len,
+               "%17s [n:%s, m:%s, mod:%s, mod_num:%s, ser:%s] %3us sup:%s [nm:%s]",
+               priv->address ?: "(none)",
+               priv->name,
+               priv->manufacturer,
+               priv->model,
+               priv->model_number,
+               priv->serial,
+               priv->last_seen > 0 ? ((now_s > 0 ? now_s : nm_utils_get_monotonic_timestamp_sec())
+                                      - priv->last_seen)
+                                   : -1,
+               supplicant_id,
+               export_path);
+
+    return str_buf;
+}
+
+gboolean
+nm_wifi_p2p_peer_check_compatible(NMWifiP2PPeer *self, NMConnection *connection)
+{
+    NMWifiP2PPeerPrivate *priv;
+    NMSettingWifiP2P *    s_wifi_p2p;
+    const char *          hwaddr;
+
+    g_return_val_if_fail(NM_IS_WIFI_P2P_PEER(self), FALSE);
+    g_return_val_if_fail(NM_IS_CONNECTION(connection), FALSE);
+
+    priv = NM_WIFI_P2P_PEER_GET_PRIVATE(self);
+
+    s_wifi_p2p =
+        NM_SETTING_WIFI_P2P(nm_connection_get_setting(connection, NM_TYPE_SETTING_WIFI_P2P));
+    if (s_wifi_p2p == NULL)
+        return FALSE;
+
+    hwaddr = nm_setting_wifi_p2p_get_peer(s_wifi_p2p);
+    if (hwaddr && (!priv->address || !nm_utils_hwaddr_matches(hwaddr, -1, priv->address, -1)))
+        return FALSE;
+
+    return TRUE;
+}
+
+/*****************************************************************************/
+
+static void
+get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec)
+{
+    NMWifiP2PPeer *       self = NM_WIFI_P2P_PEER(object);
+    NMWifiP2PPeerPrivate *priv = NM_WIFI_P2P_PEER_GET_PRIVATE(self);
+
+    switch (prop_id) {
+    case PROP_FLAGS:
+        g_value_set_uint(value, priv->flags);
+        break;
+    case PROP_NAME:
+        g_value_set_string(value, priv->name);
+        break;
+    case PROP_MANUFACTURER:
+        g_value_set_string(value, priv->manufacturer);
+        break;
+    case PROP_MODEL:
+        g_value_set_string(value, priv->model);
+        break;
+    case PROP_MODEL_NUMBER:
+        g_value_set_string(value, priv->model_number);
+        break;
+    case PROP_SERIAL:
+        g_value_set_string(value, priv->serial);
+        break;
+    case PROP_WFD_IES:
+        g_value_take_variant(value, nm_utils_gbytes_to_variant_ay(priv->wfd_ies));
+        break;
+    case PROP_HW_ADDRESS:
+        g_value_set_string(value, priv->address);
+        break;
+    case PROP_STRENGTH:
+        g_value_set_uchar(value, priv->strength);
+        break;
+    case PROP_LAST_SEEN:
+        g_value_set_int(value,
+                        priv->last_seen > 0
+                            ? (int) nm_utils_monotonic_timestamp_as_boottime(priv->last_seen,
+                                                                             NM_UTILS_NSEC_PER_SEC)
+                            : -1);
+        break;
+    default:
+        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
+        break;
+    }
+}
+
+/*****************************************************************************/
+
+static void
+nm_wifi_p2p_peer_init(NMWifiP2PPeer *self)
+{
+    NMWifiP2PPeerPrivate *priv;
+
+    priv = G_TYPE_INSTANCE_GET_PRIVATE(self, NM_TYPE_WIFI_P2P_PEER, NMWifiP2PPeerPrivate);
+
+    self->_priv = priv;
+
+    c_list_init(&self->peers_lst);
+
+    priv->flags     = NM_802_11_AP_FLAGS_NONE;
+    priv->last_seen = -1;
+}
+
+NMWifiP2PPeer *
+nm_wifi_p2p_peer_new_from_properties(const NMSupplicantPeerInfo *peer_info)
+{
+    NMWifiP2PPeer *peer;
+
+    g_return_val_if_fail(peer_info, NULL);
+
+    peer = g_object_new(NM_TYPE_WIFI_P2P_PEER, NULL);
+    nm_wifi_p2p_peer_update_from_properties(peer, peer_info);
+    return peer;
+}
+
+static void
+finalize(GObject *object)
+{
+    NMWifiP2PPeer *       self = NM_WIFI_P2P_PEER(object);
+    NMWifiP2PPeerPrivate *priv = NM_WIFI_P2P_PEER_GET_PRIVATE(self);
+
+    nm_assert(!self->wifi_device);
+    nm_assert(c_list_is_empty(&self->peers_lst));
+
+    nm_ref_string_unref(priv->supplicant_path);
+    g_free(priv->name);
+    g_free(priv->manufacturer);
+    g_free(priv->model);
+    g_free(priv->model_number);
+    g_free(priv->serial);
+    g_free(priv->address);
+    g_bytes_unref(priv->wfd_ies);
+    g_free(priv->groups);
+
+    G_OBJECT_CLASS(nm_wifi_p2p_peer_parent_class)->finalize(object);
+}
+
+static const NMDBusInterfaceInfoExtended interface_info_p2p_peer = {
+    .parent = NM_DEFINE_GDBUS_INTERFACE_INFO_INIT(
+        NM_DBUS_INTERFACE_WIFI_P2P_PEER,
+        .properties = NM_DEFINE_GDBUS_PROPERTY_INFOS(
+            /* Before 1.24, we wrongly exposed a property "Groups" of type "as". Don't reuse that property name. */
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE("Flags", "u", NM_WIFI_P2P_PEER_FLAGS),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE("Name", "s", NM_WIFI_P2P_PEER_NAME),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE("Manufacturer",
+                                                           "s",
+                                                           NM_WIFI_P2P_PEER_MANUFACTURER),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE("Model", "s", NM_WIFI_P2P_PEER_MODEL),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE("ModelNumber",
+                                                           "s",
+                                                           NM_WIFI_P2P_PEER_MODEL_NUMBER),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE("Serial", "s", NM_WIFI_P2P_PEER_SERIAL),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE("WfdIEs",
+                                                           "ay",
+                                                           NM_WIFI_P2P_PEER_WFD_IES),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE("HwAddress",
+                                                           "s",
+                                                           NM_WIFI_P2P_PEER_HW_ADDRESS),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE("Strength",
+                                                           "y",
+                                                           NM_WIFI_P2P_PEER_STRENGTH),
+            NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE("LastSeen",
+                                                           "i",
+                                                           NM_WIFI_P2P_PEER_LAST_SEEN), ), ),
+    .legacy_property_changed = FALSE,
+};
+
+static void
+nm_wifi_p2p_peer_class_init(NMWifiP2PPeerClass *klass)
+{
+    GObjectClass *     object_class      = G_OBJECT_CLASS(klass);
+    NMDBusObjectClass *dbus_object_class = NM_DBUS_OBJECT_CLASS(klass);
+
+    g_type_class_add_private(object_class, sizeof(NMWifiP2PPeerPrivate));
+
+    dbus_object_class->export_path     = NM_DBUS_EXPORT_PATH_NUMBERED(NM_DBUS_PATH_WIFI_P2P_PEER);
+    dbus_object_class->interface_infos = NM_DBUS_INTERFACE_INFOS(&interface_info_p2p_peer);
+
+    object_class->get_property = get_property;
+    object_class->finalize     = finalize;
+
+    obj_properties[PROP_FLAGS] = g_param_spec_uint(NM_WIFI_P2P_PEER_FLAGS,
+                                                   "",
+                                                   "",
+                                                   NM_802_11_AP_FLAGS_NONE,
+                                                   NM_802_11_AP_FLAGS_PRIVACY,
+                                                   NM_802_11_AP_FLAGS_NONE,
+                                                   G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_NAME] = g_param_spec_string(NM_WIFI_P2P_PEER_NAME,
+                                                    "",
+                                                    "",
+                                                    NULL,
+                                                    G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_MANUFACTURER] =
+        g_param_spec_string(NM_WIFI_P2P_PEER_MANUFACTURER,
+                            "",
+                            "",
+                            NULL,
+                            G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_MODEL] = g_param_spec_string(NM_WIFI_P2P_PEER_MODEL,
+                                                     "",
+                                                     "",
+                                                     NULL,
+                                                     G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_MODEL_NUMBER] =
+        g_param_spec_string(NM_WIFI_P2P_PEER_MODEL_NUMBER,
+                            "",
+                            "",
+                            NULL,
+                            G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_SERIAL] = g_param_spec_string(NM_WIFI_P2P_PEER_SERIAL,
+                                                      "",
+                                                      "",
+                                                      NULL,
+                                                      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_WFD_IES] = g_param_spec_variant(NM_WIFI_P2P_PEER_WFD_IES,
+                                                        "",
+                                                        "",
+                                                        G_VARIANT_TYPE("ay"),
+                                                        NULL,
+                                                        G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_HW_ADDRESS] =
+        g_param_spec_string(NM_WIFI_P2P_PEER_HW_ADDRESS,
+                            "",
+                            "",
+                            NULL,
+                            G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_STRENGTH] = g_param_spec_uchar(NM_WIFI_P2P_PEER_STRENGTH,
+                                                       "",
+                                                       "",
+                                                       0,
+                                                       G_MAXINT8,
+                                                       0,
+                                                       G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    obj_properties[PROP_LAST_SEEN] = g_param_spec_int(NM_WIFI_P2P_PEER_LAST_SEEN,
+                                                      "",
+                                                      "",
+                                                      -1,
+                                                      G_MAXINT,
+                                                      -1,
+                                                      G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
+
+    g_object_class_install_properties(object_class, _PROPERTY_ENUMS_LAST, obj_properties);
+}
diff --git a/src/core/devices/wifi/nm-wifi-p2p-peer.h b/src/core/devices/wifi/nm-wifi-p2p-peer.h
new file mode 100644
index 00000000..ee4bfb53
--- /dev/null
+++ b/src/core/devices/wifi/nm-wifi-p2p-peer.h
@@ -0,0 +1,91 @@
+/* SPDX-License-Identifier: LGPL-2.1-or-later */
+/*
+ * Copyright (C) 2018 Red Hat, Inc.
+ */
+
+#ifndef __NM_WIFI_P2P_PEER_H__
+#define __NM_WIFI_P2P_PEER_H__
+
+#include "nm-dbus-object.h"
+#include "nm-dbus-interface.h"
+#include "nm-connection.h"
+
+#define NM_TYPE_WIFI_P2P_PEER (nm_wifi_p2p_peer_get_type())
+#define NM_WIFI_P2P_PEER(obj) \
+    (G_TYPE_CHECK_INSTANCE_CAST((obj), NM_TYPE_WIFI_P2P_PEER, NMWifiP2PPeer))
+#define NM_WIFI_P2P_PEER_CLASS(klass) \
+    (G_TYPE_CHECK_CLASS_CAST((klass), NM_TYPE_WIFI_P2P_PEER, NMWifiP2PPeerClass))
+#define NM_IS_WIFI_P2P_PEER(obj)         (G_TYPE_CHECK_INSTANCE_TYPE((obj), NM_TYPE_WIFI_P2P_PEER))
+#define NM_IS_WIFI_P2P_PEER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), NM_TYPE_WIFI_P2P_PEER))
+#define NM_WIFI_P2P_PEER_GET_CLASS(obj) \
+    (G_TYPE_INSTANCE_GET_CLASS((obj), NM_TYPE_WIFI_P2P_PEER, NMWifiP2PPeerClass))
+
+#define NM_WIFI_P2P_PEER_FLAGS        "flags"
+#define NM_WIFI_P2P_PEER_NAME         "name"
+#define NM_WIFI_P2P_PEER_MANUFACTURER "manufacturer"
+#define NM_WIFI_P2P_PEER_MODEL        "model"
+#define NM_WIFI_P2P_PEER_MODEL_NUMBER "model-number"
+#define NM_WIFI_P2P_PEER_SERIAL       "serial"
+#define NM_WIFI_P2P_PEER_WFD_IES      "wfd-ies"
+#define NM_WIFI_P2P_PEER_HW_ADDRESS   "hw-address"
+#define NM_WIFI_P2P_PEER_STRENGTH     "strength"
+#define NM_WIFI_P2P_PEER_LAST_SEEN    "last-seen"
+
+typedef struct {
+    NMDBusObject                  parent;
+    NMDevice *                    wifi_device;
+    CList                         peers_lst;
+    struct _NMWifiP2PPeerPrivate *_priv;
+} NMWifiP2PPeer;
+
+typedef struct _NMWifiP2PPeerClass NMWifiP2PPeerClass;
+
+struct _NMSupplicantPeerInfo;
+
+GType nm_wifi_p2p_peer_get_type(void);
+
+NMWifiP2PPeer *nm_wifi_p2p_peer_new_from_properties(const struct _NMSupplicantPeerInfo *peer_info);
+
+gboolean nm_wifi_p2p_peer_update_from_properties(NMWifiP2PPeer *                     peer,
+                                                 const struct _NMSupplicantPeerInfo *peer_info);
+
+gboolean nm_wifi_p2p_peer_check_compatible(NMWifiP2PPeer *self, NMConnection *connection);
+
+const char *nm_wifi_p2p_peer_get_supplicant_path(NMWifiP2PPeer *peer);
+
+const char *nm_wifi_p2p_peer_get_name(const NMWifiP2PPeer *peer);
+gboolean    nm_wifi_p2p_peer_set_name(NMWifiP2PPeer *peer, const char *name);
+const char *nm_wifi_p2p_peer_get_manufacturer(const NMWifiP2PPeer *peer);
+gboolean    nm_wifi_p2p_peer_set_manufacturer(NMWifiP2PPeer *peer, const char *manufacturer);
+const char *nm_wifi_p2p_peer_get_model(const NMWifiP2PPeer *peer);
+gboolean    nm_wifi_p2p_peer_set_model(NMWifiP2PPeer *peer, const char *model);
+const char *nm_wifi_p2p_peer_get_model_number(const NMWifiP2PPeer *peer);
+gboolean    nm_wifi_p2p_peer_set_model_number(NMWifiP2PPeer *peer, const char *number);
+const char *nm_wifi_p2p_peer_get_serial(const NMWifiP2PPeer *peer);
+gboolean    nm_wifi_p2p_peer_set_serial(NMWifiP2PPeer *peer, const char *serial);
+
+GBytes * nm_wifi_p2p_peer_get_wfd_ies(const NMWifiP2PPeer *peer);
+gboolean nm_wifi_p2p_peer_set_wfd_ies(NMWifiP2PPeer *peer, GBytes *bytes);
+
+const char *const *nm_wifi_p2p_peer_get_groups(const NMWifiP2PPeer *peer);
+
+const char *   nm_wifi_p2p_peer_get_address(const NMWifiP2PPeer *peer);
+gboolean       nm_wifi_p2p_peer_set_address(NMWifiP2PPeer *peer, const char *addr);
+gint8          nm_wifi_p2p_peer_get_strength(NMWifiP2PPeer *peer);
+gboolean       nm_wifi_p2p_peer_set_strength(NMWifiP2PPeer *peer, gint8 strength);
+NM80211ApFlags nm_wifi_p2p_peer_get_flags(const NMWifiP2PPeer *self);
+
+const char *
+nm_wifi_p2p_peer_to_string(const NMWifiP2PPeer *self, char *str_buf, gsize buf_len, gint32 now_s);
+
+const char **nm_wifi_p2p_peers_get_paths(const CList *peers_lst_head);
+
+NMWifiP2PPeer *nm_wifi_p2p_peers_find_first_compatible(const CList * peers_lst_head,
+                                                       NMConnection *connection);
+
+NMWifiP2PPeer *nm_wifi_p2p_peers_find_by_supplicant_path(const CList *peers_lst_head,
+                                                         const char * path);
+
+NMWifiP2PPeer *nm_wifi_p2p_peer_lookup_for_device(NMDevice *device, const char *exported_path);
+
+#endif /* __NM_WIFI_P2P_PEER_H__ */
diff --git a/src/core/devices/wifi/nm-wifi-utils.c b/src/core/devices/wifi/nm-wifi-utils.c
new file mode 100644
index 00000000..aed236cc
--- /dev/null
+++ b/src/core/devices/wifi/nm-wifi-utils.c
@@ -0,0 +1,945 @@
+/* SPDX-License-Identifier: LGPL-2.1-or-later */
+/*
+ * Copyright (C) 2011 Red Hat, Inc.
+ */
+
+#include "src/core/nm-default-daemon.h"
+
+#include "nm-wifi-utils.h"
+
+#include <stdlib.h>
+
+#include "nm-utils.h"
+#include "nm-core-internal.h"
+
+static gboolean
+verify_no_wep(NMSettingWirelessSecurity *s_wsec, const char *tag, GError **error)
+{
+    if (nm_setting_wireless_security_get_wep_key(s_wsec, 0)
+        || nm_setting_wireless_security_get_wep_key(s_wsec, 1)
+        || nm_setting_wireless_security_get_wep_key(s_wsec, 2)
+        || nm_setting_wireless_security_get_wep_key(s_wsec, 3)
+        || nm_setting_wireless_security_get_wep_tx_keyidx(s_wsec)
+        || nm_setting_wireless_security_get_wep_key_type(s_wsec)) {
+        /* Dynamic WEP cannot have any WEP keys set */
+        g_set_error(error,
+                    NM_CONNECTION_ERROR,
+                    NM_CONNECTION_ERROR_INVALID_SETTING,
+                    _("%s is incompatible with static WEP keys"),
+                    tag);
+        g_prefix_error(error, "%s: ", NM_SETTING_WIRELESS_SECURITY_SETTING_NAME);
+        return FALSE;
+    }
+
+    return TRUE;
+}
+
+static gboolean
+verify_leap(NMSettingWirelessSecurity *s_wsec,
+            NMSetting8021x *           s_8021x,
+            gboolean                   adhoc,
+            GError **                  error)
+{
+    const char *key_mgmt, *auth_alg, *leap_username;
+
+    key_mgmt      = nm_setting_wireless_security_get_key_mgmt(s_wsec);
+    auth_alg      = nm_setting_wireless_security_get_auth_alg(s_wsec);
+    leap_username = nm_setting_wireless_security_get_leap_username(s_wsec);
+
+    /* One (or both) of two things indicates we want LEAP:
+     * 1) auth_alg == 'leap'
+     * 2) valid leap_username
+     *
+     * LEAP always requires a LEAP username.
+     */
+
+    if (auth_alg) {
+        if (!strcmp(auth_alg, "leap")) {
+            /* LEAP authentication requires at least a LEAP username */
+            if (!leap_username) {
+                g_set_error_literal(error,
+                                    NM_CONNECTION_ERROR,
+                                    NM_CONNECTION_ERROR_MISSING_PROPERTY,
+                                    _("LEAP authentication requires a LEAP username"));
+                g_prefix_error(error,
+                               "%s.%s: ",
+                               NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                               NM_SETTING_WIRELESS_SECURITY_LEAP_USERNAME);
+                return FALSE;
+            }
+        } else if (leap_username) {
+            /* Leap username requires 'leap' auth */
+            g_set_error_literal(error,
+                                NM_CONNECTION_ERROR,
+                                NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                                _("LEAP username requires 'leap' authentication"));
+            g_prefix_error(error,
+                           "%s.%s: ",
+                           NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                           NM_SETTING_WIRELESS_SECURITY_LEAP_USERNAME);
+            return FALSE;
+        }
+    }
+
+    if (leap_username) {
+        if (key_mgmt && strcmp(key_mgmt, "ieee8021x")) {
+            /* LEAP requires ieee8021x key management */
+            g_set_error_literal(error,
+                                NM_CONNECTION_ERROR,
+                                NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                                _("LEAP authentication requires IEEE 802.1x key management"));
+            g_prefix_error(error,
+                           "%s.%s: ",
+                           NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                           NM_SETTING_WIRELESS_SECURITY_KEY_MGMT);
+            return FALSE;
+        }
+    }
+
+    /* At this point if auth_alg is set it must be 'leap', and if key_mgmt
+     * is set it must be 'ieee8021x'.
+     */
+    if (leap_username) {
+        if (auth_alg)
+            g_assert(strcmp(auth_alg, "leap") == 0);
+        if (key_mgmt)
+            g_assert(strcmp(key_mgmt, "ieee8021x") == 0);
+
+        if (adhoc) {
+            g_set_error_literal(error,
+                                NM_CONNECTION_ERROR,
+                                NM_CONNECTION_ERROR_INVALID_SETTING,
+                                _("LEAP authentication is incompatible with Ad-Hoc mode"));
+            g_prefix_error(error, "%s: ", NM_SETTING_WIRELESS_SECURITY_SETTING_NAME);
+            return FALSE;
+        }
+
+        if (!verify_no_wep(s_wsec, "LEAP", error))
+            return FALSE;
+
+        if (s_8021x) {
+            g_set_error_literal(error,
+                                NM_CONNECTION_ERROR,
+                                NM_CONNECTION_ERROR_INVALID_SETTING,
+                                _("LEAP authentication is incompatible with 802.1x setting"));
+            g_prefix_error(error, "%s: ", NM_SETTING_802_1X_SETTING_NAME);
+            return FALSE;
+        }
+    }
+
+    return TRUE;
+}
+
+static gboolean
+verify_no_wpa(NMSettingWirelessSecurity *s_wsec, const char *tag, GError **error)
+{
+    const char *key_mgmt;
+    int         n, i;
+
+    key_mgmt = nm_setting_wireless_security_get_key_mgmt(s_wsec);
+    if (key_mgmt && !strncmp(key_mgmt, "wpa", 3)) {
+        g_set_error(error,
+                    NM_CONNECTION_ERROR,
+                    NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                    _("a connection using '%s' authentication cannot use WPA key management"),
+                    tag);
+        g_prefix_error(error,
+                       "%s.%s: ",
+                       NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                       NM_SETTING_WIRELESS_SECURITY_KEY_MGMT);
+        return FALSE;
+    }
+
+    if (nm_setting_wireless_security_get_num_protos(s_wsec)) {
+        g_set_error(error,
+                    NM_CONNECTION_ERROR,
+                    NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                    _("a connection using '%s' authentication cannot specify WPA protocols"),
+                    tag);
+        g_prefix_error(error,
+                       "%s.%s: ",
+                       NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                       NM_SETTING_WIRELESS_SECURITY_PROTO);
+        return FALSE;
+    }
+
+    n = nm_setting_wireless_security_get_num_pairwise(s_wsec);
+    for (i = 0; i < n; i++) {
+        const char *pw;
+
+        pw = nm_setting_wireless_security_get_pairwise(s_wsec, i);
+        if (!strcmp(pw, "tkip") || !strcmp(pw, "ccmp")) {
+            g_set_error(error,
+                        NM_CONNECTION_ERROR,
+                        NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                        _("a connection using '%s' authentication cannot specify WPA ciphers"),
+                        tag);
+            g_prefix_error(error,
+                           "%s.%s: ",
+                           NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                           NM_SETTING_WIRELESS_SECURITY_PAIRWISE);
+            return FALSE;
+        }
+    }
+
+    n = nm_setting_wireless_security_get_num_groups(s_wsec);
+    for (i = 0; i < n; i++) {
+        const char *gr;
+
+        gr = nm_setting_wireless_security_get_group(s_wsec, i);
+        if (strcmp(gr, "wep40") && strcmp(gr, "wep104")) {
+            g_set_error(error,
+                        NM_CONNECTION_ERROR,
+                        NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                        _("a connection using '%s' authentication cannot specify WPA ciphers"),
+                        tag);
+            g_prefix_error(error,
+                           "%s.%s: ",
+                           NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                           NM_SETTING_WIRELESS_SECURITY_GROUP);
+            return FALSE;
+        }
+    }
+
+    if (nm_setting_wireless_security_get_psk(s_wsec)) {
+        g_set_error(error,
+                    NM_CONNECTION_ERROR,
+                    NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                    _("a connection using '%s' authentication cannot specify a WPA password"),
+                    tag);
+        g_prefix_error(error,
+                       "%s.%s: ",
+                       NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                       NM_SETTING_WIRELESS_SECURITY_PSK);
+        return FALSE;
+    }
+
+    return TRUE;
+}
+
+static gboolean
+verify_dynamic_wep(NMSettingWirelessSecurity *s_wsec,
+                   NMSetting8021x *           s_8021x,
+                   gboolean                   adhoc,
+                   GError **                  error)
+{
+    const char *key_mgmt, *auth_alg, *leap_username;
+
+    key_mgmt      = nm_setting_wireless_security_get_key_mgmt(s_wsec);
+    auth_alg      = nm_setting_wireless_security_get_auth_alg(s_wsec);
+    leap_username = nm_setting_wireless_security_get_leap_username(s_wsec);
+
+    g_return_val_if_fail(leap_username == NULL, TRUE);
+
+    if (key_mgmt) {
+        if (!strcmp(key_mgmt, "ieee8021x")) {
+            if (!s_8021x) {
+                /* 802.1x key management requires an 802.1x setting */
+                g_set_error_literal(error,
+                                    NM_CONNECTION_ERROR,
+                                    NM_CONNECTION_ERROR_MISSING_SETTING,
+                                    _("Dynamic WEP requires an 802.1x setting"));
+                g_prefix_error(error, "%s: ", NM_SETTING_802_1X_SETTING_NAME);
+                return FALSE;
+            }
+
+            if (auth_alg && strcmp(auth_alg, "open")) {
+                /* 802.1x key management must use "open" authentication */
+                g_set_error_literal(error,
+                                    NM_CONNECTION_ERROR,
+                                    NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                                    _("Dynamic WEP requires 'open' authentication"));
+                g_prefix_error(error,
+                               "%s.%s: ",
+                               NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                               NM_SETTING_WIRELESS_SECURITY_AUTH_ALG);
+                return FALSE;
+            }
+
+            /* Dynamic WEP incompatible with anything static WEP related */
+            if (!verify_no_wep(s_wsec, "Dynamic WEP", error))
+                return FALSE;
+        } else if (!strcmp(key_mgmt, "none")) {
+            if (s_8021x) {
+                /* 802.1x setting requires 802.1x key management */
+                g_set_error_literal(error,
+                                    NM_CONNECTION_ERROR,
+                                    NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                                    _("Dynamic WEP requires 'ieee8021x' key management"));
+                g_prefix_error(error,
+                               "%s.%s: ",
+                               NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                               NM_SETTING_WIRELESS_SECURITY_KEY_MGMT);
+                return FALSE;
+            }
+        }
+    } else if (s_8021x) {
+        /* 802.1x setting incompatible with anything but 'open' auth */
+        if (auth_alg && strcmp(auth_alg, "open")) {
+            /* 802.1x key management must use "open" authentication */
+            g_set_error_literal(error,
+                                NM_CONNECTION_ERROR,
+                                NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                                _("Dynamic WEP requires 'open' authentication"));
+            g_prefix_error(error,
+                           "%s.%s: ",
+                           NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                           NM_SETTING_WIRELESS_SECURITY_AUTH_ALG);
+            return FALSE;
+        }
+
+        /* Dynamic WEP incompatible with anything static WEP related */
+        if (!verify_no_wep(s_wsec, "Dynamic WEP", error))
+            return FALSE;
+    }
+
+    return TRUE;
+}
+
+static gboolean
+verify_wpa_psk(NMSettingWirelessSecurity *s_wsec,
+               NMSetting8021x *           s_8021x,
+               gboolean                   adhoc,
+               guint32                    wpa_flags,
+               guint32                    rsn_flags,
+               GError **                  error)
+{
+    const char *key_mgmt, *auth_alg;
+
+    key_mgmt = nm_setting_wireless_security_get_key_mgmt(s_wsec);
+    auth_alg = nm_setting_wireless_security_get_auth_alg(s_wsec);
+
+    if (!nm_streq0(key_mgmt, "wpa-psk"))
+        return TRUE;
+
+    if (s_8021x) {
+        g_set_error_literal(error,
+                            NM_CONNECTION_ERROR,
+                            NM_CONNECTION_ERROR_INVALID_SETTING,
+                            _("WPA-PSK authentication is incompatible with 802.1x"));
+        g_prefix_error(error, "%s: ", NM_SETTING_802_1X_SETTING_NAME);
+        return FALSE;
+    }
+
+    if (auth_alg && !nm_streq(auth_alg, "open")) {
+        /* WPA must use "open" authentication */
+        g_set_error_literal(error,
+                            NM_CONNECTION_ERROR,
+                            NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                            _("WPA-PSK requires 'open' authentication"));
+        g_prefix_error(error,
+                       "%s.%s: ",
+                       NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                       NM_SETTING_WIRELESS_SECURITY_AUTH_ALG);
+        return FALSE;
+    }
+
+    /* Make sure the AP's capabilities support WPA-PSK */
+    if (!(wpa_flags & NM_802_11_AP_SEC_KEY_MGMT_PSK)
+        && !(rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_PSK)) {
+        g_set_error_literal(error,
+                            NM_CONNECTION_ERROR,
+                            NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                            _("Access point does not support PSK but setting requires it"));
+        g_prefix_error(error,
+                       "%s.%s: ",
+                       NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                       NM_SETTING_WIRELESS_SECURITY_KEY_MGMT);
+        return FALSE;
+    }
+
+    if (adhoc) {
+        /* Ad-Hoc RSN requires 'rsn' proto, 'ccmp' pairwise, and 'ccmp' group */
+        if (nm_setting_wireless_security_get_num_protos(s_wsec) != 1
+            || !nm_streq0(nm_setting_wireless_security_get_proto(s_wsec, 0), "rsn")) {
+            g_set_error_literal(error,
+                                NM_CONNECTION_ERROR,
+                                NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                                _("WPA Ad-Hoc authentication requires 'rsn' protocol"));
+            g_prefix_error(error,
+                           "%s.%s: ",
+                           NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                           NM_SETTING_WIRELESS_SECURITY_PROTO);
+            return FALSE;
+        }
+
+        if (nm_setting_wireless_security_get_num_pairwise(s_wsec) != 1
+            || !nm_streq0(nm_setting_wireless_security_get_pairwise(s_wsec, 0), "ccmp")) {
+            g_set_error_literal(error,
+                                NM_CONNECTION_ERROR,
+                                NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                                _("WPA Ad-Hoc authentication requires 'ccmp' pairwise cipher"));
+            g_prefix_error(error,
+                           "%s.%s: ",
+                           NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                           NM_SETTING_WIRELESS_SECURITY_PAIRWISE);
+            return FALSE;
+        }
+
+        if (nm_setting_wireless_security_get_num_groups(s_wsec) != 1
+            || !nm_streq0(nm_setting_wireless_security_get_group(s_wsec, 0), "ccmp")) {
+            g_set_error_literal(error,
+                                NM_CONNECTION_ERROR,
+                                NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                                _("WPA Ad-Hoc requires 'ccmp' group cipher"));
+            g_prefix_error(error,
+                           "%s.%s: ",
+                           NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                           NM_SETTING_WIRELESS_SECURITY_GROUP);
+            return FALSE;
+        }
+    }
+
+    return TRUE;
+}
+
+static gboolean
+verify_wpa_eap(NMSettingWirelessSecurity *s_wsec,
+               NMSetting8021x *           s_8021x,
+               guint32                    wpa_flags,
+               guint32                    rsn_flags,
+               GError **                  error)
+{
+    const char *key_mgmt, *auth_alg;
+    gboolean    is_wpa_eap = FALSE;
+
+    key_mgmt = nm_setting_wireless_security_get_key_mgmt(s_wsec);
+    auth_alg = nm_setting_wireless_security_get_auth_alg(s_wsec);
+
+    if (key_mgmt) {
+        if (NM_IN_STRSET(key_mgmt, "wpa-eap", "wpa-eap-suite-b-192")) {
+            if (!s_8021x) {
+                g_set_error_literal(error,
+                                    NM_CONNECTION_ERROR,
+                                    NM_CONNECTION_ERROR_MISSING_SETTING,
+                                    _("WPA-EAP authentication requires an 802.1x setting"));
+                g_prefix_error(error, "%s: ", NM_SETTING_802_1X_SETTING_NAME);
+                return FALSE;
+            }
+
+            if (auth_alg && strcmp(auth_alg, "open")) {
+                /* WPA must use "open" authentication */
+                g_set_error_literal(error,
+                                    NM_CONNECTION_ERROR,
+                                    NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                                    _("WPA-EAP requires 'open' authentication"));
+                g_prefix_error(error,
+                               "%s.%s: ",
+                               NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                               NM_SETTING_WIRELESS_SECURITY_AUTH_ALG);
+                return FALSE;
+            }
+
+            is_wpa_eap = TRUE;
+        } else if (s_8021x) {
+            g_set_error_literal(error,
+                                NM_CONNECTION_ERROR,
+                                NM_CONNECTION_ERROR_INVALID_SETTING,
+                                _("802.1x setting requires 'wpa-eap' key management"));
+            g_prefix_error(error, "%s: ", NM_SETTING_802_1X_SETTING_NAME);
+            return FALSE;
+        }
+    }
+
+    if (is_wpa_eap || s_8021x) {
+        /* Make sure the AP's capabilities support WPA-EAP */
+        if (!(wpa_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X)
+            && !(rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_802_1X)
+            && !(rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_EAP_SUITE_B_192)) {
+            g_set_error_literal(error,
+                                NM_CONNECTION_ERROR,
+                                NM_CONNECTION_ERROR_INVALID_SETTING,
+                                _("Access point does not support 802.1x but setting requires it"));
+            g_prefix_error(error, "%s: ", NM_SETTING_802_1X_SETTING_NAME);
+            return FALSE;
+        }
+    }
+
+    return TRUE;
+}
+
+static gboolean
+verify_adhoc(NMSettingWirelessSecurity *s_wsec,
+             NMSetting8021x *           s_8021x,
+             gboolean                   adhoc,
+             GError **                  error)
+{
+    const char *key_mgmt = NULL, *leap_username = NULL, *auth_alg = NULL;
+
+    if (!adhoc)
+        return TRUE;
+
+    if (s_wsec) {
+        key_mgmt      = nm_setting_wireless_security_get_key_mgmt(s_wsec);
+        auth_alg      = nm_setting_wireless_security_get_auth_alg(s_wsec);
+        leap_username = nm_setting_wireless_security_get_leap_username(s_wsec);
+    }
+
+    if (key_mgmt && !NM_IN_STRSET(key_mgmt, "none", "wpa-psk")) {
+        g_set_error_literal(error,
+                            NM_CONNECTION_ERROR,
+                            NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                            _("Ad-Hoc mode requires 'none' or 'wpa-psk' key management"));
+        g_prefix_error(error,
+                       "%s.%s: ",
+                       NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                       NM_SETTING_WIRELESS_SECURITY_KEY_MGMT);
+        return FALSE;
+    }
+
+    if (s_8021x) {
+        g_set_error_literal(error,
+                            NM_CONNECTION_ERROR,
+                            NM_CONNECTION_ERROR_INVALID_SETTING,
+                            _("Ad-Hoc mode is incompatible with 802.1x security"));
+        g_prefix_error(error, "%s: ", NM_SETTING_802_1X_SETTING_NAME);
+        return FALSE;
+    }
+
+    if (leap_username) {
+        g_set_error_literal(error,
+                            NM_CONNECTION_ERROR,
+                            NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                            _("Ad-Hoc mode is incompatible with LEAP security"));
+        g_prefix_error(error,
+                       "%s.%s: ",
+                       NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                       NM_SETTING_WIRELESS_SECURITY_AUTH_ALG);
+        return FALSE;
+    }
+
+    if (auth_alg && !nm_streq(auth_alg, "open")) {
+        g_set_error_literal(error,
+                            NM_CONNECTION_ERROR,
+                            NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                            _("Ad-Hoc mode requires 'open' authentication"));
+        g_prefix_error(error,
+                       "%s.%s: ",
+                       NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                       NM_SETTING_WIRELESS_SECURITY_AUTH_ALG);
+        return FALSE;
+    }
+
+    return TRUE;
+}
+
+gboolean
+nm_wifi_utils_complete_connection(GBytes *      ap_ssid,
+                                  const char *  bssid,
+                                  NM80211Mode   ap_mode,
+                                  guint32       ap_freq,
+                                  guint32       ap_flags,
+                                  guint32       ap_wpa_flags,
+                                  guint32       ap_rsn_flags,
+                                  NMConnection *connection,
+                                  gboolean      lock_bssid,
+                                  GError **     error)
+{
+    NMSettingWireless *        s_wifi;
+    NMSettingWirelessSecurity *s_wsec;
+    NMSetting8021x *           s_8021x;
+    GBytes *                   ssid;
+    const char *               mode, *key_mgmt, *auth_alg, *leap_username;
+    gboolean                   adhoc = FALSE;
+    gboolean                   mesh  = FALSE;
+
+    s_wifi = nm_connection_get_setting_wireless(connection);
+    g_assert(s_wifi);
+    s_wsec  = nm_connection_get_setting_wireless_security(connection);
+    s_8021x = nm_connection_get_setting_802_1x(connection);
+
+    /* Fill in missing SSID */
+    ssid = nm_setting_wireless_get_ssid(s_wifi);
+    if (!ssid)
+        g_object_set(G_OBJECT(s_wifi), NM_SETTING_WIRELESS_SSID, ap_ssid, NULL);
+    else if (!ap_ssid || !g_bytes_equal(ssid, ap_ssid)) {
+        g_set_error_literal(error,
+                            NM_CONNECTION_ERROR,
+                            NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                            _("connection does not match access point"));
+        g_prefix_error(error,
+                       "%s.%s: ",
+                       NM_SETTING_WIRELESS_SETTING_NAME,
+                       NM_SETTING_WIRELESS_SSID);
+        return FALSE;
+    }
+
+    if (lock_bssid && !nm_setting_wireless_get_bssid(s_wifi))
+        g_object_set(G_OBJECT(s_wifi), NM_SETTING_WIRELESS_BSSID, bssid, NULL);
+
+    /* And mode */
+    mode = nm_setting_wireless_get_mode(s_wifi);
+    if (mode) {
+        gboolean valid = FALSE;
+
+        /* Make sure the supplied mode matches the AP's */
+        if (!strcmp(mode, NM_SETTING_WIRELESS_MODE_INFRA)
+            || !strcmp(mode, NM_SETTING_WIRELESS_MODE_AP)) {
+            if (ap_mode == NM_802_11_MODE_INFRA)
+                valid = TRUE;
+        } else if (!strcmp(mode, NM_SETTING_WIRELESS_MODE_ADHOC)) {
+            if (ap_mode == NM_802_11_MODE_ADHOC)
+                valid = TRUE;
+            adhoc = TRUE;
+        } else if (!strcmp(mode, NM_SETTING_WIRELESS_MODE_MESH)) {
+            if (ap_mode == NM_802_11_MODE_MESH)
+                valid = TRUE;
+            mesh = TRUE;
+        }
+
+        if (valid == FALSE) {
+            g_set_error(error,
+                        NM_CONNECTION_ERROR,
+                        NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                        _("connection does not match access point"));
+            g_prefix_error(error,
+                           "%s.%s: ",
+                           NM_SETTING_WIRELESS_SETTING_NAME,
+                           NM_SETTING_WIRELESS_MODE);
+            return FALSE;
+        }
+    } else {
+        mode = NM_SETTING_WIRELESS_MODE_INFRA;
+        if (ap_mode == NM_802_11_MODE_ADHOC) {
+            mode  = NM_SETTING_WIRELESS_MODE_ADHOC;
+            adhoc = TRUE;
+        } else if (ap_mode == NM_802_11_MODE_MESH) {
+            mode = NM_SETTING_WIRELESS_MODE_MESH;
+            mesh = TRUE;
+        }
+        g_object_set(G_OBJECT(s_wifi), NM_SETTING_WIRELESS_MODE, mode, NULL);
+    }
+
+    /* For now mesh requires channel and band, fill them only if both not present.
+     * Do not check existing values against an existing ap/mesh point,
+     * mesh join will start a new network if required */
+    if (mesh) {
+        const char *band;
+        guint32     channel;
+        gboolean    band_valid = TRUE;
+        gboolean    chan_valid = TRUE;
+        gboolean    valid;
+
+        band    = nm_setting_wireless_get_band(s_wifi);
+        channel = nm_setting_wireless_get_channel(s_wifi);
+
+        valid = ((band == NULL) && (channel == 0)) || ((band != NULL) && (channel != 0));
+
+        if ((band == NULL) && (channel == 0)) {
+            channel = nm_utils_wifi_freq_to_channel(ap_freq);
+            if (channel) {
+                g_object_set(s_wifi, NM_SETTING_WIRELESS_CHANNEL, channel, NULL);
+            } else {
+                chan_valid = FALSE;
+            }
+
+            band = nm_utils_wifi_freq_to_band(ap_freq);
+            if (band) {
+                g_object_set(s_wifi, NM_SETTING_WIRELESS_BAND, band, NULL);
+            } else {
+                band_valid = FALSE;
+            }
+        }
+
+        if (!valid || !chan_valid || !band_valid) {
+            g_set_error(error,
+                        NM_CONNECTION_ERROR,
+                        NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                        _("connection does not match mesh point"));
+            g_prefix_error(error,
+                           "%s.%s: ",
+                           NM_SETTING_WIRELESS_SETTING_NAME,
+                           NM_SETTING_WIRELESS_MODE);
+            return FALSE;
+        }
+    }
+
+    /* Security */
+
+    /* Open */
+    if (!(ap_flags & NM_802_11_AP_FLAGS_PRIVACY) && (ap_wpa_flags == NM_802_11_AP_SEC_NONE)
+        && (ap_rsn_flags == NM_802_11_AP_SEC_NONE)) {
+        /* Make sure the connection doesn't specify security */
+        if (s_wsec || s_8021x) {
+            g_set_error_literal(error,
+                                NM_CONNECTION_ERROR,
+                                NM_CONNECTION_ERROR_INVALID_SETTING,
+                                _("Access point is unencrypted but setting specifies security"));
+            if (s_wsec)
+                g_prefix_error(error, "%s: ", NM_SETTING_WIRELESS_SECURITY_SETTING_NAME);
+            else
+                g_prefix_error(error, "%s: ", NM_SETTING_802_1X_SETTING_NAME);
+            return FALSE;
+        }
+        return TRUE;
+    }
+
+    /* Everything else requires security */
+    if (!s_wsec) {
+        s_wsec = (NMSettingWirelessSecurity *) nm_setting_wireless_security_new();
+        nm_connection_add_setting(connection, NM_SETTING(s_wsec));
+    }
+
+    key_mgmt      = nm_setting_wireless_security_get_key_mgmt(s_wsec);
+    auth_alg      = nm_setting_wireless_security_get_auth_alg(s_wsec);
+    leap_username = nm_setting_wireless_security_get_leap_username(s_wsec);
+
+    /* Ad-Hoc checks */
+    if (!verify_adhoc(s_wsec, s_8021x, adhoc, error))
+        return FALSE;
+
+    /* Static WEP, Dynamic WEP, or LEAP */
+    if ((ap_flags & NM_802_11_AP_FLAGS_PRIVACY) && (ap_wpa_flags == NM_802_11_AP_SEC_NONE)
+        && (ap_rsn_flags == NM_802_11_AP_SEC_NONE)) {
+        const char *tag            = "WEP";
+        gboolean    is_dynamic_wep = FALSE;
+
+        if (!verify_leap(s_wsec, s_8021x, adhoc, error))
+            return FALSE;
+
+        if (leap_username) {
+            tag = "LEAP";
+        } else {
+            /* Static or Dynamic WEP */
+            if (!verify_dynamic_wep(s_wsec, s_8021x, adhoc, error))
+                return FALSE;
+
+            if (s_8021x || (key_mgmt && !strcmp(key_mgmt, "ieee8021x"))) {
+                is_dynamic_wep = TRUE;
+                tag            = "Dynamic WEP";
+            }
+        }
+
+        /* Nothing WPA-related can be set */
+        if (!verify_no_wpa(s_wsec, tag, error))
+            return FALSE;
+
+        if (leap_username) {
+            /* LEAP */
+            g_object_set(s_wsec,
+                         NM_SETTING_WIRELESS_SECURITY_KEY_MGMT,
+                         "ieee8021x",
+                         NM_SETTING_WIRELESS_SECURITY_AUTH_ALG,
+                         "leap",
+                         NULL);
+        } else if (is_dynamic_wep) {
+            /* Dynamic WEP */
+            g_object_set(s_wsec,
+                         NM_SETTING_WIRELESS_SECURITY_KEY_MGMT,
+                         "ieee8021x",
+                         NM_SETTING_WIRELESS_SECURITY_AUTH_ALG,
+                         "open",
+                         NULL);
+
+            if (s_8021x) {
+                /* Dynamic WEP requires a valid 802.1x setting since we can't
+                 * autocomplete 802.1x.
+                 */
+                if (!nm_setting_verify(NM_SETTING(s_8021x), NULL, error))
+                    return FALSE;
+            }
+        } else {
+            /* Static WEP */
+            g_object_set(s_wsec, NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, "none", NULL);
+        }
+
+        return TRUE;
+    }
+
+    /* WPA/RSN */
+    g_assert(ap_wpa_flags || ap_rsn_flags);
+
+    /* Ensure key management is valid for WPA */
+    if ((key_mgmt && !strcmp(key_mgmt, "ieee8021x")) || leap_username) {
+        g_set_error_literal(
+            error,
+            NM_CONNECTION_ERROR,
+            NM_CONNECTION_ERROR_INVALID_PROPERTY,
+            _("WPA authentication is incompatible with non-EAP (original) LEAP or Dynamic WEP"));
+        g_prefix_error(error,
+                       "%s.%s: ",
+                       NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                       NM_SETTING_WIRELESS_SECURITY_KEY_MGMT);
+        return FALSE;
+    }
+
+    /* 'shared' auth incompatible with any type of WPA */
+    if (auth_alg && strcmp(auth_alg, "open")) {
+        g_set_error_literal(error,
+                            NM_CONNECTION_ERROR,
+                            NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                            _("WPA authentication is incompatible with Shared Key authentication"));
+        g_prefix_error(error,
+                       "%s.%s: ",
+                       NM_SETTING_WIRELESS_SECURITY_SETTING_NAME,
+                       NM_SETTING_WIRELESS_SECURITY_AUTH_ALG);
+        return FALSE;
+    }
+
+    if (!verify_no_wep(s_wsec, "WPA", error))
+        return FALSE;
+
+    if (!verify_wpa_psk(s_wsec, s_8021x, adhoc, ap_wpa_flags, ap_rsn_flags, error))
+        return FALSE;
+
+    if (!adhoc && !verify_wpa_eap(s_wsec, s_8021x, ap_wpa_flags, ap_rsn_flags, error))
+        return FALSE;
+
+    if (adhoc) {
+        g_object_set(s_wsec,
+                     NM_SETTING_WIRELESS_SECURITY_KEY_MGMT,
+                     "wpa-psk",
+                     NM_SETTING_WIRELESS_SECURITY_AUTH_ALG,
+                     "open",
+                     NULL);
+        nm_setting_wireless_security_add_proto(s_wsec, "rsn");
+        nm_setting_wireless_security_add_pairwise(s_wsec, "ccmp");
+        nm_setting_wireless_security_add_group(s_wsec, "ccmp");
+    } else if (s_8021x) {
+        g_object_set(s_wsec,
+                     NM_SETTING_WIRELESS_SECURITY_KEY_MGMT,
+                     "wpa-eap",
+                     NM_SETTING_WIRELESS_SECURITY_AUTH_ALG,
+                     "open",
+                     NULL);
+        /* Leave proto/pairwise/group as client set them; if they are unset the
+         * supplicant will figure out the best combination at connect time.
+         */
+
+        /* 802.1x also requires the client to completely fill in the 8021x
+         * setting.  Since there's so much configuration required for it, there's
+         * no way it can be automatically completed.
+         */
+    } else if ((key_mgmt && !strcmp(key_mgmt, "sae"))
+               || (ap_rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_SAE)) {
+        g_object_set(s_wsec,
+                     NM_SETTING_WIRELESS_SECURITY_KEY_MGMT,
+                     "sae",
+                     NM_SETTING_WIRELESS_SECURITY_AUTH_ALG,
+                     "open",
+                     NULL);
+    } else if ((key_mgmt && !strcmp(key_mgmt, "owe"))
+               || NM_FLAGS_ANY(ap_rsn_flags,
+                               NM_802_11_AP_SEC_KEY_MGMT_OWE | NM_802_11_AP_SEC_KEY_MGMT_OWE_TM)) {
+        g_object_set(s_wsec,
+                     NM_SETTING_WIRELESS_SECURITY_KEY_MGMT,
+                     "owe",
+                     NM_SETTING_WIRELESS_SECURITY_AUTH_ALG,
+                     "open",
+                     NULL);
+    } else if ((key_mgmt && !strcmp(key_mgmt, "wpa-psk"))
+               || (ap_wpa_flags & NM_802_11_AP_SEC_KEY_MGMT_PSK)
+               || (ap_rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_PSK)) {
+        g_object_set(s_wsec,
+                     NM_SETTING_WIRELESS_SECURITY_KEY_MGMT,
+                     "wpa-psk",
+                     NM_SETTING_WIRELESS_SECURITY_AUTH_ALG,
+                     "open",
+                     NULL);
+        /* Leave proto/pairwise/group as client set them; if they are unset the
+         * supplicant will figure out the best combination at connect time.
+         */
+    } else if ((key_mgmt && !strcmp(key_mgmt, "wpa-eap-suite-b-192"))
+               || (ap_rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_EAP_SUITE_B_192)) {
+        g_object_set(s_wsec,
+                     NM_SETTING_WIRELESS_SECURITY_KEY_MGMT,
+                     "wpa-eap-suite-b-192",
+                     NM_SETTING_WIRELESS_SECURITY_AUTH_ALG,
+                     "open",
+                     NULL);
+    } else {
+        g_set_error_literal(error,
+                            NM_CONNECTION_ERROR,
+                            NM_CONNECTION_ERROR_FAILED,
+                            _("Failed to determine AP security information"));
+        return FALSE;
+    }
+
+    return TRUE;
+}
+
+gboolean
+nm_wifi_utils_is_manf_default_ssid(GBytes *ssid)
+{
+    const guint8 *ssid_p;
+    gsize         ssid_l;
+    int           i;
+    /*
+     * List of manufacturer default SSIDs that are often unchanged by users.
+     *
+     * NOTE: this list should *not* contain networks that you would like to
+     * automatically roam to like "Starbucks" or "AT&T" or "T-Mobile HotSpot".
+     */
+    static const char *manf_defaults[] = {
+        "linksys",
+        "linksys-a",
+        "linksys-g",
+        "default",
+        "belkin54g",
+        "NETGEAR",
+        "o2DSL",
+        "WLAN",
+        "ALICE-WLAN",
+        "Speedport W 501V",
+        "TURBONETT",
+    };
+
+    ssid_p = g_bytes_get_data(ssid, &ssid_l);
+
+    for (i = 0; i < G_N_ELEMENTS(manf_defaults); i++) {
+        if (ssid_l == strlen(manf_defaults[i])) {
+            if (memcmp(manf_defaults[i], ssid_p, ssid_l) == 0)
+                return TRUE;
+        }
+    }
+    return FALSE;
+}
+
+/* To be used for connections where the SSID has been validated before */
+gboolean
+nm_wifi_connection_get_iwd_ssid_and_security(NMConnection *        connection,
+                                             char **               ssid,
+                                             NMIwdNetworkSecurity *security)
+{
+    NMSettingWireless *        s_wireless;
+    NMSettingWirelessSecurity *s_wireless_sec;
+    const char *               key_mgmt = NULL;
+
+    s_wireless = nm_connection_get_setting_wireless(connection);
+    if (!s_wireless)
+        return FALSE;
+
+    if (ssid) {
+        GBytes *    bytes = nm_setting_wireless_get_ssid(s_wireless);
+        gsize       ssid_len;
+        const char *ssid_str = (const char *) g_bytes_get_data(bytes, &ssid_len);
+
+        nm_assert(bytes && g_utf8_validate(ssid_str, ssid_len, NULL));
+        NM_SET_OUT(ssid, g_strndup(ssid_str, ssid_len));
+    }
+
+    if (!security)
+        return TRUE;
+
+    s_wireless_sec = nm_connection_get_setting_wireless_security(connection);
+    if (!s_wireless_sec) {
+        NM_SET_OUT(security, NM_IWD_NETWORK_SECURITY_OPEN);
+        return TRUE;
+    }
+
+    key_mgmt = nm_setting_wireless_security_get_key_mgmt(s_wireless_sec);
+    nm_assert(key_mgmt);
+
+    if (NM_IN_STRSET(key_mgmt, "none", "ieee8021x"))
+        NM_SET_OUT(security, NM_IWD_NETWORK_SECURITY_WEP);
+    else if (nm_streq(key_mgmt, "owe"))
+        NM_SET_OUT(security, NM_IWD_NETWORK_SECURITY_OPEN);
+    else if (NM_IN_STRSET(key_mgmt, "wpa-psk", "sae"))
+        NM_SET_OUT(security, NM_IWD_NETWORK_SECURITY_PSK);
+    else if (nm_streq(key_mgmt, "wpa-eap"))
+        NM_SET_OUT(security, NM_IWD_NETWORK_SECURITY_8021X);
+    else
+        return FALSE;
+
+    return TRUE;
+}
diff --git a/src/core/devices/wifi/nm-wifi-utils.h b/src/core/devices/wifi/nm-wifi-utils.h
new file mode 100644
index 00000000..474bea41
--- /dev/null
+++ b/src/core/devices/wifi/nm-wifi-utils.h
@@ -0,0 +1,39 @@
+/* SPDX-License-Identifier: LGPL-2.1-or-later */
+/*
+ * Copyright (C) 2011 Red Hat, Inc.
+ */
+
+#ifndef __NM_WIFI_UTILS_H__
+#define __NM_WIFI_UTILS_H__
+
+#include "nm-dbus-interface.h"
+#include "nm-connection.h"
+#include "nm-setting-wireless.h"
+#include "nm-setting-wireless-security.h"
+#include "nm-setting-8021x.h"
+
+typedef enum {
+    NM_IWD_NETWORK_SECURITY_OPEN,
+    NM_IWD_NETWORK_SECURITY_WEP,
+    NM_IWD_NETWORK_SECURITY_PSK,
+    NM_IWD_NETWORK_SECURITY_8021X,
+} NMIwdNetworkSecurity;
+
+gboolean nm_wifi_utils_complete_connection(GBytes *      ssid,
+                                           const char *  bssid,
+                                           NM80211Mode   mode,
+                                           guint32       ap_freq,
+                                           guint32       flags,
+                                           guint32       wpa_flags,
+                                           guint32       rsn_flags,
+                                           NMConnection *connection,
+                                           gboolean      lock_bssid,
+                                           GError **     error);
+
+gboolean nm_wifi_utils_is_manf_default_ssid(GBytes *ssid);
+
+gboolean nm_wifi_connection_get_iwd_ssid_and_security(NMConnection *        connection,
+                                                      char **               ssid,
+                                                      NMIwdNetworkSecurity *security);
+
+#endif /* __NM_WIFI_UTILS_H__ */
diff --git a/src/core/devices/wifi/tests/test-devices-wifi.c b/src/core/devices/wifi/tests/test-devices-wifi.c
new file mode 100644
index 00000000..bc0ba126
--- /dev/null
+++ b/src/core/devices/wifi/tests/test-devices-wifi.c
@@ -0,0 +1,1609 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+/*
+ * Copyright (C) 2011 Red Hat, Inc.
+ */
+
+#include "src/core/nm-default-daemon.h"
+
+#include "devices/wifi/nm-wifi-utils.h"
+#include "devices/wifi/nm-device-wifi.h"
+#include "nm-core-internal.h"
+
+#include "nm-test-utils-core.h"
+
+#define DEBUG 1
+
+/*****************************************************************************/
+
+#define COMPARE(src, expected, success, error, edomain, ecode)                             \
+    {                                                                                      \
+        if (expected) {                                                                    \
+            if (!success) {                                                                \
+                g_assert(error != NULL);                                                   \
+                g_warning("Failed to complete connection: %s", error->message);            \
+            }                                                                              \
+            g_assert(success == TRUE);                                                     \
+            g_assert(error == NULL);                                                       \
+                                                                                           \
+            success = nm_connection_compare(src, expected, NM_SETTING_COMPARE_FLAG_EXACT); \
+            if (success == FALSE && DEBUG) {                                               \
+                g_print("\n- COMPLETED ---------------------------------\n");              \
+                nm_connection_dump(src);                                                   \
+                g_print("+ EXPECTED ++++++++++++++++++++++++++++++++++++\n");              \
+                nm_connection_dump(expected);                                              \
+                g_print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n");              \
+            }                                                                              \
+            g_assert(success == TRUE);                                                     \
+        } else {                                                                           \
+            if (success) {                                                                 \
+                g_print("\n- COMPLETED ---------------------------------\n");              \
+                nm_connection_dump(src);                                                   \
+            }                                                                              \
+            g_assert(success == FALSE);                                                    \
+            g_assert_error(error, edomain, ecode);                                         \
+        }                                                                                  \
+                                                                                           \
+        g_clear_error(&error);                                                             \
+    }
+
+static gboolean
+complete_connection(const char *  ssid,
+                    const char *  bssid,
+                    NM80211Mode   mode,
+                    guint32       flags,
+                    guint32       wpa_flags,
+                    guint32       rsn_flags,
+                    gboolean      lock_bssid,
+                    NMConnection *src,
+                    GError **     error)
+{
+    gs_unref_bytes GBytes *ssid_b = NULL;
+    NMSettingWireless *    s_wifi;
+
+    /* Add a wifi setting if one doesn't exist */
+    s_wifi = nm_connection_get_setting_wireless(src);
+    if (!s_wifi) {
+        s_wifi = (NMSettingWireless *) nm_setting_wireless_new();
+        nm_connection_add_setting(src, NM_SETTING(s_wifi));
+    }
+
+    ssid_b = g_bytes_new(ssid, strlen(ssid));
+
+    return nm_wifi_utils_complete_connection(ssid_b,
+                                             bssid,
+                                             mode,
+                                             0,
+                                             flags,
+                                             wpa_flags,
+                                             rsn_flags,
+                                             src,
+                                             lock_bssid,
+                                             error);
+}
+
+typedef struct {
+    const char *key;
+    const char *str;
+    guint32     uint;
+} KeyData;
+
+static void
+set_items(NMSetting *setting, const KeyData *items)
+{
+    const KeyData *item;
+    GParamSpec *   pspec;
+    GBytes *       tmp;
+
+    for (item = items; item && item->key; item++) {
+        g_assert(item->key);
+        pspec = g_object_class_find_property(G_OBJECT_GET_CLASS(setting), item->key);
+        g_assert(pspec);
+
+        if (pspec->value_type == G_TYPE_STRING) {
+            g_assert(item->uint == 0);
+            if (item->str)
+                g_object_set(G_OBJECT(setting), item->key, item->str, NULL);
+        } else if (pspec->value_type == G_TYPE_UINT) {
+            g_assert(item->str == NULL);
+            g_object_set(G_OBJECT(setting), item->key, item->uint, NULL);
+        } else if (pspec->value_type == G_TYPE_INT) {
+            int foo = (int) item->uint;
+
+            g_assert(item->str == NULL);
+            g_object_set(G_OBJECT(setting), item->key, foo, NULL);
+        } else if (pspec->value_type == G_TYPE_BOOLEAN) {
+            gboolean foo = !!(item->uint);
+
+            g_assert(item->str == NULL);
+            g_object_set(G_OBJECT(setting), item->key, foo, NULL);
+        } else if (pspec->value_type == G_TYPE_BYTES) {
+            g_assert(item->str);
+            tmp = g_bytes_new(item->str, strlen(item->str));
+            g_object_set(G_OBJECT(setting), item->key, tmp, NULL);
+            g_bytes_unref(tmp);
+        } else {
+            /* Special types, check based on property name */
+            if (!strcmp(item->key, NM_SETTING_WIRELESS_SECURITY_PROTO))
+                nm_setting_wireless_security_add_proto(NM_SETTING_WIRELESS_SECURITY(setting),
+                                                       item->str);
+            else if (!strcmp(item->key, NM_SETTING_WIRELESS_SECURITY_PAIRWISE))
+                nm_setting_wireless_security_add_pairwise(NM_SETTING_WIRELESS_SECURITY(setting),
+                                                          item->str);
+            else if (!strcmp(item->key, NM_SETTING_WIRELESS_SECURITY_GROUP))
+                nm_setting_wireless_security_add_group(NM_SETTING_WIRELESS_SECURITY(setting),
+                                                       item->str);
+            else if (!strcmp(item->key, NM_SETTING_802_1X_EAP))
+                nm_setting_802_1x_add_eap_method(NM_SETTING_802_1X(setting), item->str);
+        }
+    }
+}
+
+static NMSettingWireless *
+fill_wifi_empty(NMConnection *connection)
+{
+    NMSettingWireless *s_wifi;
+
+    s_wifi = nm_connection_get_setting_wireless(connection);
+    if (!s_wifi) {
+        s_wifi = (NMSettingWireless *) nm_setting_wireless_new();
+        nm_connection_add_setting(connection, NM_SETTING(s_wifi));
+    }
+    return s_wifi;
+}
+
+static NMSettingWireless *
+fill_wifi(NMConnection *connection, const KeyData items[])
+{
+    NMSettingWireless *s_wifi;
+
+    s_wifi = nm_connection_get_setting_wireless(connection);
+    if (!s_wifi) {
+        s_wifi = (NMSettingWireless *) nm_setting_wireless_new();
+        nm_connection_add_setting(connection, NM_SETTING(s_wifi));
+    }
+
+    set_items(NM_SETTING(s_wifi), items);
+    return s_wifi;
+}
+
+static NMSettingWirelessSecurity *
+fill_wsec(NMConnection *connection, const KeyData items[])
+{
+    NMSettingWirelessSecurity *s_wsec;
+
+    s_wsec = nm_connection_get_setting_wireless_security(connection);
+    if (!s_wsec) {
+        s_wsec = (NMSettingWirelessSecurity *) nm_setting_wireless_security_new();
+        nm_connection_add_setting(connection, NM_SETTING(s_wsec));
+    }
+
+    set_items(NM_SETTING(s_wsec), items);
+    return s_wsec;
+}
+
+static NMSetting8021x *
+fill_8021x(NMConnection *connection, const KeyData items[])
+{
+    NMSetting8021x *s_8021x;
+
+    s_8021x = nm_connection_get_setting_802_1x(connection);
+    if (!s_8021x) {
+        s_8021x = (NMSetting8021x *) nm_setting_802_1x_new();
+        nm_connection_add_setting(connection, NM_SETTING(s_8021x));
+    }
+
+    set_items(NM_SETTING(s_8021x), items);
+    return s_8021x;
+}
+
+static NMConnection *
+create_basic(const char *ssid, const char *bssid, NM80211Mode mode)
+{
+    NMConnection *     connection;
+    NMSettingWireless *s_wifi = NULL;
+    GBytes *           tmp;
+
+    connection = nm_simple_connection_new();
+
+    s_wifi = (NMSettingWireless *) nm_setting_wireless_new();
+    nm_connection_add_setting(connection, NM_SETTING(s_wifi));
+
+    /* SSID */
+    tmp = g_bytes_new(ssid, strlen(ssid));
+    g_object_set(G_OBJECT(s_wifi), NM_SETTING_WIRELESS_SSID, tmp, NULL);
+    g_bytes_unref(tmp);
+
+    /* BSSID */
+    if (bssid)
+        g_object_set(G_OBJECT(s_wifi), NM_SETTING_WIRELESS_BSSID, bssid, NULL);
+
+    if (mode == NM_802_11_MODE_INFRA)
+        g_object_set(G_OBJECT(s_wifi), NM_SETTING_WIRELESS_MODE, "infrastructure", NULL);
+    else if (mode == NM_802_11_MODE_ADHOC)
+        g_object_set(G_OBJECT(s_wifi), NM_SETTING_WIRELESS_MODE, "adhoc", NULL);
+    else
+        g_assert_not_reached();
+
+    return connection;
+}
+
+/*****************************************************************************/
+
+static void
+test_lock_bssid(void)
+{
+    NMConnection *src, *expected;
+    const char *  bssid = "01:02:03:04:05:06";
+    const char *  ssid  = "blahblah";
+    gboolean      success;
+    GError *      error = NULL;
+
+    src      = nm_simple_connection_new();
+    success  = complete_connection(ssid,
+                                  bssid,
+                                  NM_802_11_MODE_INFRA,
+                                  NM_802_11_AP_FLAGS_NONE,
+                                  NM_802_11_AP_SEC_NONE,
+                                  NM_802_11_AP_SEC_NONE,
+                                  TRUE,
+                                  src,
+                                  &error);
+    expected = create_basic(ssid, bssid, NM_802_11_MODE_INFRA);
+    COMPARE(src, expected, success, error, 0, 0);
+
+    g_object_unref(src);
+    g_object_unref(expected);
+}
+
+/*****************************************************************************/
+
+static void
+test_open_ap_empty_connection(void)
+{
+    NMConnection *src, *expected;
+    const char *  bssid = "01:02:03:04:05:06";
+    const char *  ssid  = "blahblah";
+    gboolean      success;
+    GError *      error = NULL;
+
+    /* Test that an empty source connection is correctly filled with the
+     * SSID and Infra modes of the given AP details.
+     */
+
+    src      = nm_simple_connection_new();
+    success  = complete_connection(ssid,
+                                  bssid,
+                                  NM_802_11_MODE_INFRA,
+                                  NM_802_11_AP_FLAGS_NONE,
+                                  NM_802_11_AP_SEC_NONE,
+                                  NM_802_11_AP_SEC_NONE,
+                                  FALSE,
+                                  src,
+                                  &error);
+    expected = create_basic(ssid, NULL, NM_802_11_MODE_INFRA);
+    COMPARE(src, expected, success, error, 0, 0);
+
+    g_object_unref(src);
+    g_object_unref(expected);
+}
+
+/*****************************************************************************/
+
+static void
+test_open_ap_leap_connection_1(gconstpointer add_wifi)
+{
+    NMConnection *src;
+    const char *  bssid      = "01:02:03:04:05:06";
+    const KeyData src_wsec[] = {{NM_SETTING_WIRELESS_SECURITY_LEAP_USERNAME, "Bill Smith", 0},
+                                {NULL}};
+    gboolean      success;
+    GError *      error = NULL;
+
+    /* Test that a basic connection filled with a LEAP username is
+     * rejected when completion is attempted with an open AP.  LEAP requires
+     * the AP to have the Privacy bit set.
+     */
+
+    src = nm_simple_connection_new();
+    if (add_wifi)
+        fill_wifi_empty(src);
+    fill_wsec(src, src_wsec);
+
+    success = complete_connection("blahblah",
+                                  bssid,
+                                  NM_802_11_MODE_INFRA,
+                                  NM_802_11_AP_FLAGS_NONE,
+                                  NM_802_11_AP_SEC_NONE,
+                                  NM_802_11_AP_SEC_NONE,
+                                  FALSE,
+                                  src,
+                                  &error);
+    /* We expect failure */
+    COMPARE(src, NULL, success, error, NM_CONNECTION_ERROR, NM_CONNECTION_ERROR_INVALID_SETTING);
+
+    g_object_unref(src);
+}
+
+/*****************************************************************************/
+
+static void
+test_open_ap_leap_connection_2(void)
+{
+    NMConnection *src;
+    const char *  bssid      = "01:02:03:04:05:06";
+    const KeyData src_wsec[] = {{NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, "ieee8021x", 0}, {NULL}};
+    gboolean      success;
+    GError *      error = NULL;
+
+    /* Test that a basic connection specifying IEEE8021x security (ie, Dynamic
+     * WEP or LEAP) is rejected when completion is attempted with an open AP.
+     */
+
+    src = nm_simple_connection_new();
+    fill_wifi_empty(src);
+    fill_wsec(src, src_wsec);
+
+    success = complete_connection("blahblah",
+                                  bssid,
+                                  NM_802_11_MODE_INFRA,
+                                  NM_802_11_AP_FLAGS_NONE,
+                                  NM_802_11_AP_SEC_NONE,
+                                  NM_802_11_AP_SEC_NONE,
+                                  FALSE,
+                                  src,
+                                  &error);
+    /* We expect failure */
+    COMPARE(src, NULL, success, error, NM_CONNECTION_ERROR, NM_CONNECTION_ERROR_INVALID_SETTING);
+
+    g_object_unref(src);
+}
+
+/*****************************************************************************/
+
+static void
+test_open_ap_wep_connection(gconstpointer add_wifi)
+{
+    NMConnection *src;
+    const char *  bssid      = "01:02:03:04:05:06";
+    const KeyData src_wsec[] = {
+        {NM_SETTING_WIRELESS_SECURITY_WEP_KEY0, "11111111111111111111111111", 0},
+        {NM_SETTING_WIRELESS_SECURITY_WEP_TX_KEYIDX, NULL, 0},
+        {NM_SETTING_WIRELESS_SECURITY_AUTH_ALG, "open", 0},
+        {NULL}};
+    gboolean success;
+    GError * error = NULL;
+
+    /* Test that a static WEP connection is rejected when completion is
+     * attempted with an open AP.
+     */
+
+    src = nm_simple_connection_new();
+    if (add_wifi)
+        fill_wifi_empty(src);
+    fill_wsec(src, src_wsec);
+    success = complete_connection("blahblah",
+                                  bssid,
+                                  NM_802_11_MODE_INFRA,
+                                  NM_802_11_AP_FLAGS_NONE,
+                                  NM_802_11_AP_SEC_NONE,
+                                  NM_802_11_AP_SEC_NONE,
+                                  FALSE,
+                                  src,
+                                  &error);
+    /* We expect failure */
+    COMPARE(src, NULL, success, error, NM_CONNECTION_ERROR, NM_CONNECTION_ERROR_INVALID_SETTING);
+
+    g_object_unref(src);
+}
+
+/*****************************************************************************/
+
+static void
+test_ap_wpa_psk_connection_base(const char *  key_mgmt,
+                                const char *  auth_alg,
+                                guint32       flags,
+                                guint32       wpa_flags,
+                                guint32       rsn_flags,
+                                gboolean      add_wifi,
+                                guint         error_code,
+                                NMConnection *expected)
+{
+    NMConnection *src;
+    const char *  ssid        = "blahblah";
+    const char *  bssid       = "01:02:03:04:05:06";
+    const KeyData exp_wifi[]  = {{NM_SETTING_WIRELESS_SSID, ssid, 0},
+                                {NM_SETTING_WIRELESS_MODE, "infrastructure", 0},
+                                {NULL}};
+    const KeyData both_wsec[] = {{NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, key_mgmt, 0},
+                                 {NM_SETTING_WIRELESS_SECURITY_AUTH_ALG, auth_alg, 0},
+                                 {NM_SETTING_WIRELESS_SECURITY_PSK, "asdfasdfasdfasdfasdfafs", 0},
+                                 {NULL}};
+    gboolean      success;
+    GError *      error = NULL;
+
+    src = nm_simple_connection_new();
+    if (add_wifi)
+        fill_wifi_empty(src);
+    fill_wsec(src, both_wsec);
+    success = complete_connection(ssid,
+                                  bssid,
+                                  NM_802_11_MODE_INFRA,
+                                  flags,
+                                  wpa_flags,
+                                  rsn_flags,
+                                  FALSE,
+                                  src,
+                                  &error);
+    if (expected) {
+        fill_wifi(expected, exp_wifi);
+        fill_wsec(expected, both_wsec);
+    }
+    COMPARE(src, expected, success, error, NM_CONNECTION_ERROR, error_code);
+
+    g_object_unref(src);
+}
+
+static void
+test_open_ap_wpa_psk_connection_1(void)
+{
+    /* Test that a WPA-PSK connection filling only the PSK itself and *not*
+     * filling the wifi setting is rejected when completion is attempted with
+     * an open AP.
+     */
+    test_ap_wpa_psk_connection_base(NULL,
+                                    NULL,
+                                    NM_802_11_AP_FLAGS_NONE,
+                                    NM_802_11_AP_SEC_NONE,
+                                    NM_802_11_AP_SEC_NONE,
+                                    FALSE,
+                                    NM_CONNECTION_ERROR_INVALID_SETTING,
+                                    NULL);
+}
+
+static void
+test_open_ap_wpa_psk_connection_2(void)
+{
+    /* Test that a WPA-PSK connection filling only the PSK itself and also
+     * filling the wifi setting is rejected when completion is attempted with
+     * an open AP.
+     */
+    test_ap_wpa_psk_connection_base(NULL,
+                                    NULL,
+                                    NM_802_11_AP_FLAGS_NONE,
+                                    NM_802_11_AP_SEC_NONE,
+                                    NM_802_11_AP_SEC_NONE,
+                                    TRUE,
+                                    NM_CONNECTION_ERROR_INVALID_SETTING,
+                                    NULL);
+}
+
+static void
+test_open_ap_wpa_psk_connection_3(void)
+{
+    /* Test that a WPA-PSK connection filling the PSK and setting the auth alg
+     * to 'open' is rejected when completion is attempted with an open AP.
+     */
+    test_ap_wpa_psk_connection_base(NULL,
+                                    "open",
+                                    NM_802_11_AP_FLAGS_NONE,
+                                    NM_802_11_AP_SEC_NONE,
+                                    NM_802_11_AP_SEC_NONE,
+                                    FALSE,
+                                    NM_CONNECTION_ERROR_INVALID_SETTING,
+                                    NULL);
+}
+
+static void
+test_open_ap_wpa_psk_connection_4(void)
+{
+    /* Test that a WPA-PSK connection filling the PSK and setting the auth alg
+     * to 'shared' is rejected when completion is attempted with an open AP.
+     * Shared auth cannot be used with WPA.
+     */
+    test_ap_wpa_psk_connection_base(NULL,
+                                    "shared",
+                                    NM_802_11_AP_FLAGS_NONE,
+                                    NM_802_11_AP_SEC_NONE,
+                                    NM_802_11_AP_SEC_NONE,
+                                    FALSE,
+                                    NM_CONNECTION_ERROR_INVALID_SETTING,
+                                    NULL);
+}
+
+static void
+test_open_ap_wpa_psk_connection_5(void)
+{
+    /* Test that a WPA-PSK connection filling the PSK, the auth algorithm, and
+     * key management is rejected when completion is attempted with an open AP.
+     */
+    test_ap_wpa_psk_connection_base("wpa-psk",
+                                    "open",
+                                    NM_802_11_AP_FLAGS_NONE,
+                                    NM_802_11_AP_SEC_NONE,
+                                    NM_802_11_AP_SEC_NONE,
+                                    FALSE,
+                                    NM_CONNECTION_ERROR_INVALID_SETTING,
+                                    NULL);
+}
+
+/*****************************************************************************/
+
+static void
+test_ap_wpa_eap_connection_base(const char *key_mgmt,
+                                const char *auth_alg,
+                                guint32     flags,
+                                guint32     wpa_flags,
+                                guint32     rsn_flags,
+                                gboolean    add_wifi,
+                                guint       error_code)
+{
+    NMConnection *src;
+    const char *  bssid       = "01:02:03:04:05:06";
+    const KeyData src_empty[] = {{NULL}};
+    const KeyData src_wsec[]  = {{NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, key_mgmt, 0},
+                                {NM_SETTING_WIRELESS_SECURITY_AUTH_ALG, auth_alg, 0},
+                                {NULL}};
+    gboolean      success;
+    GError *      error = NULL;
+
+    src = nm_simple_connection_new();
+    if (add_wifi)
+        fill_wifi_empty(src);
+    fill_wsec(src, src_wsec);
+    fill_8021x(src, src_empty);
+    success = complete_connection("blahblah",
+                                  bssid,
+                                  NM_802_11_MODE_INFRA,
+                                  flags,
+                                  wpa_flags,
+                                  rsn_flags,
+                                  FALSE,
+                                  src,
+                                  &error);
+    /* Failure expected */
+    COMPARE(src, NULL, success, error, NM_CONNECTION_ERROR, error_code);
+
+    g_object_unref(src);
+}
+
+enum {
+    IDX_NONE = 0,
+    IDX_OPEN,
+    IDX_PRIV,
+    IDX_WPA_PSK_PTKIP_GTKIP,
+    IDX_WPA_PSK_PTKIP_PCCMP_GTKIP,
+    IDX_WPA_RSN_PSK_PTKIP_PCCMP_GTKIP,
+    IDX_WPA_RSN_PSK_PCCMP_GCCMP,
+    IDX_RSN_PSK_PCCMP_GCCMP,
+    IDX_RSN_PSK_PTKIP_PCCMP_GTKIP,
+    IDX_WPA_8021X,
+    IDX_RSN_8021X,
+};
+
+static guint32
+flags_for_idx(guint32 idx)
+{
+    if (idx == IDX_OPEN)
+        return NM_802_11_AP_FLAGS_NONE;
+    else if (idx == IDX_PRIV || idx == IDX_WPA_PSK_PTKIP_GTKIP
+             || idx == IDX_WPA_PSK_PTKIP_PCCMP_GTKIP || idx == IDX_RSN_PSK_PCCMP_GCCMP
+             || idx == IDX_RSN_PSK_PTKIP_PCCMP_GTKIP || idx == IDX_WPA_RSN_PSK_PTKIP_PCCMP_GTKIP
+             || idx == IDX_WPA_RSN_PSK_PCCMP_GCCMP || idx == IDX_WPA_8021X || idx == IDX_RSN_8021X)
+        return NM_802_11_AP_FLAGS_PRIVACY;
+    else
+        g_assert_not_reached();
+}
+
+static guint32
+wpa_flags_for_idx(guint32 idx)
+{
+    if (idx == IDX_OPEN || idx == IDX_PRIV || idx == IDX_RSN_8021X || idx == IDX_RSN_PSK_PCCMP_GCCMP
+        || idx == IDX_RSN_PSK_PTKIP_PCCMP_GTKIP)
+        return NM_802_11_AP_SEC_NONE;
+    else if (idx == IDX_WPA_PSK_PTKIP_GTKIP)
+        return NM_802_11_AP_SEC_PAIR_TKIP | NM_802_11_AP_SEC_GROUP_TKIP
+               | NM_802_11_AP_SEC_KEY_MGMT_PSK;
+    else if (idx == IDX_WPA_RSN_PSK_PTKIP_PCCMP_GTKIP)
+        return NM_802_11_AP_SEC_PAIR_TKIP | NM_802_11_AP_SEC_PAIR_CCMP | NM_802_11_AP_SEC_GROUP_TKIP
+               | NM_802_11_AP_SEC_KEY_MGMT_PSK;
+    else if (NM_IN_SET(idx, IDX_WPA_PSK_PTKIP_PCCMP_GTKIP, IDX_WPA_RSN_PSK_PCCMP_GCCMP))
+        return NM_802_11_AP_SEC_PAIR_CCMP | NM_802_11_AP_SEC_GROUP_CCMP
+               | NM_802_11_AP_SEC_KEY_MGMT_PSK;
+    else if (idx == IDX_WPA_8021X)
+        return NM_802_11_AP_SEC_PAIR_TKIP | NM_802_11_AP_SEC_GROUP_TKIP
+               | NM_802_11_AP_SEC_KEY_MGMT_802_1X;
+    else
+        g_assert_not_reached();
+}
+
+static guint32
+rsn_flags_for_idx(guint32 idx)
+{
+    if (idx == IDX_OPEN || idx == IDX_PRIV || idx == IDX_WPA_8021X || idx == IDX_WPA_PSK_PTKIP_GTKIP
+        || idx == IDX_WPA_PSK_PTKIP_PCCMP_GTKIP)
+        return NM_802_11_AP_SEC_NONE;
+    else if (idx == IDX_RSN_PSK_PCCMP_GCCMP)
+        return NM_802_11_AP_SEC_PAIR_CCMP | NM_802_11_AP_SEC_GROUP_CCMP
+               | NM_802_11_AP_SEC_KEY_MGMT_PSK;
+    else if (idx == IDX_RSN_PSK_PTKIP_PCCMP_GTKIP)
+        return NM_802_11_AP_SEC_PAIR_TKIP | NM_802_11_AP_SEC_PAIR_CCMP | NM_802_11_AP_SEC_GROUP_TKIP
+               | NM_802_11_AP_SEC_KEY_MGMT_PSK;
+    else if (idx == IDX_WPA_RSN_PSK_PTKIP_PCCMP_GTKIP)
+        return NM_802_11_AP_SEC_PAIR_TKIP | NM_802_11_AP_SEC_PAIR_CCMP | NM_802_11_AP_SEC_GROUP_TKIP
+               | NM_802_11_AP_SEC_KEY_MGMT_PSK;
+    else if (idx == IDX_WPA_RSN_PSK_PCCMP_GCCMP)
+        return NM_802_11_AP_SEC_PAIR_CCMP | NM_802_11_AP_SEC_GROUP_CCMP
+               | NM_802_11_AP_SEC_KEY_MGMT_PSK;
+    else if (idx == IDX_RSN_8021X)
+        return NM_802_11_AP_SEC_PAIR_CCMP | NM_802_11_AP_SEC_GROUP_CCMP
+               | NM_802_11_AP_SEC_KEY_MGMT_802_1X;
+    else
+        g_assert_not_reached();
+}
+
+static guint32
+error_code_for_idx(guint32 idx, guint num)
+{
+    if (idx == IDX_OPEN)
+        return NM_CONNECTION_ERROR_INVALID_SETTING;
+    else if (idx == IDX_PRIV) {
+        if (num <= 3)
+            return NM_CONNECTION_ERROR_MISSING_PROPERTY;
+        else
+            return NM_CONNECTION_ERROR_INVALID_PROPERTY;
+    } else if (idx == IDX_WPA_PSK_PTKIP_GTKIP || idx == IDX_WPA_PSK_PTKIP_PCCMP_GTKIP
+               || idx == IDX_WPA_RSN_PSK_PCCMP_GCCMP || idx == IDX_WPA_RSN_PSK_PTKIP_PCCMP_GTKIP
+               || idx == IDX_RSN_PSK_PTKIP_PCCMP_GTKIP || idx == IDX_RSN_PSK_PCCMP_GCCMP)
+        if (num == 4)
+            return NM_CONNECTION_ERROR_INVALID_PROPERTY;
+        else
+            return NM_CONNECTION_ERROR_INVALID_SETTING;
+    else
+        g_assert_not_reached();
+}
+
+static void
+test_ap_wpa_eap_connection_1(gconstpointer data)
+{
+    guint idx = GPOINTER_TO_UINT(data);
+
+    test_ap_wpa_eap_connection_base(NULL,
+                                    NULL,
+                                    flags_for_idx(idx),
+                                    wpa_flags_for_idx(idx),
+                                    rsn_flags_for_idx(idx),
+                                    FALSE,
+                                    error_code_for_idx(idx, 1));
+}
+
+static void
+test_ap_wpa_eap_connection_2(gconstpointer data)
+{
+    guint idx = GPOINTER_TO_UINT(data);
+
+    test_ap_wpa_eap_connection_base(NULL,
+                                    NULL,
+                                    flags_for_idx(idx),
+                                    wpa_flags_for_idx(idx),
+                                    rsn_flags_for_idx(idx),
+                                    TRUE,
+                                    error_code_for_idx(idx, 2));
+}
+
+static void
+test_ap_wpa_eap_connection_3(gconstpointer data)
+{
+    guint idx = GPOINTER_TO_UINT(data);
+
+    test_ap_wpa_eap_connection_base(NULL,
+                                    "open",
+                                    flags_for_idx(idx),
+                                    wpa_flags_for_idx(idx),
+                                    rsn_flags_for_idx(idx),
+                                    FALSE,
+                                    error_code_for_idx(idx, 3));
+}
+
+static void
+test_ap_wpa_eap_connection_4(gconstpointer data)
+{
+    guint idx = GPOINTER_TO_UINT(data);
+
+    test_ap_wpa_eap_connection_base(NULL,
+                                    "shared",
+                                    flags_for_idx(idx),
+                                    wpa_flags_for_idx(idx),
+                                    rsn_flags_for_idx(idx),
+                                    FALSE,
+                                    error_code_for_idx(idx, 4));
+}
+
+static void
+test_ap_wpa_eap_connection_5(gconstpointer data)
+{
+    guint idx = GPOINTER_TO_UINT(data);
+
+    test_ap_wpa_eap_connection_base("wpa-eap",
+                                    "open",
+                                    flags_for_idx(idx),
+                                    wpa_flags_for_idx(idx),
+                                    rsn_flags_for_idx(idx),
+                                    FALSE,
+                                    error_code_for_idx(idx, 5));
+}
+
+/*****************************************************************************/
+
+static void
+test_priv_ap_empty_connection(void)
+{
+    NMConnection *src, *expected;
+    const char *  bssid      = "01:02:03:04:05:06";
+    const char *  ssid       = "blahblah";
+    const KeyData exp_wsec[] = {{NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, "none", 0}, {NULL}};
+    gboolean      success;
+    GError *      error = NULL;
+
+    /* Test that an empty connection is completed to a valid Static WEP
+     * connection when completed with an AP with the Privacy bit set.
+     */
+
+    src     = nm_simple_connection_new();
+    success = complete_connection(ssid,
+                                  bssid,
+                                  NM_802_11_MODE_INFRA,
+                                  NM_802_11_AP_FLAGS_PRIVACY,
+                                  NM_802_11_AP_SEC_NONE,
+                                  NM_802_11_AP_SEC_NONE,
+                                  FALSE,
+                                  src,
+                                  &error);
+
+    /* Static WEP connection expected */
+    expected = create_basic(ssid, NULL, NM_802_11_MODE_INFRA);
+    fill_wsec(expected, exp_wsec);
+    COMPARE(src, expected, success, error, 0, 0);
+
+    g_object_unref(src);
+    g_object_unref(expected);
+}
+
+/*****************************************************************************/
+
+static void
+test_priv_ap_leap_connection_1(gconstpointer add_wifi)
+{
+    NMConnection *src, *expected;
+    const char *  ssid          = "blahblah";
+    const char *  bssid         = "01:02:03:04:05:06";
+    const char *  leap_username = "Bill Smith";
+    const KeyData src_wsec[]    = {{NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, "ieee8021x", 0},
+                                {NM_SETTING_WIRELESS_SECURITY_LEAP_USERNAME, leap_username, 0},
+                                {NULL}};
+    const KeyData exp_wsec[]    = {{NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, "ieee8021x", 0},
+                                {NM_SETTING_WIRELESS_SECURITY_AUTH_ALG, "leap", 0},
+                                {NM_SETTING_WIRELESS_SECURITY_LEAP_USERNAME, leap_username, 0},
+                                {NULL}};
+    gboolean      success;
+    GError *      error = NULL;
+
+    /* Test that an minimal LEAP connection specifying only key management and
+     * the LEAP username is completed to a full LEAP connection when completed
+     * with an AP with the Privacy bit set.
+     */
+
+    src = nm_simple_connection_new();
+    if (add_wifi)
+        fill_wifi_empty(src);
+    fill_wsec(src, src_wsec);
+    success = complete_connection(ssid,
+                                  bssid,
+                                  NM_802_11_MODE_INFRA,
+                                  NM_802_11_AP_FLAGS_PRIVACY,
+                                  NM_802_11_AP_SEC_NONE,
+                                  NM_802_11_AP_SEC_NONE,
+                                  FALSE,
+                                  src,
+                                  &error);
+    /* We expect success here; since LEAP APs just set the 'privacy' flag
+     * there's no way to determine from the AP's beacon whether it's static WEP,
+     * dynamic WEP, or LEAP.
+     */
+    expected = create_basic(ssid, NULL, NM_802_11_MODE_INFRA);
+    fill_wsec(expected, exp_wsec);
+    COMPARE(src, expected, success, error, 0, 0);
+
+    g_object_unref(src);
+    g_object_unref(expected);
+}
+
+/*****************************************************************************/
+
+static void
+test_priv_ap_leap_connection_2(void)
+{
+    NMConnection *src;
+    const char *  bssid      = "01:02:03:04:05:06";
+    const KeyData src_wsec[] = {{NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, "ieee8021x", 0},
+                                {NM_SETTING_WIRELESS_SECURITY_AUTH_ALG, "leap", 0},
+                                {NULL}};
+    gboolean      success;
+    GError *      error = NULL;
+
+    /* Test that an minimal LEAP connection specifying only key management and
+     * the LEAP auth alg is completed to a full LEAP connection when completed
+     * with an AP with the Privacy bit set.
+     */
+
+    src = nm_simple_connection_new();
+    fill_wifi_empty(src);
+    fill_wsec(src, src_wsec);
+    success = complete_connection("blahblah",
+                                  bssid,
+                                  NM_802_11_MODE_INFRA,
+                                  NM_802_11_AP_FLAGS_PRIVACY,
+                                  NM_802_11_AP_SEC_NONE,
+                                  NM_802_11_AP_SEC_NONE,
+                                  FALSE,
+                                  src,
+                                  &error);
+    /* We expect failure here, we need a LEAP username */
+    COMPARE(src, NULL, success, error, NM_CONNECTION_ERROR, NM_CONNECTION_ERROR_MISSING_PROPERTY);
+
+    g_object_unref(src);
+}
+
+/*****************************************************************************/
+
+static void
+test_priv_ap_dynamic_wep_1(void)
+{
+    NMConnection *src, *expected;
+    const char *  ssid         = "blahblah";
+    const char *  bssid        = "01:02:03:04:05:06";
+    const KeyData src_wsec[]   = {{NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, "ieee8021x", 0},
+                                {NM_SETTING_WIRELESS_SECURITY_AUTH_ALG, "open", 0},
+                                {NULL}};
+    const KeyData both_8021x[] = {{NM_SETTING_802_1X_EAP, "peap", 0},
+                                  {NM_SETTING_802_1X_IDENTITY, "Bill Smith", 0},
+                                  {NM_SETTING_802_1X_PHASE2_AUTH, "mschapv2", 0},
+                                  {NULL}};
+    const KeyData exp_wsec[]   = {{NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, "ieee8021x", 0},
+                                {NM_SETTING_WIRELESS_SECURITY_AUTH_ALG, "open", 0},
+                                {NULL}};
+    gboolean      success;
+    GError *      error = NULL;
+
+    /* Test that an minimal Dynamic WEP connection specifying key management,
+     * the auth algorithm, and valid 802.1x setting is completed to a valid
+     * Dynamic WEP connection when completed with an AP with the Privacy bit set.
+     */
+
+    src = nm_simple_connection_new();
+    fill_wifi_empty(src);
+    fill_wsec(src, src_wsec);
+    fill_8021x(src, both_8021x);
+    success = complete_connection(ssid,
+                                  bssid,
+                                  NM_802_11_MODE_INFRA,
+                                  NM_802_11_AP_FLAGS_PRIVACY,
+                                  NM_802_11_AP_SEC_NONE,
+                                  NM_802_11_AP_SEC_NONE,
+                                  FALSE,
+                                  src,
+                                  &error);
+
+    /* We expect a completed Dynamic WEP connection */
+    expected = create_basic(ssid, NULL, NM_802_11_MODE_INFRA);
+    fill_wsec(expected, exp_wsec);
+    fill_8021x(expected, both_8021x);
+    COMPARE(src, expected, success, error, 0, 0);
+
+    g_object_unref(src);
+    g_object_unref(expected);
+}
+
+/*****************************************************************************/
+
+static void
+test_priv_ap_dynamic_wep_2(void)
+{
+    NMConnection *src, *expected;
+    const char *  ssid         = "blahblah";
+    const char *  bssid        = "01:02:03:04:05:06";
+    const KeyData src_wsec[]   = {{NM_SETTING_WIRELESS_SECURITY_AUTH_ALG, "open", 0}, {NULL}};
+    const KeyData both_8021x[] = {{NM_SETTING_802_1X_EAP, "peap", 0},
+                                  {NM_SETTING_802_1X_IDENTITY, "Bill Smith", 0},
+                                  {NM_SETTING_802_1X_PHASE2_AUTH, "mschapv2", 0},
+                                  {NULL}};
+    const KeyData exp_wsec[]   = {{NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, "ieee8021x", 0},
+                                {NM_SETTING_WIRELESS_SECURITY_AUTH_ALG, "open", 0},
+                                {NULL}};
+    gboolean      success;
+    GError *      error = NULL;
+
+    /* Test that an minimal Dynamic WEP connection specifying only the auth
+     * algorithm and a valid 802.1x setting is completed to a valid Dynamic
+     * WEP connection when completed with an AP with the Privacy bit set.
+     */
+
+    src = nm_simple_connection_new();
+    fill_wifi_empty(src);
+    fill_wsec(src, src_wsec);
+    fill_8021x(src, both_8021x);
+    success = complete_connection(ssid,
+                                  bssid,
+                                  NM_802_11_MODE_INFRA,
+                                  NM_802_11_AP_FLAGS_PRIVACY,
+                                  NM_802_11_AP_SEC_NONE,
+                                  NM_802_11_AP_SEC_NONE,
+                                  FALSE,
+                                  src,
+                                  &error);
+
+    /* We expect a completed Dynamic WEP connection */
+    expected = create_basic(ssid, NULL, NM_802_11_MODE_INFRA);
+    fill_wsec(expected, exp_wsec);
+    fill_8021x(expected, both_8021x);
+    COMPARE(src, expected, success, error, 0, 0);
+
+    g_object_unref(src);
+    g_object_unref(expected);
+}
+
+/*****************************************************************************/
+
+static void
+test_priv_ap_dynamic_wep_3(void)
+{
+    NMConnection *src;
+    const char *  bssid       = "01:02:03:04:05:06";
+    const KeyData src_wsec[]  = {{NM_SETTING_WIRELESS_SECURITY_AUTH_ALG, "shared", 0}, {NULL}};
+    const KeyData src_8021x[] = {{NM_SETTING_802_1X_EAP, "peap", 0},
+                                 {NM_SETTING_802_1X_IDENTITY, "Bill Smith", 0},
+                                 {NM_SETTING_802_1X_PHASE2_AUTH, "mschapv2", 0},
+                                 {NULL}};
+    gboolean      success;
+    GError *      error = NULL;
+
+    /* Ensure that a basic connection specifying 'shared' auth and an 802.1x
+     * setting is rejected, as 802.1x is incompatible with 'shared' auth.
+     */
+
+    src = nm_simple_connection_new();
+    fill_wifi_empty(src);
+    fill_wsec(src, src_wsec);
+    fill_8021x(src, src_8021x);
+    success = complete_connection("blahblah",
+                                  bssid,
+                                  NM_802_11_MODE_INFRA,
+                                  NM_802_11_AP_FLAGS_PRIVACY,
+                                  NM_802_11_AP_SEC_NONE,
+                                  NM_802_11_AP_SEC_NONE,
+                                  FALSE,
+                                  src,
+                                  &error);
+    /* Expect failure; shared is not compatible with dynamic WEP */
+    COMPARE(src, NULL, success, error, NM_CONNECTION_ERROR, NM_CONNECTION_ERROR_INVALID_PROPERTY);
+
+    g_object_unref(src);
+}
+
+/*****************************************************************************/
+
+static void
+test_priv_ap_wpa_psk_connection_1(void)
+{
+    /* Test that a basic WPA-PSK connection is rejected when completion is
+     * attempted with an AP with just the Privacy bit set.  Lack of WPA/RSN
+     * flags means the AP provides Static/Dynamic WEP or LEAP, not WPA.
+     */
+    test_ap_wpa_psk_connection_base(NULL,
+                                    NULL,
+                                    NM_802_11_AP_FLAGS_PRIVACY,
+                                    NM_802_11_AP_SEC_NONE,
+                                    NM_802_11_AP_SEC_NONE,
+                                    FALSE,
+                                    NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                                    NULL);
+}
+
+static void
+test_priv_ap_wpa_psk_connection_2(void)
+{
+    /* Test that a basic WPA-PSK connection is rejected when completion is
+     * attempted with an AP with just the Privacy bit set.  Lack of WPA/RSN
+     * flags means the AP provides Static/Dynamic WEP or LEAP, not WPA.
+     */
+    test_ap_wpa_psk_connection_base(NULL,
+                                    NULL,
+                                    NM_802_11_AP_FLAGS_PRIVACY,
+                                    NM_802_11_AP_SEC_NONE,
+                                    NM_802_11_AP_SEC_NONE,
+                                    TRUE,
+                                    NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                                    NULL);
+}
+
+static void
+test_priv_ap_wpa_psk_connection_3(void)
+{
+    /* Test that a basic WPA-PSK connection specifying only the auth algorithm
+     * is rejected when completion is attempted with an AP with just the Privacy
+     * bit set.  Lack of WPA/RSN flags means the AP provides Static/Dynamic WEP
+     * or LEAP, not WPA.
+     */
+    test_ap_wpa_psk_connection_base(NULL,
+                                    "open",
+                                    NM_802_11_AP_FLAGS_PRIVACY,
+                                    NM_802_11_AP_SEC_NONE,
+                                    NM_802_11_AP_SEC_NONE,
+                                    FALSE,
+                                    NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                                    NULL);
+}
+
+static void
+test_priv_ap_wpa_psk_connection_4(void)
+{
+    /* Test that a basic WPA-PSK connection specifying only the auth algorithm
+     * is rejected when completion is attempted with an AP with just the Privacy
+     * bit set.  Lack of WPA/RSN flags means the AP provides Static/Dynamic WEP
+     * or LEAP, not WPA.  Second, 'shared' auth is incompatible with WPA.
+     */
+    test_ap_wpa_psk_connection_base(NULL,
+                                    "shared",
+                                    NM_802_11_AP_FLAGS_PRIVACY,
+                                    NM_802_11_AP_SEC_NONE,
+                                    NM_802_11_AP_SEC_NONE,
+                                    FALSE,
+                                    NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                                    NULL);
+}
+
+static void
+test_priv_ap_wpa_psk_connection_5(void)
+{
+    /* Test that a WPA-PSK connection specifying both the key management and
+     * auth algorithm is rejected when completion is attempted with an AP with
+     * just the Privacy bit set.  Lack of WPA/RSN flags means the AP provides
+     * Static/Dynamic WEP or LEAP, not WPA.
+     */
+    test_ap_wpa_psk_connection_base("wpa-psk",
+                                    "open",
+                                    NM_802_11_AP_FLAGS_PRIVACY,
+                                    NM_802_11_AP_SEC_NONE,
+                                    NM_802_11_AP_SEC_NONE,
+                                    FALSE,
+                                    NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                                    NULL);
+}
+
+/*****************************************************************************/
+
+static void
+test_wpa_ap_empty_connection(gconstpointer data)
+{
+    guint         idx = GPOINTER_TO_UINT(data);
+    NMConnection *src, *expected;
+    const char *  bssid      = "01:02:03:04:05:06";
+    const char *  ssid       = "blahblah";
+    const KeyData exp_wsec[] = {{NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, "wpa-psk", 0},
+                                {NM_SETTING_WIRELESS_SECURITY_AUTH_ALG, "open", 0},
+                                {NULL}};
+    gboolean      success;
+    GError *      error = NULL;
+
+    /* Test that a basic WPA-PSK connection specifying just key management and
+     * the auth algorithm is completed successfully when given an AP with WPA
+     * or RSN flags.
+     */
+
+    src     = nm_simple_connection_new();
+    success = complete_connection(ssid,
+                                  bssid,
+                                  NM_802_11_MODE_INFRA,
+                                  NM_802_11_AP_FLAGS_PRIVACY,
+                                  wpa_flags_for_idx(idx),
+                                  rsn_flags_for_idx(idx),
+                                  FALSE,
+                                  src,
+                                  &error);
+
+    /* WPA connection expected */
+    expected = create_basic(ssid, NULL, NM_802_11_MODE_INFRA);
+    fill_wsec(expected, exp_wsec);
+    COMPARE(src, expected, success, error, 0, 0);
+
+    g_object_unref(src);
+    g_object_unref(expected);
+}
+
+/*****************************************************************************/
+
+static void
+test_wpa_ap_leap_connection_1(gconstpointer data)
+{
+    guint         idx = GPOINTER_TO_UINT(data);
+    NMConnection *src;
+    const char *  ssid          = "blahblah";
+    const char *  bssid         = "01:02:03:04:05:06";
+    const char *  leap_username = "Bill Smith";
+    const KeyData src_wsec[]    = {{NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, "ieee8021x", 0},
+                                {NM_SETTING_WIRELESS_SECURITY_LEAP_USERNAME, leap_username, 0},
+                                {NULL}};
+    gboolean      success;
+    GError *      error = NULL;
+
+    /* Test that completion of a LEAP connection with a WPA-enabled AP is
+     * rejected since WPA APs (usually) do not support LEAP.
+     */
+
+    src = nm_simple_connection_new();
+    fill_wifi_empty(src);
+    fill_wsec(src, src_wsec);
+    success = complete_connection(ssid,
+                                  bssid,
+                                  NM_802_11_MODE_INFRA,
+                                  NM_802_11_AP_FLAGS_PRIVACY,
+                                  wpa_flags_for_idx(idx),
+                                  rsn_flags_for_idx(idx),
+                                  FALSE,
+                                  src,
+                                  &error);
+    /* Expect failure here; WPA APs don't support old-school LEAP */
+    COMPARE(src, NULL, success, error, NM_CONNECTION_ERROR, NM_CONNECTION_ERROR_INVALID_PROPERTY);
+
+    g_object_unref(src);
+}
+
+/*****************************************************************************/
+
+static void
+test_wpa_ap_leap_connection_2(gconstpointer data)
+{
+    guint         idx = GPOINTER_TO_UINT(data);
+    NMConnection *src;
+    const char *  bssid      = "01:02:03:04:05:06";
+    const KeyData src_wsec[] = {{NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, "ieee8021x", 0},
+                                {NM_SETTING_WIRELESS_SECURITY_AUTH_ALG, "leap", 0},
+                                {NULL}};
+    gboolean      success;
+    GError *      error = NULL;
+
+    /* Test that completion of a LEAP connection with a WPA-enabled AP is
+     * rejected since WPA APs (usually) do not support LEAP.
+     */
+
+    src = nm_simple_connection_new();
+    fill_wifi_empty(src);
+    fill_wsec(src, src_wsec);
+    success = complete_connection("blahblah",
+                                  bssid,
+                                  NM_802_11_MODE_INFRA,
+                                  NM_802_11_AP_FLAGS_PRIVACY,
+                                  wpa_flags_for_idx(idx),
+                                  rsn_flags_for_idx(idx),
+                                  FALSE,
+                                  src,
+                                  &error);
+    /* We expect failure here, we need a LEAP username */
+    COMPARE(src, NULL, success, error, NM_CONNECTION_ERROR, NM_CONNECTION_ERROR_INVALID_PROPERTY);
+
+    g_object_unref(src);
+}
+
+/*****************************************************************************/
+
+static void
+test_wpa_ap_dynamic_wep_connection(gconstpointer data)
+{
+    guint         idx = GPOINTER_TO_UINT(data);
+    NMConnection *src;
+    const char *  bssid      = "01:02:03:04:05:06";
+    const KeyData src_wsec[] = {{NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, "ieee8021x", 0}, {NULL}};
+    gboolean      success;
+    GError *      error = NULL;
+
+    /* Test that completion of a Dynamic WEP connection with a WPA-enabled AP is
+     * rejected since WPA APs (usually) do not support Dynamic WEP.
+     */
+
+    src = nm_simple_connection_new();
+    fill_wifi_empty(src);
+    fill_wsec(src, src_wsec);
+    success = complete_connection("blahblah",
+                                  bssid,
+                                  NM_802_11_MODE_INFRA,
+                                  NM_802_11_AP_FLAGS_PRIVACY,
+                                  wpa_flags_for_idx(idx),
+                                  rsn_flags_for_idx(idx),
+                                  FALSE,
+                                  src,
+                                  &error);
+    /* We expect failure here since Dynamic WEP is incompatible with WPA */
+    COMPARE(src, NULL, success, error, NM_CONNECTION_ERROR, NM_CONNECTION_ERROR_INVALID_PROPERTY);
+
+    g_object_unref(src);
+}
+
+/*****************************************************************************/
+
+static void
+test_wpa_ap_wpa_psk_connection_1(gconstpointer data)
+{
+    guint         idx = GPOINTER_TO_UINT(data);
+    NMConnection *expected;
+    const KeyData exp_wsec[] = {{NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, "wpa-psk", 0},
+                                {NM_SETTING_WIRELESS_SECURITY_AUTH_ALG, "open", 0},
+                                {NULL}};
+
+    expected = nm_simple_connection_new();
+    fill_wsec(expected, exp_wsec);
+    test_ap_wpa_psk_connection_base(NULL,
+                                    NULL,
+                                    NM_802_11_AP_FLAGS_PRIVACY,
+                                    wpa_flags_for_idx(idx),
+                                    rsn_flags_for_idx(idx),
+                                    FALSE,
+                                    NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                                    expected);
+    g_object_unref(expected);
+}
+
+static void
+test_wpa_ap_wpa_psk_connection_2(gconstpointer data)
+{
+    guint         idx = GPOINTER_TO_UINT(data);
+    NMConnection *expected;
+    const KeyData exp_wsec[] = {{NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, "wpa-psk", 0},
+                                {NM_SETTING_WIRELESS_SECURITY_AUTH_ALG, "open", 0},
+                                {NULL}};
+
+    expected = nm_simple_connection_new();
+    fill_wsec(expected, exp_wsec);
+    test_ap_wpa_psk_connection_base(NULL,
+                                    NULL,
+                                    NM_802_11_AP_FLAGS_PRIVACY,
+                                    wpa_flags_for_idx(idx),
+                                    rsn_flags_for_idx(idx),
+                                    TRUE,
+                                    NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                                    expected);
+    g_object_unref(expected);
+}
+
+static void
+test_wpa_ap_wpa_psk_connection_3(gconstpointer data)
+{
+    guint         idx = GPOINTER_TO_UINT(data);
+    NMConnection *expected;
+    const KeyData exp_wsec[] = {{NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, "wpa-psk", 0},
+                                {NM_SETTING_WIRELESS_SECURITY_AUTH_ALG, "open", 0},
+                                {NULL}};
+
+    expected = nm_simple_connection_new();
+    fill_wsec(expected, exp_wsec);
+    test_ap_wpa_psk_connection_base(NULL,
+                                    "open",
+                                    NM_802_11_AP_FLAGS_PRIVACY,
+                                    wpa_flags_for_idx(idx),
+                                    rsn_flags_for_idx(idx),
+                                    FALSE,
+                                    NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                                    expected);
+    g_object_unref(expected);
+}
+
+static void
+test_wpa_ap_wpa_psk_connection_4(gconstpointer data)
+{
+    guint idx = GPOINTER_TO_UINT(data);
+    test_ap_wpa_psk_connection_base(NULL,
+                                    "shared",
+                                    NM_802_11_AP_FLAGS_PRIVACY,
+                                    wpa_flags_for_idx(idx),
+                                    rsn_flags_for_idx(idx),
+                                    FALSE,
+                                    NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                                    NULL);
+}
+
+static void
+test_wpa_ap_wpa_psk_connection_5(gconstpointer data)
+{
+    guint         idx = GPOINTER_TO_UINT(data);
+    NMConnection *expected;
+    const KeyData exp_wsec[] = {{NM_SETTING_WIRELESS_SECURITY_KEY_MGMT, "wpa-psk", 0},
+                                {NM_SETTING_WIRELESS_SECURITY_AUTH_ALG, "open", 0},
+                                {NULL}};
+
+    expected = nm_simple_connection_new();
+    fill_wsec(expected, exp_wsec);
+    test_ap_wpa_psk_connection_base("wpa-psk",
+                                    "open",
+                                    NM_802_11_AP_FLAGS_PRIVACY,
+                                    wpa_flags_for_idx(idx),
+                                    rsn_flags_for_idx(idx),
+                                    FALSE,
+                                    NM_CONNECTION_ERROR_INVALID_PROPERTY,
+                                    expected);
+    g_object_unref(expected);
+}
+
+/*****************************************************************************/
+
+static void
+test_strength_dbm(void)
+{
+    /* boundary conditions first */
+    g_assert_cmpint(nm_wifi_utils_level_to_quality(-1), ==, 100);
+    g_assert_cmpint(nm_wifi_utils_level_to_quality(-40), ==, 100);
+    g_assert_cmpint(nm_wifi_utils_level_to_quality(-30), ==, 100);
+    g_assert_cmpint(nm_wifi_utils_level_to_quality(-100), ==, 0);
+    g_assert_cmpint(nm_wifi_utils_level_to_quality(-200), ==, 0);
+
+    g_assert_cmpint(nm_wifi_utils_level_to_quality(-81), ==, 32);
+    g_assert_cmpint(nm_wifi_utils_level_to_quality(-92), ==, 14);
+    g_assert_cmpint(nm_wifi_utils_level_to_quality(-74), ==, 44);
+    g_assert_cmpint(nm_wifi_utils_level_to_quality(-81), ==, 32);
+    g_assert_cmpint(nm_wifi_utils_level_to_quality(-66), ==, 57);
+}
+
+static void
+test_strength_percent(void)
+{
+    int i;
+
+    /* boundary conditions first */
+    g_assert_cmpint(nm_wifi_utils_level_to_quality(0), ==, 0);
+    g_assert_cmpint(nm_wifi_utils_level_to_quality(100), ==, 100);
+    g_assert_cmpint(nm_wifi_utils_level_to_quality(110), ==, 100);
+
+    for (i = 0; i <= 100; i++)
+        g_assert_cmpint(nm_wifi_utils_level_to_quality(i), ==, i);
+}
+
+static void
+test_strength_wext(void)
+{
+    /* boundary conditions that we assume aren't WEXT first */
+    g_assert_cmpint(nm_wifi_utils_level_to_quality(256), ==, 100);
+    g_assert_cmpint(nm_wifi_utils_level_to_quality(110), ==, 100);
+
+    /* boundary conditions that we assume are WEXT */
+    g_assert_cmpint(nm_wifi_utils_level_to_quality(111), ==, 0);
+    g_assert_cmpint(nm_wifi_utils_level_to_quality(150), ==, 0);
+    g_assert_cmpint(nm_wifi_utils_level_to_quality(225), ==, 100);
+    g_assert_cmpint(nm_wifi_utils_level_to_quality(255), ==, 100);
+
+    g_assert_cmpint(nm_wifi_utils_level_to_quality(157), ==, 2);
+    g_assert_cmpint(nm_wifi_utils_level_to_quality(200), ==, 74);
+    g_assert_cmpint(nm_wifi_utils_level_to_quality(215), ==, 99);
+}
+
+#define _assert_strength_in_range(x)  \
+    ({                                \
+        guint32 _x = (x);             \
+        g_assert_cmpint(_x, >=, 0);   \
+        g_assert_cmpint(_x, <=, 100); \
+    })
+
+static void
+test_strength_all(void)
+{
+    int val;
+
+    for (val = -200; val < 300; val++)
+        _assert_strength_in_range(nm_wifi_utils_level_to_quality(val));
+    _assert_strength_in_range(nm_wifi_utils_level_to_quality(G_MININT));
+    _assert_strength_in_range(nm_wifi_utils_level_to_quality(G_MAXINT));
+    _assert_strength_in_range(nm_wifi_utils_level_to_quality(G_MININT32));
+    _assert_strength_in_range(nm_wifi_utils_level_to_quality(G_MAXINT32));
+    _assert_strength_in_range(nm_wifi_utils_level_to_quality(G_MININT16));
+    _assert_strength_in_range(nm_wifi_utils_level_to_quality(G_MAXINT16));
+}
+
+/*****************************************************************************/
+
+static void
+do_test_ssids_options_to_ptrarray(const char *const *ssids)
+{
+    GVariantBuilder  builder;
+    gs_unref_variant GVariant *variant     = NULL;
+    gs_unref_ptrarray GPtrArray *ssids_arr = NULL;
+    gs_free_error GError *error            = NULL;
+    gsize                 len;
+    gsize                 i;
+
+    g_assert(ssids);
+
+    len = NM_PTRARRAY_LEN(ssids);
+
+    g_variant_builder_init(&builder, G_VARIANT_TYPE("aay"));
+    for (i = 0; i < len; i++) {
+        const char *ssid = ssids[i];
+
+        g_variant_builder_add(
+            &builder,
+            "@ay",
+            g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, ssid, strlen(ssid), 1));
+    }
+    variant = g_variant_builder_end(&builder);
+
+    if (nmtst_get_rand_bool())
+        g_variant_ref_sink(variant);
+
+    ssids_arr = nmtst_ssids_options_to_ptrarray(variant, &error);
+    g_assert(!error);
+    if (len == 0) {
+        g_assert(!ssids_arr);
+        return;
+    }
+    g_assert_cmpint(len, ==, ssids_arr->len);
+    for (i = 0; i < len; i++) {
+        const char *ssid  = ssids[i];
+        GBytes *    bytes = ssids_arr->pdata[i];
+
+        g_assert(nm_utils_gbytes_equal_mem(bytes, ssid, strlen(ssid)));
+    }
+}
+
+static void
+test_ssids_options_to_ptrarray(void)
+{
+    do_test_ssids_options_to_ptrarray(NM_PTRARRAY_EMPTY(const char *));
+    do_test_ssids_options_to_ptrarray(NM_MAKE_STRV("ab"));
+    do_test_ssids_options_to_ptrarray(NM_MAKE_STRV("ab", "cd", "fsdfdsf"));
+}
+
+/*****************************************************************************/
+
+NMTST_DEFINE();
+
+int
+main(int argc, char **argv)
+{
+    gsize i;
+
+    nmtst_init_assert_logging(&argc, &argv, "INFO", "DEFAULT");
+
+    g_test_add_func("/wifi/lock_bssid", test_lock_bssid);
+
+    /* Open AP tests; make sure that connections to be completed that have
+     * various security-related settings already set cause the completion
+     * to fail.
+     */
+    g_test_add_func("/wifi/open_ap/empty_connection", test_open_ap_empty_connection);
+    g_test_add_data_func("/wifi/open_ap/leap_connection/1",
+                         (gconstpointer) TRUE,
+                         test_open_ap_leap_connection_1);
+    g_test_add_data_func("/wifi/open_ap/leap_connection/1_no_add_wifi",
+                         (gconstpointer) FALSE,
+                         test_open_ap_leap_connection_1);
+    g_test_add_func("/wifi/open_ap/leap_connection/2", test_open_ap_leap_connection_2);
+    g_test_add_data_func("/wifi/open_ap/wep_connection_true",
+                         (gconstpointer) TRUE,
+                         test_open_ap_wep_connection);
+    g_test_add_data_func("/wifi/open_ap/wep_connection_false",
+                         (gconstpointer) FALSE,
+                         test_open_ap_wep_connection);
+
+    g_test_add_func("/wifi/open_ap/wpa_psk_connection/1", test_open_ap_wpa_psk_connection_1);
+    g_test_add_func("/wifi/open_ap/wpa_psk_connection/2", test_open_ap_wpa_psk_connection_2);
+    g_test_add_func("/wifi/open_ap/wpa_psk_connection/3", test_open_ap_wpa_psk_connection_3);
+    g_test_add_func("/wifi/open_ap/wpa_psk_connection/4", test_open_ap_wpa_psk_connection_4);
+    g_test_add_func("/wifi/open_ap/wpa_psk_connection/5", test_open_ap_wpa_psk_connection_5);
+
+    g_test_add_data_func("/wifi/open_ap/wpa_eap_connection/1",
+                         (gconstpointer) IDX_OPEN,
+                         test_ap_wpa_eap_connection_1);
+    g_test_add_data_func("/wifi/open_ap/wpa_eap_connection/2",
+                         (gconstpointer) IDX_OPEN,
+                         test_ap_wpa_eap_connection_2);
+    g_test_add_data_func("/wifi/open_ap/wpa_eap_connection/3",
+                         (gconstpointer) IDX_OPEN,
+                         test_ap_wpa_eap_connection_3);
+    g_test_add_data_func("/wifi/open_ap/wpa_eap_connection/4",
+                         (gconstpointer) IDX_OPEN,
+                         test_ap_wpa_eap_connection_4);
+    g_test_add_data_func("/wifi/open_ap/wpa_eap_connection/5",
+                         (gconstpointer) IDX_OPEN,
+                         test_ap_wpa_eap_connection_5);
+
+    /* WEP AP tests */
+    g_test_add_func("/wifi/priv_ap/empty_connection", test_priv_ap_empty_connection);
+    g_test_add_data_func("/wifi/priv_ap/leap_connection/1",
+                         (gconstpointer) FALSE,
+                         test_priv_ap_leap_connection_1);
+    g_test_add_func("/wifi/priv_ap/leap_connection/2", test_priv_ap_leap_connection_2);
+
+    g_test_add_func("/wifi/priv_ap/dynamic_wep/1", test_priv_ap_dynamic_wep_1);
+    g_test_add_func("/wifi/priv_ap/dynamic_wep/2", test_priv_ap_dynamic_wep_2);
+    g_test_add_func("/wifi/priv_ap/dynamic_wep/3", test_priv_ap_dynamic_wep_3);
+
+    g_test_add_func("/wifi/priv_ap/wpa_psk_connection/1", test_priv_ap_wpa_psk_connection_1);
+    g_test_add_func("/wifi/priv_ap/wpa_psk_connection/2", test_priv_ap_wpa_psk_connection_2);
+    g_test_add_func("/wifi/priv_ap/wpa_psk_connection/3", test_priv_ap_wpa_psk_connection_3);
+    g_test_add_func("/wifi/priv_ap/wpa_psk_connection/4", test_priv_ap_wpa_psk_connection_4);
+    g_test_add_func("/wifi/priv_ap/wpa_psk_connection/5", test_priv_ap_wpa_psk_connection_5);
+
+    g_test_add_data_func("/wifi/priv_ap/wpa_eap_connection/1",
+                         (gconstpointer) IDX_PRIV,
+                         test_ap_wpa_eap_connection_1);
+    g_test_add_data_func("/wifi/priv_ap/wpa_eap_connection/2",
+                         (gconstpointer) IDX_PRIV,
+                         test_ap_wpa_eap_connection_2);
+    g_test_add_data_func("/wifi/priv_ap/wpa_eap_connection/3",
+                         (gconstpointer) IDX_PRIV,
+                         test_ap_wpa_eap_connection_3);
+    g_test_add_data_func("/wifi/priv_ap/wpa_eap_connection/4",
+                         (gconstpointer) IDX_PRIV,
+                         test_ap_wpa_eap_connection_4);
+    g_test_add_data_func("/wifi/priv_ap/wpa_eap_connection/5",
+                         (gconstpointer) IDX_PRIV,
+                         test_ap_wpa_eap_connection_5);
+
+#define ADD_FUNC(func)                                                                  \
+    do {                                                                                \
+        char *name_idx = g_strdup_printf("/wifi/wpa_psk/" G_STRINGIFY(func) "/%zd", i); \
+        g_test_add_data_func(name_idx, (gconstpointer) i, func);                        \
+        g_free(name_idx);                                                               \
+    } while (0)
+
+    /* WPA-PSK tests */
+    for (i = IDX_WPA_PSK_PTKIP_GTKIP; i <= IDX_WPA_RSN_PSK_PCCMP_GCCMP; i++) {
+        ADD_FUNC(test_wpa_ap_empty_connection);
+        ADD_FUNC(test_wpa_ap_leap_connection_1);
+        ADD_FUNC(test_wpa_ap_leap_connection_2);
+        ADD_FUNC(test_wpa_ap_dynamic_wep_connection);
+        ADD_FUNC(test_wpa_ap_wpa_psk_connection_1);
+        ADD_FUNC(test_wpa_ap_wpa_psk_connection_2);
+        ADD_FUNC(test_wpa_ap_wpa_psk_connection_3);
+        ADD_FUNC(test_wpa_ap_wpa_psk_connection_4);
+        ADD_FUNC(test_wpa_ap_wpa_psk_connection_5);
+        ADD_FUNC(test_ap_wpa_eap_connection_1);
+        ADD_FUNC(test_ap_wpa_eap_connection_2);
+        ADD_FUNC(test_ap_wpa_eap_connection_3);
+        ADD_FUNC(test_ap_wpa_eap_connection_4);
+        ADD_FUNC(test_ap_wpa_eap_connection_5);
+    }
+
+#undef ADD_FUNC
+#define ADD_FUNC(func)                                                                  \
+    do {                                                                                \
+        char *name_idx = g_strdup_printf("/wifi/rsn_psk/" G_STRINGIFY(func) "/%zd", i); \
+        g_test_add_data_func(name_idx, (gconstpointer) i, func);                        \
+        g_free(name_idx);                                                               \
+    } while (0)
+
+    /* RSN-PSK tests */
+    for (i = IDX_WPA_RSN_PSK_PTKIP_PCCMP_GTKIP; i <= IDX_RSN_PSK_PTKIP_PCCMP_GTKIP; i++) {
+        ADD_FUNC(test_wpa_ap_empty_connection);
+        ADD_FUNC(test_wpa_ap_leap_connection_1);
+        ADD_FUNC(test_wpa_ap_leap_connection_2);
+        ADD_FUNC(test_wpa_ap_dynamic_wep_connection);
+        ADD_FUNC(test_wpa_ap_wpa_psk_connection_1);
+        ADD_FUNC(test_wpa_ap_wpa_psk_connection_2);
+        ADD_FUNC(test_wpa_ap_wpa_psk_connection_3);
+        ADD_FUNC(test_wpa_ap_wpa_psk_connection_4);
+        ADD_FUNC(test_wpa_ap_wpa_psk_connection_5);
+        ADD_FUNC(test_ap_wpa_eap_connection_1);
+        ADD_FUNC(test_ap_wpa_eap_connection_2);
+        ADD_FUNC(test_ap_wpa_eap_connection_3);
+        ADD_FUNC(test_ap_wpa_eap_connection_4);
+        ADD_FUNC(test_ap_wpa_eap_connection_5);
+    }
+
+#undef ADD_FUNC
+
+    /* Scanned signal strength conversion tests */
+    g_test_add_func("/wifi/strength/dbm", test_strength_dbm);
+    g_test_add_func("/wifi/strength/percent", test_strength_percent);
+    g_test_add_func("/wifi/strength/wext", test_strength_wext);
+    g_test_add_func("/wifi/strength/all", test_strength_all);
+
+    g_test_add_func("/wifi/ssids_options_to_ptrarray", test_ssids_options_to_ptrarray);
+
+    return g_test_run();
+}