eiwd

no dbus iwd with iwctl functionality
git clone https://git.daat.foo/repos/eiwd.git
Log | Files | Refs | Submodules | README | LICENSE

ap.c (128836B)


      1 /*
      2  *
      3  *  Wireless daemon for Linux
      4  *
      5  *  Copyright (C) 2017-2019  Intel Corporation. All rights reserved.
      6  *
      7  *  This library is free software; you can redistribute it and/or
      8  *  modify it under the terms of the GNU Lesser General Public
      9  *  License as published by the Free Software Foundation; either
     10  *  version 2.1 of the License, or (at your option) any later version.
     11  *
     12  *  This library is distributed in the hope that it will be useful,
     13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
     14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     15  *  Lesser General Public License for more details.
     16  *
     17  *  You should have received a copy of the GNU Lesser General Public
     18  *  License along with this library; if not, write to the Free Software
     19  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
     20  *
     21  */
     22 
     23 #ifdef HAVE_CONFIG_H
     24 #include <config.h>
     25 #endif
     26 
     27 #define _GNU_SOURCE
     28 #include <errno.h>
     29 #include <linux/if_ether.h>
     30 #include <netinet/in.h>
     31 #include <arpa/inet.h>
     32 #include <linux/if.h>
     33 
     34 #include <ell/ell.h>
     35 
     36 #include "linux/nl80211.h"
     37 
     38 #include "ell/useful.h"
     39 #include "src/missing.h"
     40 #include "src/iwd.h"
     41 #include "src/module.h"
     42 #include "src/scan.h"
     43 #include "src/netdev.h"
     44 #include "src/wiphy.h"
     45 #include "src/crypto.h"
     46 #include "src/ie.h"
     47 #include "src/mpdu.h"
     48 #include "src/util.h"
     49 #include "src/eapol.h"
     50 #include "src/handshake.h"
     51 #include "src/dbus.h"
     52 #include "src/nl80211util.h"
     53 #include "src/frame-xchg.h"
     54 #include "src/wscutil.h"
     55 #include "src/eap-wsc.h"
     56 #include "src/ip-pool.h"
     57 #include "src/netconfig.h"
     58 #include "src/ap.h"
     59 #include "src/storage.h"
     60 #include "src/diagnostic.h"
     61 #include "src/band.h"
     62 #include "src/common.h"
     63 
     64 struct ap_state {
     65 	struct netdev *netdev;
     66 	struct l_genl_family *nl80211;
     67 	const struct ap_ops *ops;
     68 	ap_stopped_func_t stopped_func;
     69 	void *user_data;
     70 
     71 	char ssid[SSID_MAX_SIZE + 1];
     72 	char passphrase[64];
     73 	uint8_t psk[32];
     74 	enum band_freq band;
     75 	uint8_t channel;
     76 	struct band_chandef chandef;
     77 	uint8_t *authorized_macs;
     78 	unsigned int authorized_macs_num;
     79 	char wsc_name[33];
     80 	struct wsc_primary_device_type wsc_primary_device_type;
     81 
     82 	unsigned int ciphers;
     83 	enum ie_rsn_cipher_suite group_cipher;
     84 	uint32_t beacon_interval;
     85 	struct l_uintset *rates;
     86 	uint32_t start_stop_cmd_id;
     87 	uint32_t mlme_watch;
     88 	uint8_t gtk[CRYPTO_MAX_GTK_LEN];
     89 	uint8_t gtk_index;
     90 	struct l_queue *wsc_pbc_probes;
     91 	struct l_timeout *wsc_pbc_timeout;
     92 	uint16_t wsc_dpid;
     93 	uint8_t wsc_uuid_r[16];
     94 
     95 	uint16_t last_aid;
     96 	struct l_queue *sta_states;
     97 
     98 	struct l_dhcp_server *netconfig_dhcp;
     99 	struct l_rtnl_address *netconfig_addr4;
    100 	uint32_t rtnl_add_cmd;
    101 	uint32_t rtnl_get_gateway4_mac_cmd;
    102 	uint32_t rtnl_get_dns4_mac_cmd;
    103 	uint8_t netconfig_gateway4_mac[6];
    104 	uint8_t netconfig_dns4_mac[6];
    105 
    106 	uint32_t scan_id;
    107 	struct l_dbus_message *scan_pending;
    108 	struct l_queue *networks;
    109 
    110 	struct l_timeout *rekey_timeout;
    111 	unsigned int rekey_time;
    112 
    113 	uint32_t pre_scan_cmd_id;
    114 
    115 	bool started : 1;
    116 	bool gtk_set : 1;
    117 	bool netconfig_set_addr4 : 1;
    118 	bool in_event : 1;
    119 	bool free_pending : 1;
    120 	bool scanning : 1;
    121 	bool supports_ht : 1;
    122 };
    123 
    124 struct sta_state {
    125 	uint8_t addr[6];
    126 	bool associated;
    127 	bool rsna;
    128 	uint16_t aid;
    129 	struct mmpdu_field_capability capability;
    130 	uint16_t listen_interval;
    131 	struct l_uintset *rates;
    132 	uint32_t assoc_resp_cmd_id;
    133 	struct ap_state *ap;
    134 	uint8_t *assoc_ies;
    135 	size_t assoc_ies_len;
    136 	uint8_t *assoc_rsne;
    137 	struct eapol_sm *sm;
    138 	struct handshake_state *hs;
    139 	uint32_t gtk_query_cmd_id;
    140 	struct l_idle *stop_handshake_work;
    141 	struct l_settings *wsc_settings;
    142 	uint8_t wsc_uuid_e[16];
    143 	bool wsc_v2;
    144 	struct l_dhcp_lease *ip_alloc_lease;
    145 	bool ip_alloc_sent;
    146 	uint64_t rekey_time;
    147 
    148 	bool ht_support : 1;
    149 	bool ht_greenfield : 1;
    150 };
    151 
    152 struct ap_wsc_pbc_probe_record {
    153 	uint8_t mac[6];
    154 	uint8_t uuid_e[16];
    155 	uint64_t timestamp;
    156 };
    157 
    158 struct ap_network {
    159 	char ssid[SSID_MAX_SIZE + 1];
    160 	int16_t signal;
    161 	enum security security;
    162 };
    163 
    164 static char **global_addr4_strs;
    165 static uint32_t netdev_watch;
    166 static struct l_netlink *rtnl;
    167 
    168 static bool network_match_ssid(const void *a, const void *b)
    169 {
    170 	const struct ap_network *network = a;
    171 	const char *ssid = b;
    172 
    173 	return !strcmp(network->ssid, ssid);
    174 }
    175 
    176 static int network_signal_compare(const void *a, const void *b, void *user)
    177 {
    178 	const struct ap_network *new_network = a;
    179 	const struct ap_network *network = b;
    180 
    181 	return (network->signal > new_network->signal) ? 1 : -1;
    182 }
    183 
    184 static struct ap_network *ap_network_find(struct ap_state *ap,
    185 						struct scan_bss *bss)
    186 {
    187 	char ssid[SSID_MAX_SIZE + 1];
    188 
    189 	memcpy(ssid, bss->ssid, bss->ssid_len);
    190 	ssid[bss->ssid_len] = '\0';
    191 
    192 	return l_queue_find(ap->networks, network_match_ssid, ssid);
    193 }
    194 
    195 static void ap_network_append(struct ap_state *ap, struct scan_bss *bss)
    196 {
    197 	struct ap_network *network;
    198 	enum security security;
    199 
    200 	if (util_ssid_is_hidden(bss->ssid_len, bss->ssid))
    201 		return;
    202 
    203 	network = ap_network_find(ap, bss);
    204 	if (!network) {
    205 		if (scan_bss_get_security(bss, &security) < 0)
    206 			return;
    207 
    208 		network = l_new(struct ap_network, 1);
    209 		network->signal = bss->signal_strength;
    210 		network->security = security;
    211 
    212 		memcpy(network->ssid, bss->ssid, bss->ssid_len);
    213 		network->ssid[bss->ssid_len] = '\0';
    214 
    215 		goto insert;
    216 	}
    217 
    218 	if (bss->signal_strength <= network->signal)
    219 		return;
    220 
    221 	l_queue_remove(ap->networks, network);
    222 	network->signal = bss->signal_strength;
    223 
    224 insert:
    225 	l_queue_insert(ap->networks, network, network_signal_compare, NULL);
    226 }
    227 
    228 static void ap_stop_handshake(struct sta_state *sta)
    229 {
    230 	if (sta->sm) {
    231 		eapol_sm_free(sta->sm);
    232 		sta->sm = NULL;
    233 	}
    234 
    235 	if (sta->hs) {
    236 		handshake_state_unref(sta->hs);
    237 		sta->hs = NULL;
    238 	}
    239 
    240 	if (sta->wsc_settings) {
    241 		l_settings_free(sta->wsc_settings);
    242 		sta->wsc_settings = NULL;
    243 	}
    244 
    245 	if (sta->stop_handshake_work) {
    246 		l_idle_remove(sta->stop_handshake_work);
    247 		sta->stop_handshake_work = NULL;
    248 	}
    249 }
    250 
    251 static void ap_stop_handshake_work(struct l_idle *idle, void *user_data)
    252 {
    253 	struct sta_state *sta = user_data;
    254 
    255 	ap_stop_handshake(sta);
    256 }
    257 
    258 static void ap_sta_free(void *data)
    259 {
    260 	struct sta_state *sta = data;
    261 	struct ap_state *ap = sta->ap;
    262 
    263 	if (sta->rates)
    264 		l_uintset_free(sta->rates);
    265 
    266 	l_free(sta->assoc_ies);
    267 
    268 	if (sta->assoc_resp_cmd_id)
    269 		l_genl_family_cancel(ap->nl80211, sta->assoc_resp_cmd_id);
    270 
    271 	if (sta->gtk_query_cmd_id)
    272 		l_genl_family_cancel(ap->nl80211, sta->gtk_query_cmd_id);
    273 
    274 	if (sta->ip_alloc_lease && ap->netconfig_dhcp)
    275 		l_dhcp_server_lease_remove(ap->netconfig_dhcp,
    276 						sta->ip_alloc_lease);
    277 
    278 	ap_stop_handshake(sta);
    279 
    280 	l_free(sta);
    281 }
    282 
    283 static void ap_reset(struct ap_state *ap)
    284 {
    285 	struct netdev *netdev = ap->netdev;
    286 
    287 	explicit_bzero(ap->passphrase, sizeof(ap->passphrase));
    288 	explicit_bzero(ap->psk, sizeof(ap->psk));
    289 
    290 	if (ap->authorized_macs_num) {
    291 		l_free(ap->authorized_macs);
    292 		ap->authorized_macs_num = 0;
    293 	}
    294 
    295 	if (ap->mlme_watch) {
    296 		l_genl_family_unregister(ap->nl80211, ap->mlme_watch);
    297 		ap->mlme_watch = 0;
    298 	}
    299 
    300 	frame_watch_wdev_remove(netdev_get_wdev_id(netdev));
    301 
    302 	if (ap->start_stop_cmd_id) {
    303 		l_genl_family_cancel(ap->nl80211, ap->start_stop_cmd_id);
    304 		ap->start_stop_cmd_id = 0;
    305 	}
    306 
    307 	if (ap->rtnl_add_cmd) {
    308 		l_netlink_cancel(rtnl, ap->rtnl_add_cmd);
    309 		ap->rtnl_add_cmd = 0;
    310 	}
    311 
    312 	if (ap->rtnl_get_gateway4_mac_cmd) {
    313 		l_netlink_cancel(rtnl, ap->rtnl_get_gateway4_mac_cmd);
    314 		ap->rtnl_get_gateway4_mac_cmd = 0;
    315 	}
    316 
    317 	if (ap->rtnl_get_dns4_mac_cmd) {
    318 		l_netlink_cancel(rtnl, ap->rtnl_get_dns4_mac_cmd);
    319 		ap->rtnl_get_dns4_mac_cmd = 0;
    320 	}
    321 
    322 	l_queue_destroy(l_steal_ptr(ap->sta_states), ap_sta_free);
    323 
    324 	if (ap->rates)
    325 		l_uintset_free(l_steal_ptr(ap->rates));
    326 
    327 	l_queue_destroy(l_steal_ptr(ap->wsc_pbc_probes), l_free);
    328 	l_timeout_remove(ap->wsc_pbc_timeout);
    329 
    330 	ap->started = false;
    331 
    332 	/* Delete IP if one was set by IWD */
    333 	if (ap->netconfig_set_addr4) {
    334 		l_rtnl_ifaddr_delete(rtnl, netdev_get_ifindex(netdev),
    335 					ap->netconfig_addr4, NULL, NULL, NULL);
    336 		ap->netconfig_set_addr4 = false;
    337 	}
    338 
    339 	l_rtnl_address_free(l_steal_ptr(ap->netconfig_addr4));
    340 
    341 	if (ap->netconfig_dhcp) {
    342 		l_dhcp_server_destroy(ap->netconfig_dhcp);
    343 		ap->netconfig_dhcp = NULL;
    344 	}
    345 
    346 	if (ap->scan_id) {
    347 		scan_cancel(netdev_get_wdev_id(ap->netdev), ap->scan_id);
    348 		ap->scan_id = 0;
    349 	}
    350 
    351 	if (ap->networks) {
    352 		l_queue_destroy(ap->networks, l_free);
    353 		ap->networks = NULL;
    354 	}
    355 
    356 	if (ap->rekey_timeout) {
    357 		l_timeout_remove(ap->rekey_timeout);
    358 		ap->rekey_timeout = NULL;
    359 	}
    360 
    361 	if (ap->pre_scan_cmd_id) {
    362 		scan_cancel(netdev_get_wdev_id(ap->netdev),
    363 				ap->pre_scan_cmd_id);
    364 		ap->pre_scan_cmd_id = 0;
    365 	}
    366 }
    367 
    368 static bool ap_event_done(struct ap_state *ap, bool prev_in_event)
    369 {
    370 	ap->in_event = prev_in_event;
    371 
    372 	if (!prev_in_event && ap->free_pending) {
    373 		l_genl_family_free(ap->nl80211);
    374 		l_free(ap);
    375 		return true;
    376 	}
    377 
    378 	return ap->free_pending;
    379 }
    380 
    381 /*
    382  * Returns true if the AP is considered freed and the caller must avoid
    383  * accessing @ap.
    384  */
    385 static bool ap_event(struct ap_state *ap, enum ap_event_type event,
    386 			const void *event_data)
    387 {
    388 	bool prev = ap->in_event;
    389 
    390 	if (ap->free_pending)
    391 		return true;
    392 
    393 	ap->in_event = true;
    394 	ap->ops->handle_event(event, event_data, ap->user_data);
    395 	return ap_event_done(ap, prev);
    396 }
    397 
    398 static void ap_check_rekeys(struct ap_state *ap);
    399 
    400 static void ap_del_station(struct sta_state *sta, uint16_t reason,
    401 				bool disassociate)
    402 {
    403 	struct ap_state *ap = sta->ap;
    404 	uint32_t ifindex = netdev_get_ifindex(ap->netdev);
    405 	struct ap_event_station_removed_data event_data;
    406 	bool send_event = false;
    407 	struct l_genl_msg *msg;
    408 	uint8_t subtype = disassociate ?
    409 			MPDU_MANAGEMENT_SUBTYPE_DISASSOCIATION :
    410 			MPDU_MANAGEMENT_SUBTYPE_DEAUTHENTICATION;
    411 
    412 	msg = nl80211_build_del_station(ifindex, sta->addr, reason, subtype);
    413 	l_genl_family_send(ap->nl80211, msg, NULL, NULL, NULL);
    414 
    415 	sta->associated = false;
    416 
    417 	if (sta->rsna) {
    418 		if (ap->ops->handle_event) {
    419 			memset(&event_data, 0, sizeof(event_data));
    420 			event_data.mac = sta->addr;
    421 			event_data.reason = reason;
    422 			send_event = true;
    423 		}
    424 
    425 		sta->rsna = false;
    426 	}
    427 
    428 	if (sta->assoc_resp_cmd_id) {
    429 		l_genl_family_cancel(ap->nl80211, sta->assoc_resp_cmd_id);
    430 		sta->assoc_resp_cmd_id = 0;
    431 	}
    432 
    433 	if (sta->gtk_query_cmd_id) {
    434 		l_genl_family_cancel(ap->nl80211, sta->gtk_query_cmd_id);
    435 		sta->gtk_query_cmd_id = 0;
    436 	}
    437 
    438 	ap_stop_handshake(sta);
    439 
    440 	/*
    441 	 * If the event handler tears the AP down, we've made sure above that
    442 	 * a subsequent ap_sta_free(sta) has no need to access sta->ap.
    443 	 */
    444 	if (send_event)
    445 		if (ap_event(ap, AP_EVENT_STATION_REMOVED, &event_data))
    446 			return;
    447 
    448 	/*
    449 	 * Expire any DHCP leases owned by this client when it disconnects to
    450 	 * make it harder for somebody to DoS the IP pool.  If the client
    451 	 * comes back and the lease is still in the expired leases list they
    452 	 * will get their IP back.
    453 	 */
    454 	if (ap->netconfig_dhcp) {
    455 		bool prev = ap->in_event;
    456 
    457 		/*
    458 		 * If the LEASE_EXPIRED event in ap_dhcp_event_cb triggers an
    459 		 * ap_free(), delay cleanup to avoid destroying the DHCP
    460 		 * server midway through l_dhcp_server_expire_by_mac().
    461 		 */
    462 		ap->in_event = true;
    463 
    464 		sta->ip_alloc_lease = NULL;
    465 		l_dhcp_server_expire_by_mac(ap->netconfig_dhcp, sta->addr);
    466 
    467 		if (ap_event_done(ap, prev))
    468 			return;
    469 	}
    470 
    471 	/*
    472 	 * Set the rekey time to zero which will skip this station when
    473 	 * determining the next rekey.
    474 	 */
    475 	sta->rekey_time = 0;
    476 	ap_check_rekeys(ap);
    477 }
    478 
    479 static void ap_start_rekey(struct ap_state *ap, struct sta_state *sta)
    480 {
    481 	l_debug("Rekey STA "MAC, MAC_STR(sta->addr));
    482 
    483 	eapol_start(sta->sm);
    484 }
    485 
    486 static void ap_rekey_timeout(struct l_timeout *timeout, void *user_data)
    487 {
    488 	struct ap_state *ap = user_data;
    489 
    490 	ap_check_rekeys(ap);
    491 }
    492 
    493 /*
    494  * Used to check/start any rekeys which are due and reset the rekey timer to the
    495  * next soonest station needing a rekey.
    496  *
    497  * TODO: Could adapt this to also take into account the next GTK rekey and
    498  * service that as well. But GTK rekeys are not yet supported in AP mode.
    499  */
    500 static void ap_check_rekeys(struct ap_state *ap)
    501 {
    502 	const struct l_queue_entry *e;
    503 	uint64_t now = l_time_now();
    504 	uint64_t next = 0;
    505 
    506 	if (!ap->rekey_time)
    507 		return;
    508 
    509 	/* Find the station(s) that need a rekey and start it */
    510 	for (e = l_queue_get_entries(ap->sta_states); e; e = e->next) {
    511 		struct sta_state *sta = e->data;
    512 
    513 		if (!sta->associated || !sta->rsna || sta->rekey_time == 0)
    514 			continue;
    515 
    516 		if (l_time_before(now, sta->rekey_time)) {
    517 			uint64_t diff = l_time_diff(now, sta->rekey_time);
    518 
    519 			/* Finding the next rekey time */
    520 			if (next < diff)
    521 				next = diff;
    522 
    523 			continue;
    524 		}
    525 
    526 		ap_start_rekey(ap, sta);
    527 	}
    528 
    529 	/*
    530 	 * Set the next rekey to the station needing it the soonest, or remove
    531 	 * if a single station and wait until the rekey is complete to reset
    532 	 * the timer.
    533 	 */
    534 	if (next)
    535 		l_timeout_modify(ap->rekey_timeout, l_time_to_secs(next));
    536 	else {
    537 		l_timeout_remove(ap->rekey_timeout);
    538 		ap->rekey_timeout = NULL;
    539 	}
    540 }
    541 
    542 static void ap_set_sta_rekey_timer(struct ap_state *ap, struct sta_state *sta)
    543 {
    544 	if (!ap->rekey_time)
    545 		return;
    546 
    547 	sta->rekey_time = l_time_now() + ap->rekey_time - 1;
    548 
    549 	/*
    550 	 * First/only station authenticated, set rekey timer. Any more stations
    551 	 * will just set their rekey time and be serviced by the single callback
    552 	 */
    553 	if (!ap->rekey_timeout)
    554 		ap->rekey_timeout = l_timeout_create(
    555 						l_time_to_secs(ap->rekey_time),
    556 						ap_rekey_timeout, ap, NULL);
    557 }
    558 
    559 static bool ap_sta_match_addr(const void *a, const void *b)
    560 {
    561 	const struct sta_state *sta = a;
    562 
    563 	return !memcmp(sta->addr, b, 6);
    564 }
    565 
    566 static void ap_remove_sta(struct sta_state *sta)
    567 {
    568 	if (!l_queue_remove(sta->ap->sta_states, sta)) {
    569 		l_error("tried to remove station that doesn't exist");
    570 		return;
    571 	}
    572 
    573 	ap_sta_free(sta);
    574 }
    575 
    576 static void ap_set_sta_cb(struct l_genl_msg *msg, void *user_data)
    577 {
    578 	if (l_genl_msg_get_error(msg) < 0)
    579 		l_error("SET_STATION failed: %i", l_genl_msg_get_error(msg));
    580 }
    581 
    582 static void ap_del_key_cb(struct l_genl_msg *msg, void *user_data)
    583 {
    584 	if (l_genl_msg_get_error(msg) < 0)
    585 		l_debug("DEL_KEY failed: %i", l_genl_msg_get_error(msg));
    586 }
    587 
    588 static void ap_new_rsna(struct sta_state *sta)
    589 {
    590 	struct ap_state *ap = sta->ap;
    591 	struct ap_event_station_added_data event_data = {};
    592 
    593 	l_debug("STA "MAC" authenticated", MAC_STR(sta->addr));
    594 
    595 	sta->rsna = true;
    596 
    597 	ap_set_sta_rekey_timer(ap, sta);
    598 
    599 	event_data.mac = sta->addr;
    600 	event_data.assoc_ies = sta->assoc_ies;
    601 	event_data.assoc_ies_len = sta->assoc_ies_len;
    602 	ap_event(ap, AP_EVENT_STATION_ADDED, &event_data);
    603 }
    604 
    605 static void ap_drop_rsna(struct sta_state *sta)
    606 {
    607 	struct ap_state *ap = sta->ap;
    608 	struct l_genl_msg *msg;
    609 	uint32_t ifindex = netdev_get_ifindex(sta->ap->netdev);
    610 	uint8_t key_id = 0;
    611 	struct ap_event_station_removed_data event_data = {};
    612 
    613 	sta->rsna = false;
    614 
    615 	msg = nl80211_build_set_station_unauthorized(ifindex, sta->addr);
    616 
    617 	l_genl_msg_append_attr(msg, NL80211_ATTR_STA_AID, 2, &sta->aid);
    618 
    619 	if (!l_genl_family_send(ap->nl80211, msg, ap_set_sta_cb, NULL, NULL)) {
    620 		l_genl_msg_unref(msg);
    621 		l_error("Issuing SET_STATION failed");
    622 	}
    623 
    624 	msg = l_genl_msg_new_sized(NL80211_CMD_DEL_KEY, 64);
    625 	l_genl_msg_append_attr(msg, NL80211_ATTR_IFINDEX, 4, &ifindex);
    626 	l_genl_msg_append_attr(msg, NL80211_ATTR_KEY_IDX, 1, &key_id);
    627 	l_genl_msg_append_attr(msg, NL80211_ATTR_MAC, 6, sta->addr);
    628 
    629 	if (!l_genl_family_send(ap->nl80211, msg, ap_del_key_cb, NULL, NULL)) {
    630 		l_genl_msg_unref(msg);
    631 		l_error("Issuing DEL_KEY failed");
    632 	}
    633 
    634 	ap_stop_handshake(sta);
    635 
    636 	event_data.mac = sta->addr;
    637 	ap_event(ap, AP_EVENT_STATION_REMOVED, &event_data);
    638 }
    639 
    640 static void ap_set_rsn_info(struct ap_state *ap, struct ie_rsn_info *rsn)
    641 {
    642 	memset(rsn, 0, sizeof(*rsn));
    643 	rsn->akm_suites = IE_RSN_AKM_SUITE_PSK;
    644 	rsn->pairwise_ciphers = ap->ciphers;
    645 	rsn->group_cipher = ap->group_cipher;
    646 }
    647 
    648 static void ap_wsc_exit_pbc(struct ap_state *ap)
    649 {
    650 	if (!ap->wsc_pbc_timeout)
    651 		return;
    652 
    653 	l_timeout_remove(ap->wsc_pbc_timeout);
    654 	ap->wsc_dpid = 0;
    655 	ap_update_beacon(ap);
    656 
    657 	ap_event(ap, AP_EVENT_PBC_MODE_EXIT, NULL);
    658 }
    659 
    660 struct ap_pbc_record_expiry_data {
    661 	uint64_t min_time;
    662 	const uint8_t *mac;
    663 };
    664 
    665 static bool ap_wsc_pbc_record_expire(void *data, void *user_data)
    666 {
    667 	struct ap_wsc_pbc_probe_record *record = data;
    668 	const struct ap_pbc_record_expiry_data *expiry_data = user_data;
    669 
    670 	if (record->timestamp > expiry_data->min_time &&
    671 			memcmp(record->mac, expiry_data->mac, 6))
    672 		return false;
    673 
    674 	l_free(record);
    675 	return true;
    676 }
    677 
    678 #define AP_WSC_PBC_MONITOR_TIME	120
    679 #define AP_WSC_PBC_WALK_TIME	120
    680 
    681 static void ap_process_wsc_probe_req(struct ap_state *ap, const uint8_t *from,
    682 					const uint8_t *wsc_data,
    683 					size_t wsc_data_len)
    684 {
    685 	struct wsc_probe_request req;
    686 	struct ap_pbc_record_expiry_data expiry_data;
    687 	struct ap_wsc_pbc_probe_record *record;
    688 	uint64_t now;
    689 	bool empty;
    690 	uint8_t first_sta_addr[6] = {};
    691 	const struct l_queue_entry *entry;
    692 
    693 	if (wsc_parse_probe_request(wsc_data, wsc_data_len, &req) < 0)
    694 		return;
    695 
    696 	if (!(req.config_methods & WSC_CONFIGURATION_METHOD_PUSH_BUTTON))
    697 		return;
    698 
    699 	if (req.device_password_id != WSC_DEVICE_PASSWORD_ID_PUSH_BUTTON)
    700 		return;
    701 
    702 	/* Save the address of the first enrollee record */
    703 	record = l_queue_peek_head(ap->wsc_pbc_probes);
    704 	if (record)
    705 		memcpy(first_sta_addr, record->mac, 6);
    706 
    707 	now = l_time_now();
    708 
    709 	/*
    710 	 * Expire entries older than PBC Monitor Time.  While there also drop
    711 	 * older entries from the same Enrollee that sent us this new Probe
    712 	 * Request.  It's unclear whether we should also match by the UUID-E.
    713 	 */
    714 	expiry_data.min_time = now - AP_WSC_PBC_MONITOR_TIME * 1000000;
    715 	expiry_data.mac = from;
    716 	l_queue_foreach_remove(ap->wsc_pbc_probes, ap_wsc_pbc_record_expire,
    717 				&expiry_data);
    718 
    719 	empty = l_queue_isempty(ap->wsc_pbc_probes);
    720 
    721 	if (!ap->wsc_pbc_probes)
    722 		ap->wsc_pbc_probes = l_queue_new();
    723 
    724 	/* Add new record */
    725 	record = l_new(struct ap_wsc_pbc_probe_record, 1);
    726 	memcpy(record->mac, from, 6);
    727 	memcpy(record->uuid_e, req.uuid_e, sizeof(record->uuid_e));
    728 	record->timestamp = now;
    729 	l_queue_push_tail(ap->wsc_pbc_probes, record);
    730 
    731 	/*
    732 	 * If queue was non-empty and we've added one more record then we
    733 	 * now have seen more than one PBC enrollee during the PBC Monitor
    734 	 * Time and must exit "active PBC mode" due to "session overlap".
    735 	 * WSC v2.0.5 Section 11.3:
    736 	 * "Within the PBC Monitor Time, if the Registrar receives PBC
    737 	 * probe requests from more than one Enrollee [...] then the
    738 	 * Registrar SHALL signal a "session overlap" error.  As a result,
    739 	 * the Registrar shall refuse to enter active PBC mode and shall
    740 	 * also refuse to perform a PBC-based Registration Protocol
    741 	 * exchange [...]"
    742 	 */
    743 	if (empty)
    744 		return;
    745 
    746 	if (ap->wsc_pbc_timeout) {
    747 		l_debug("Exiting PBC mode due to Session Overlap");
    748 		ap_wsc_exit_pbc(ap);
    749 	}
    750 
    751 	/*
    752 	 * "If the Registrar is engaged in PBC Registration Protocol
    753 	 * exchange with an Enrollee and receives a Probe Request or M1
    754 	 * Message from another Enrollee, then the Registrar should
    755 	 * signal a "session overlap" error".
    756 	 *
    757 	 * For simplicity just interrupt the handshake with that enrollee.
    758 	 */
    759 	for (entry = l_queue_get_entries(ap->sta_states); entry;
    760 			entry = entry->next) {
    761 		struct sta_state *sta = entry->data;
    762 
    763 		if (!sta->associated || sta->assoc_rsne)
    764 			continue;
    765 
    766 		/*
    767 		 * Check whether this enrollee is in PBC Registration
    768 		 * Protocol by comparing its mac with the first (and only)
    769 		 * record we had in ap->wsc_pbc_probes.  If we had more
    770 		 * than one record we wouldn't have been in
    771 		 * "active PBC mode".
    772 		 */
    773 		if (memcmp(sta->addr, first_sta_addr, 6) ||
    774 				!memcmp(sta->addr, from, 6))
    775 			continue;
    776 
    777 		l_debug("Interrupting handshake with %s due to Session Overlap",
    778 			util_address_to_string(sta->addr));
    779 
    780 		if (sta->hs) {
    781 			netdev_handshake_failed(sta->hs,
    782 					MMPDU_REASON_CODE_DISASSOC_AP_BUSY);
    783 			sta->sm = NULL;
    784 		}
    785 
    786 		ap_remove_sta(sta);
    787 	}
    788 }
    789 
    790 static void ap_write_authorized_macs(struct ap_state *ap,
    791 					size_t out_len, uint8_t *out)
    792 {
    793 	size_t len = ap->authorized_macs_num * 6;
    794 
    795 	if (!len)
    796 		return;
    797 
    798 	if (len > out_len)
    799 		len = out_len;
    800 
    801 	memcpy(out, ap->authorized_macs, len);
    802 }
    803 
    804 static size_t ap_get_wsc_ie_len(struct ap_state *ap,
    805 				enum mpdu_management_subtype type,
    806 				const struct mmpdu_header *client_frame,
    807 				size_t client_frame_len)
    808 {
    809 	return 256;
    810 }
    811 
    812 static size_t ap_write_wsc_ie(struct ap_state *ap,
    813 				enum mpdu_management_subtype type,
    814 				const struct mmpdu_header *client_frame,
    815 				size_t client_frame_len,
    816 				uint8_t *out_buf)
    817 {
    818 	uint8_t *wsc_data;
    819 	size_t wsc_data_size;
    820 	uint8_t *wsc_ie;
    821 	size_t wsc_ie_size;
    822 	size_t len = 0;
    823 
    824 	/* WSC IE */
    825 	if (type == MPDU_MANAGEMENT_SUBTYPE_PROBE_RESPONSE && client_frame) {
    826 		const uint8_t *from = client_frame->address_2;
    827 		struct wsc_probe_response wsc_pr = {};
    828 		const struct mmpdu_probe_request *req =
    829 			mmpdu_body(client_frame);
    830 		size_t req_ies_len = (void *) client_frame + client_frame_len -
    831 			(void *) req->ies;
    832 		ssize_t req_wsc_data_size;
    833 
    834 		/*
    835 		 * Process the client Probe Request WSC IE first as it may
    836 		 * cause us to exit "active PBC mode" and that will be
    837 		 * immediately reflected in our Probe Response WSC IE.
    838 		 */
    839 		wsc_data = ie_tlv_extract_wsc_payload(req->ies, req_ies_len,
    840 							&req_wsc_data_size);
    841 		if (wsc_data) {
    842 			ap_process_wsc_probe_req(ap, from, wsc_data,
    843 							req_wsc_data_size);
    844 			l_free(wsc_data);
    845 		}
    846 
    847 		wsc_pr.version2 = true;
    848 		wsc_pr.state = WSC_STATE_CONFIGURED;
    849 
    850 		if (ap->wsc_pbc_timeout) {
    851 			wsc_pr.selected_registrar = true;
    852 			wsc_pr.device_password_id = ap->wsc_dpid;
    853 			wsc_pr.selected_reg_config_methods =
    854 				WSC_CONFIGURATION_METHOD_PUSH_BUTTON;
    855 		}
    856 
    857 		wsc_pr.response_type = WSC_RESPONSE_TYPE_AP;
    858 		memcpy(wsc_pr.uuid_e, ap->wsc_uuid_r, sizeof(wsc_pr.uuid_e));
    859 		wsc_pr.primary_device_type = ap->wsc_primary_device_type;
    860 
    861 		if (ap->wsc_name[0] != '\0')
    862 			l_strlcpy(wsc_pr.device_name, ap->wsc_name,
    863 					sizeof(wsc_pr.device_name));
    864 
    865 		wsc_pr.config_methods =
    866 			WSC_CONFIGURATION_METHOD_PUSH_BUTTON;
    867 
    868 		ap_write_authorized_macs(ap, sizeof(wsc_pr.authorized_macs),
    869 						wsc_pr.authorized_macs);
    870 		wsc_data = wsc_build_probe_response(&wsc_pr, &wsc_data_size);
    871 	} else if (type == MPDU_MANAGEMENT_SUBTYPE_BEACON) {
    872 		struct wsc_beacon wsc_beacon = {};
    873 
    874 		wsc_beacon.version2 = true;
    875 		wsc_beacon.state = WSC_STATE_CONFIGURED;
    876 
    877 		if (ap->wsc_pbc_timeout) {
    878 			wsc_beacon.selected_registrar = true;
    879 			wsc_beacon.device_password_id = ap->wsc_dpid;
    880 			wsc_beacon.selected_reg_config_methods =
    881 				WSC_CONFIGURATION_METHOD_PUSH_BUTTON;
    882 		}
    883 
    884 		ap_write_authorized_macs(ap, sizeof(wsc_beacon.authorized_macs),
    885 						wsc_beacon.authorized_macs);
    886 		wsc_data = wsc_build_beacon(&wsc_beacon, &wsc_data_size);
    887 	} else if (L_IN_SET(type, MPDU_MANAGEMENT_SUBTYPE_ASSOCIATION_RESPONSE,
    888 			MPDU_MANAGEMENT_SUBTYPE_REASSOCIATION_RESPONSE)) {
    889 		const uint8_t *from = client_frame->address_2;
    890 		struct wsc_association_response wsc_resp = {};
    891 		struct sta_state *sta =
    892 			l_queue_find(ap->sta_states, ap_sta_match_addr, from);
    893 
    894 		if (!sta || sta->assoc_rsne)
    895 			return 0;
    896 
    897 		wsc_resp.response_type = WSC_RESPONSE_TYPE_AP;
    898 		wsc_resp.version2 = sta->wsc_v2;
    899 
    900 		wsc_data = wsc_build_association_response(&wsc_resp,
    901 								&wsc_data_size);
    902 	} else
    903 		return 0;
    904 
    905 	if (!wsc_data) {
    906 		l_error("wsc_build_<mgmt-subtype> error (stype 0x%x)", type);
    907 		return 0;
    908 	}
    909 
    910 	wsc_ie = ie_tlv_encapsulate_wsc_payload(wsc_data, wsc_data_size,
    911 						&wsc_ie_size);
    912 	l_free(wsc_data);
    913 
    914 	if (!wsc_ie) {
    915 		l_error("ie_tlv_encapsulate_wsc_payload error (stype 0x%x)",
    916 			type);
    917 		return 0;
    918 	}
    919 
    920 	memcpy(out_buf + len, wsc_ie, wsc_ie_size);
    921 	len += wsc_ie_size;
    922 	l_free(wsc_ie);
    923 
    924 	return len;
    925 }
    926 
    927 static size_t ap_build_supported_rates(struct ap_state *ap,
    928 					uint8_t *rates)
    929 {
    930 	uint32_t minr, maxr, count, r;
    931 
    932 	minr = l_uintset_find_min(ap->rates);
    933 	maxr = l_uintset_find_max(ap->rates);
    934 	count = 0;
    935 	for (r = minr; r <= maxr && count < 8; r++)
    936 		if (l_uintset_contains(ap->rates, r)) {
    937 			uint8_t flag = 0;
    938 
    939 			/* Mark only the lowest rate as Basic Rate */
    940 			if (count == 0)
    941 				flag = 0x80;
    942 
    943 			*rates++ = r | flag;
    944 			count++;
    945 		}
    946 
    947 	return count;
    948 }
    949 
    950 static size_t ap_get_extra_ies_len(struct ap_state *ap,
    951 					enum mpdu_management_subtype type,
    952 					const struct mmpdu_header *client_frame,
    953 					size_t client_frame_len)
    954 {
    955 	size_t len = 0;
    956 
    957 	len += ap_get_wsc_ie_len(ap, type, client_frame, client_frame_len);
    958 
    959 	/* WMM IE length */
    960 	if (ap->supports_ht)
    961 		len += 50;
    962 
    963 	if (ap->ops->get_extra_ies_len)
    964 		len += ap->ops->get_extra_ies_len(type, client_frame,
    965 							client_frame_len,
    966 							ap->user_data);
    967 
    968 	return len;
    969 }
    970 
    971 /* WMM Specification 2.2.2 WMM Parameter Element */
    972 struct ap_wmm_ac_record {
    973 #if defined(__LITTLE_ENDIAN_BITFIELD)
    974 	uint8_t aifsn : 4;
    975 	uint8_t acm : 1;
    976 	uint8_t aci : 2;
    977 	uint8_t reserved : 1;
    978 	uint8_t ecw_min : 4;
    979 	uint8_t ecw_max : 4;
    980 #elif defined (__BIG_ENDIAN_BITFIELD)
    981 	uint8_t reserved : 1;
    982 	uint8_t aci : 2;
    983 	uint8_t acm : 1;
    984 	uint8_t aifsn : 4;
    985 	uint8_t ecw_max : 4;
    986 	uint8_t ecw_min : 4;
    987 #else
    988 #error "Please fix <asm/byteorder.h"
    989 #endif
    990 	__le16 txop_limit;
    991 } __attribute__((packed));
    992 
    993 static size_t ap_write_wmm_ies(struct ap_state *ap, uint8_t *out_buf)
    994 {
    995 	unsigned int i;
    996 	struct wiphy *wiphy = netdev_get_wiphy(ap->netdev);
    997 
    998 	/*
    999 	 * Linux kernel requires APs include WMM Information element if
   1000 	 * supporting HT/VHT/etc.
   1001 	 *
   1002 	 * The only value we can actually get from the kernel is UAPSD. The
   1003 	 * remaining values (AC parameter records) are made up or defaults
   1004 	 * defined in the WMM spec are used.
   1005 	 */
   1006 	*out_buf++ = IE_TYPE_VENDOR_SPECIFIC;
   1007 	*out_buf++ = 24;
   1008 	memcpy(out_buf, microsoft_oui, sizeof(microsoft_oui));
   1009 	out_buf += sizeof(microsoft_oui);
   1010 	*out_buf++ = 2; /* WMM OUI Type */
   1011 	*out_buf++ = 1; /* WMM Parameter subtype */
   1012 	*out_buf++ = 1; /* WMM Version */
   1013 	*out_buf++ = wiphy_supports_uapsd(wiphy) ? 1 << 7 : 0;
   1014 	*out_buf++ = 0; /* reserved */
   1015 
   1016 	for (i = 0; i < 4; i++) {
   1017 		struct ap_wmm_ac_record ac = { 0 };
   1018 
   1019 		ac.aifsn = 2;
   1020 		ac.acm = 0;
   1021 		ac.aci = i;
   1022 		ac.ecw_min = 1;
   1023 		ac.ecw_max = 15;
   1024 		l_put_le16(0, &ac.txop_limit);
   1025 
   1026 		memcpy(out_buf + (i * 4), &ac, sizeof(struct ap_wmm_ac_record));
   1027 	}
   1028 
   1029 	return 26;
   1030 }
   1031 
   1032 static size_t ap_write_extra_ies(struct ap_state *ap,
   1033 					enum mpdu_management_subtype type,
   1034 					const struct mmpdu_header *client_frame,
   1035 					size_t client_frame_len,
   1036 					uint8_t *out_buf)
   1037 {
   1038 	size_t len = 0;
   1039 
   1040 	len += ap_write_wsc_ie(ap, type, client_frame, client_frame_len,
   1041 				out_buf + len);
   1042 
   1043 	if (ap->supports_ht)
   1044 		len += ap_write_wmm_ies(ap, out_buf + len);
   1045 
   1046 	if (ap->ops->write_extra_ies)
   1047 		len += ap->ops->write_extra_ies(type,
   1048 						client_frame, client_frame_len,
   1049 						out_buf + len, ap->user_data);
   1050 
   1051 	return len;
   1052 }
   1053 
   1054 static size_t ap_build_ht_capability(struct ap_state *ap, uint8_t *buf)
   1055 {
   1056 	struct wiphy *wiphy = netdev_get_wiphy(ap->netdev);
   1057 	size_t ht_capa_len;
   1058 	const uint8_t *ht_capa = wiphy_get_ht_capabilities(wiphy, ap->band,
   1059 								&ht_capa_len);
   1060 
   1061 	memcpy(buf, ht_capa, ht_capa_len);
   1062 
   1063 	return ht_capa_len;
   1064 }
   1065 
   1066 static size_t ap_build_ht_operation(struct ap_state *ap, uint8_t *buf)
   1067 {
   1068 	const struct l_queue_entry *e;
   1069 	unsigned int non_ht = false;
   1070 	unsigned int non_greenfield = false;
   1071 
   1072 	memset(buf, 0, 22);
   1073 	*buf++ = ap->channel;
   1074 
   1075 	/*
   1076 	 * If 40MHz set 'Secondary Channel Offset' (bits 0-1) to above/below
   1077 	 * and set 'STA Channel Width' (bit 2) to indicate non-20Mhz.
   1078 	 */
   1079 	if (ap->chandef.channel_width == BAND_CHANDEF_WIDTH_20)
   1080 		goto check_stas;
   1081 	else if (ap->chandef.frequency < ap->chandef.center1_frequency)
   1082 		*buf |= 1 & 0x3;
   1083 	else
   1084 		*buf |= 3 & 0x3;
   1085 
   1086 	*buf |= 1 << 2;
   1087 
   1088 check_stas:
   1089 	for (e = l_queue_get_entries(ap->sta_states); e; e = e->next) {
   1090 		struct sta_state *sta = e->data;
   1091 
   1092 		if (!sta->associated)
   1093 			continue;
   1094 
   1095 		if (!sta->ht_support)
   1096 			non_ht = true;
   1097 		else if (!sta->ht_greenfield)
   1098 			non_greenfield = true;
   1099 	}
   1100 
   1101 	if (non_greenfield)
   1102 		set_bit(buf, 10);
   1103 
   1104 	if (non_ht)
   1105 		set_bit(buf, 12);
   1106 
   1107 	/*
   1108 	 * TODO: Basic MCS set for all associated STAs
   1109 	 */
   1110 
   1111 	return 22;
   1112 }
   1113 
   1114 /*
   1115  * Build a Beacon frame or a Probe Response frame's header and body until
   1116  * the TIM IE.  Except for the optional TIM IE which is inserted by the
   1117  * kernel when needed, our contents for both frames are the same.
   1118  * See Beacon format in 8.3.3.2 and Probe Response format in 8.3.3.10.
   1119  *
   1120  * 802.11-2016, Section 9.4.2.1:
   1121  * "The frame body components specified for many management subtypes result
   1122  * in elements ordered by ascending values of the Element ID field and then
   1123  * the Element ID Extension field (when present), with the exception of the
   1124  * MIC Management element (9.4.2.55)."
   1125  */
   1126 static size_t ap_build_beacon_pr_head(struct ap_state *ap,
   1127 					enum mpdu_management_subtype stype,
   1128 					const uint8_t *dest, uint8_t *out_buf,
   1129 					size_t out_len)
   1130 {
   1131 	struct mmpdu_header *mpdu = (void *) out_buf;
   1132 	uint16_t capability = IE_BSS_CAP_ESS | IE_BSS_CAP_PRIVACY;
   1133 	const uint8_t *bssid = netdev_get_address(ap->netdev);
   1134 	size_t len;
   1135 	struct ie_tlv_builder builder;
   1136 
   1137 	memset(mpdu, 0, 36); /* Zero out header + non-IE fields */
   1138 
   1139 	/* Header */
   1140 	mpdu->fc.protocol_version = 0;
   1141 	mpdu->fc.type = MPDU_TYPE_MANAGEMENT;
   1142 	mpdu->fc.subtype = stype;
   1143 	memcpy(mpdu->address_1, dest, 6);	/* DA */
   1144 	memcpy(mpdu->address_2, bssid, 6);	/* SA */
   1145 	memcpy(mpdu->address_3, bssid, 6);	/* BSSID */
   1146 
   1147 	/* Body non-IE fields */
   1148 	l_put_le16(ap->beacon_interval, out_buf + 32);	/* Beacon Interval */
   1149 	l_put_le16(capability, out_buf + 34);		/* Capability Info */
   1150 
   1151 	ie_tlv_builder_init(&builder, out_buf + 36, out_len - 36);
   1152 
   1153 	/* SSID IE */
   1154 	ie_tlv_builder_next(&builder, IE_TYPE_SSID);
   1155 	ie_tlv_builder_set_data(&builder, ap->ssid, strlen(ap->ssid));
   1156 
   1157 	/* Supported Rates IE */
   1158 	ie_tlv_builder_next(&builder, IE_TYPE_SUPPORTED_RATES);
   1159 	len = ap_build_supported_rates(ap, ie_tlv_builder_get_data(&builder));
   1160 	ie_tlv_builder_set_length(&builder, len);
   1161 
   1162 	/* DSSS Parameter Set IE for DSSS, HR, ERP and HT PHY rates */
   1163 	ie_tlv_builder_next(&builder, IE_TYPE_DSSS_PARAMETER_SET);
   1164 	ie_tlv_builder_set_data(&builder, &ap->channel, 1);
   1165 
   1166 	if (ap->supports_ht) {
   1167 		ie_tlv_builder_next(&builder, IE_TYPE_HT_CAPABILITIES);
   1168 		len = ap_build_ht_capability(ap,
   1169 					ie_tlv_builder_get_data(&builder));
   1170 		ie_tlv_builder_set_length(&builder, len);
   1171 
   1172 		ie_tlv_builder_next(&builder, IE_TYPE_HT_OPERATION);
   1173 		len = ap_build_ht_operation(ap,
   1174 					ie_tlv_builder_get_data(&builder));
   1175 		ie_tlv_builder_set_length(&builder, len);
   1176 	}
   1177 
   1178 	ie_tlv_builder_finalize(&builder, &out_len);
   1179 	return 36 + out_len;
   1180 }
   1181 
   1182 static size_t ap_build_country_ie(struct ap_state *ap, uint8_t *out_buf,
   1183 					size_t buf_len)
   1184 {
   1185 	size_t len;
   1186 	size_t i;
   1187 	int spacing;
   1188 	uint8_t *pos = out_buf;
   1189 	uint8_t nchans = 1;
   1190 	struct wiphy *wiphy = netdev_get_wiphy(ap->netdev);
   1191 	const struct band_freq_attrs *last = NULL;
   1192 	const struct band_freq_attrs *list = wiphy_get_frequency_info_list(
   1193 							wiphy, ap->band, &len);
   1194 
   1195 	if (!list || wiphy_country_is_unknown(wiphy))
   1196 		return 0;
   1197 
   1198 	if (L_WARN_ON(buf_len < 5))
   1199 		goto no_space;
   1200 
   1201 	*pos++ = IE_TYPE_COUNTRY;
   1202 	/* length not yet known */
   1203 	pos++;
   1204 
   1205 	wiphy_get_reg_domain_country(wiphy, (char *)pos);
   1206 	pos += 2;
   1207 	*pos++ = ' ';
   1208 
   1209 	buf_len -= 5;
   1210 
   1211 	if (ap->band == BAND_FREQ_2_4_GHZ)
   1212 		spacing = 1;
   1213 	else
   1214 		spacing = 4;
   1215 
   1216 	/*
   1217 	 * Construct a list of subband triplet entries. Each entry contains a
   1218 	 * starting channel and a number of channels which are spaced evenly
   1219 	 * and use the same TX power. Any deviation from this results in a new
   1220 	 * channel group.
   1221 	 *
   1222 	 * TODO: 6GHz requires operating triplets, not subband triplets.
   1223 	 */
   1224 	for (i = 0; i < len; i++) {
   1225 		const struct band_freq_attrs *attr = &list[i];
   1226 
   1227 		if (!attr->supported || attr->disabled)
   1228 			continue;
   1229 
   1230 		if (!last) {
   1231 			/* Room for one complete triplet */
   1232 			if (L_WARN_ON(buf_len < 3))
   1233 				goto no_space;
   1234 
   1235 			*pos++ = i;
   1236 			last = attr;
   1237 			continue;
   1238 		}
   1239 
   1240 		if (spacing != attr - last ||
   1241 					attr->tx_power != last->tx_power) {
   1242 			/* finish current group */
   1243 			*pos++ = nchans;
   1244 			*pos++ = last->tx_power;
   1245 			buf_len -= 3;
   1246 
   1247 			/* start a new group */
   1248 			if (L_WARN_ON(buf_len < 3))
   1249 				goto no_space;
   1250 
   1251 			*pos++ = i;
   1252 			nchans = 1;
   1253 		} else
   1254 			nchans++;
   1255 
   1256 		last = attr;
   1257 	}
   1258 
   1259 	/* finish final group */
   1260 	if (last) {
   1261 		*pos++ = nchans;
   1262 		*pos++ = last->tx_power;
   1263 	}
   1264 
   1265 	len = pos - out_buf - 2;
   1266 
   1267 	/* Pad to even byte */
   1268 	if (len & 1) {
   1269 		if (L_WARN_ON(buf_len < 1))
   1270 			goto no_space;
   1271 
   1272 		*pos++ = 0;
   1273 		len++;
   1274 	}
   1275 
   1276 	out_buf[1] = len;
   1277 
   1278 	return out_buf[1] + 2;
   1279 
   1280 no_space:
   1281 	return 0;
   1282 }
   1283 
   1284 /* Beacon / Probe Response frame portion after the TIM IE */
   1285 static size_t ap_build_beacon_pr_tail(struct ap_state *ap,
   1286 					enum mpdu_management_subtype stype,
   1287 					const struct mmpdu_header *req,
   1288 					size_t req_len, uint8_t *out_buf,
   1289 					size_t buf_len)
   1290 {
   1291 	size_t len;
   1292 	struct ie_rsn_info rsn;
   1293 
   1294 	len = ap_build_country_ie(ap, out_buf, buf_len);
   1295 
   1296 	/* RSNE */
   1297 	ap_set_rsn_info(ap, &rsn);
   1298 	if (!ie_build_rsne(&rsn, out_buf + len))
   1299 		return 0;
   1300 	len += 2 + out_buf[len + 1];
   1301 
   1302 	len += ap_write_extra_ies(ap, stype, req, req_len, out_buf + len);
   1303 	return len;
   1304 }
   1305 
   1306 static void ap_set_beacon_cb(struct l_genl_msg *msg, void *user_data)
   1307 {
   1308 	int error = l_genl_msg_get_error(msg);
   1309 
   1310 	if (error < 0)
   1311 		l_error("SET_BEACON failed: %s (%i)", strerror(-error), -error);
   1312 }
   1313 
   1314 void ap_update_beacon(struct ap_state *ap)
   1315 {
   1316 	struct l_genl_msg *cmd;
   1317 	uint8_t head[256];
   1318 	size_t tail_len = 256 + ap_get_extra_ies_len(ap,
   1319 						MPDU_MANAGEMENT_SUBTYPE_BEACON,
   1320 						NULL, 0);
   1321 	L_AUTO_FREE_VAR(uint8_t *, tail) = malloc(tail_len);
   1322 	size_t head_len;
   1323 	uint64_t wdev_id = netdev_get_wdev_id(ap->netdev);
   1324 	static const uint8_t bcast_addr[6] = {
   1325 		0xff, 0xff, 0xff, 0xff, 0xff, 0xff
   1326 	};
   1327 
   1328 	if (L_WARN_ON(!ap->started))
   1329 		return;
   1330 
   1331 	head_len = ap_build_beacon_pr_head(ap, MPDU_MANAGEMENT_SUBTYPE_BEACON,
   1332 						bcast_addr, head, sizeof(head));
   1333 	tail_len = ap_build_beacon_pr_tail(ap, MPDU_MANAGEMENT_SUBTYPE_BEACON,
   1334 						NULL, 0, tail, tail_len);
   1335 	if (L_WARN_ON(!head_len || !tail_len))
   1336 		return;
   1337 
   1338 	cmd = l_genl_msg_new_sized(NL80211_CMD_SET_BEACON,
   1339 					32 + head_len + tail_len);
   1340 	l_genl_msg_append_attr(cmd, NL80211_ATTR_WDEV, 8, &wdev_id);
   1341 	l_genl_msg_append_attr(cmd, NL80211_ATTR_BEACON_HEAD, head_len, head);
   1342 	l_genl_msg_append_attr(cmd, NL80211_ATTR_BEACON_TAIL, tail_len, tail);
   1343 	l_genl_msg_append_attr(cmd, NL80211_ATTR_IE, 0, "");
   1344 	l_genl_msg_append_attr(cmd, NL80211_ATTR_IE_PROBE_RESP, 0, "");
   1345 	l_genl_msg_append_attr(cmd, NL80211_ATTR_IE_ASSOC_RESP, 0, "");
   1346 
   1347 	if (l_genl_family_send(ap->nl80211, cmd, ap_set_beacon_cb, NULL, NULL))
   1348 		return;
   1349 
   1350 	l_genl_msg_unref(cmd);
   1351 	l_error("Issuing SET_BEACON failed");
   1352 }
   1353 
   1354 static uint32_t ap_send_mgmt_frame(struct ap_state *ap,
   1355 					const struct mmpdu_header *frame,
   1356 					size_t frame_len,
   1357 					frame_xchg_cb_t callback,
   1358 					void *user_data)
   1359 {
   1360 	uint32_t ch_freq = band_channel_to_freq(ap->channel, ap->band);
   1361 	uint64_t wdev_id = netdev_get_wdev_id(ap->netdev);
   1362 	struct iovec iov[2];
   1363 
   1364 	iov[0].iov_base = (void *) frame;
   1365 	iov[0].iov_len = frame_len;
   1366 	iov[1].iov_base = NULL;
   1367 	return frame_xchg_start(wdev_id, iov, ch_freq, 0, 0, 0, 0,
   1368 					callback, user_data, NULL, NULL);
   1369 }
   1370 
   1371 #define IP4_FROM_STR(str)						\
   1372 	(__extension__ ({						\
   1373 		struct in_addr ia;					\
   1374 		inet_pton(AF_INET, str, &ia) == 1 ? ia.s_addr : 0;	\
   1375 	}))
   1376 
   1377 static void ap_start_handshake(struct sta_state *sta, bool use_eapol_start,
   1378 				const uint8_t *gtk_rsc)
   1379 {
   1380 	struct ap_state *ap = sta->ap;
   1381 	const uint8_t *own_addr = netdev_get_address(ap->netdev);
   1382 	struct ie_rsn_info rsn;
   1383 	uint8_t bss_rsne[64];
   1384 
   1385 	handshake_state_set_ssid(sta->hs, (void *) ap->ssid, strlen(ap->ssid));
   1386 	handshake_state_set_authenticator_address(sta->hs, own_addr);
   1387 	handshake_state_set_supplicant_address(sta->hs, sta->addr);
   1388 
   1389 	ap_set_rsn_info(ap, &rsn);
   1390 	/*
   1391 	 * Note: This assumes the length that ap_set_rsn_info() requires. If
   1392 	 * ap_set_rsn_info() changes then this will need to be updated.
   1393 	 */
   1394 	ie_build_rsne(&rsn, bss_rsne);
   1395 	handshake_state_set_authenticator_ie(sta->hs, bss_rsne);
   1396 
   1397 	if (gtk_rsc)
   1398 		handshake_state_set_gtk(sta->hs, sta->ap->gtk,
   1399 					sta->ap->gtk_index, gtk_rsc);
   1400 
   1401 	if (ap->netconfig_dhcp)
   1402 		sta->hs->support_ip_allocation = true;
   1403 
   1404 	sta->sm = eapol_sm_new(sta->hs);
   1405 	if (!sta->sm) {
   1406 		ap_stop_handshake(sta);
   1407 		l_error("could not create sm object");
   1408 		goto error;
   1409 	}
   1410 
   1411 	eapol_sm_set_listen_interval(sta->sm, sta->listen_interval);
   1412 	eapol_sm_set_use_eapol_start(sta->sm, use_eapol_start);
   1413 
   1414 	eapol_register(sta->sm);
   1415 	eapol_start(sta->sm);
   1416 
   1417 	return;
   1418 
   1419 error:
   1420 	ap_del_station(sta, MMPDU_REASON_CODE_UNSPECIFIED, true);
   1421 }
   1422 
   1423 static bool ap_sta_get_dhcp4_lease(struct sta_state *sta)
   1424 {
   1425 	if (sta->ip_alloc_lease)
   1426 		return true;
   1427 
   1428 	if (!sta->ap->netconfig_dhcp)
   1429 		return false;
   1430 
   1431 	sta->ip_alloc_lease = l_dhcp_server_discover(sta->ap->netconfig_dhcp,
   1432 							0, NULL, sta->addr);
   1433 	if (!sta->ip_alloc_lease) {
   1434 		l_error("l_dhcp_server_discover() failed, see IWD_DHCP_DEBUG "
   1435 			"output");
   1436 		return false;
   1437 	}
   1438 
   1439 	return true;
   1440 }
   1441 
   1442 static void ap_handshake_event(struct handshake_state *hs,
   1443 		enum handshake_event event, void *user_data, ...)
   1444 {
   1445 	struct sta_state *sta = user_data;
   1446 	struct ap_state *ap = sta->ap;
   1447 	va_list args;
   1448 
   1449 	va_start(args, user_data);
   1450 
   1451 	switch (event) {
   1452 	case HANDSHAKE_EVENT_COMPLETE:
   1453 		if (sta->ip_alloc_lease) {
   1454 			if (hs->support_ip_allocation)
   1455 				sta->ip_alloc_sent = true;
   1456 
   1457 			/*
   1458 			 * Move the lease from offered to active state if the
   1459 			 * client has actually used it.  In any case drop our
   1460 			 * reference to the lease, the server owns the lease
   1461 			 * and if we want to keep our reference we'd need to
   1462 			 * react to relevant server events.
   1463 			 */
   1464 			if (sta->ip_alloc_sent)
   1465 				l_dhcp_server_request(ap->netconfig_dhcp,
   1466 							sta->ip_alloc_lease);
   1467 
   1468 			sta->ip_alloc_lease = NULL;
   1469 		}
   1470 
   1471 		ap_new_rsna(sta);
   1472 		break;
   1473 	case HANDSHAKE_EVENT_FAILED:
   1474 		netdev_handshake_failed(hs, va_arg(args, int));
   1475 		/* fall through */
   1476 	case HANDSHAKE_EVENT_SETTING_KEYS_FAILED:
   1477 		sta->sm = NULL;
   1478 		ap_remove_sta(sta);
   1479 		break;
   1480 	case HANDSHAKE_EVENT_P2P_IP_REQUEST:
   1481 	{
   1482 		char own_addr_str[INET_ADDRSTRLEN];
   1483 
   1484 		if (!ap_sta_get_dhcp4_lease(sta))
   1485 			break;
   1486 
   1487 		sta->hs->client_ip_addr =
   1488 			l_dhcp_lease_get_address_u32(sta->ip_alloc_lease);
   1489 		sta->hs->subnet_mask =
   1490 			l_dhcp_lease_get_netmask_u32(sta->ip_alloc_lease);
   1491 		l_rtnl_address_get_address(ap->netconfig_addr4, own_addr_str);
   1492 		sta->hs->go_ip_addr = IP4_FROM_STR(own_addr_str);
   1493 		break;
   1494 	}
   1495 	case HANDSHAKE_EVENT_REKEY_COMPLETE:
   1496 		ap_set_sta_rekey_timer(ap, sta);
   1497 		break;
   1498 	default:
   1499 		break;
   1500 	}
   1501 
   1502 	va_end(args);
   1503 }
   1504 
   1505 static void ap_start_rsna(struct sta_state *sta, const uint8_t *gtk_rsc)
   1506 {
   1507 	/* this handshake setup assumes PSK network */
   1508 	sta->hs = netdev_handshake_state_new(sta->ap->netdev);
   1509 	handshake_state_set_authenticator(sta->hs, true);
   1510 	handshake_state_set_event_func(sta->hs, ap_handshake_event, sta);
   1511 	handshake_state_set_supplicant_ie(sta->hs, sta->assoc_rsne);
   1512 	handshake_state_set_pmk(sta->hs, sta->ap->psk, 32);
   1513 	ap_start_handshake(sta, false, gtk_rsc);
   1514 }
   1515 
   1516 static void ap_gtk_query_cb(struct l_genl_msg *msg, void *user_data)
   1517 {
   1518 	struct sta_state *sta = user_data;
   1519 	const void *gtk_rsc;
   1520 	uint8_t zero_gtk_rsc[6];
   1521 	int err;
   1522 
   1523 	sta->gtk_query_cmd_id = 0;
   1524 
   1525 	err = l_genl_msg_get_error(msg);
   1526 	if (err == -ENOTSUP)
   1527 		goto zero_rsc;
   1528 	else if (err < 0)
   1529 		goto error;
   1530 
   1531 	gtk_rsc = nl80211_parse_get_key_seq(msg);
   1532 	if (!gtk_rsc) {
   1533 zero_rsc:
   1534 		memset(zero_gtk_rsc, 0, 6);
   1535 		gtk_rsc = zero_gtk_rsc;
   1536 	}
   1537 
   1538 	ap_start_rsna(sta, gtk_rsc);
   1539 	return;
   1540 
   1541 error:
   1542 	ap_del_station(sta, MMPDU_REASON_CODE_UNSPECIFIED, true);
   1543 }
   1544 
   1545 static void ap_stop_handshake_schedule(struct sta_state *sta)
   1546 {
   1547 	if (sta->stop_handshake_work)
   1548 		return;
   1549 
   1550 	sta->stop_handshake_work = l_idle_create(ap_stop_handshake_work,
   1551 							sta, NULL);
   1552 }
   1553 
   1554 static void ap_wsc_handshake_event(struct handshake_state *hs,
   1555 		enum handshake_event event, void *user_data, ...)
   1556 {
   1557 	struct sta_state *sta = user_data;
   1558 	va_list args;
   1559 	struct ap_event_registration_success_data event_data;
   1560 	struct ap_pbc_record_expiry_data expiry_data;
   1561 
   1562 	va_start(args, user_data);
   1563 
   1564 	switch (event) {
   1565 	case HANDSHAKE_EVENT_FAILED:
   1566 		sta->sm = NULL;
   1567 		ap_stop_handshake_schedule(sta);
   1568 		/*
   1569 		 * Some diagrams in WSC v2.0.5 indicate we should
   1570 		 * automatically deauthenticate the Enrollee.  The text
   1571 		 * generally indicates the Enrollee may disassociate
   1572 		 * meaning that we should neither deauthenticate nor
   1573 		 * disassociate it automatically.  Some places indicate
   1574 		 * that the enrollee can send a new EAPoL-Start right away
   1575 		 * on an unsuccessful registration, we don't implement
   1576 		 * this for now.  STA remains associated but not authorized
   1577 		 * and basically has no other option than to re-associate
   1578 		 * or disassociate/deauthenticate.
   1579 		 */
   1580 		break;
   1581 	case HANDSHAKE_EVENT_EAP_NOTIFY:
   1582 		if (va_arg(args, unsigned int) != EAP_WSC_EVENT_CREDENTIAL_SENT)
   1583 			break;
   1584 
   1585 		/*
   1586 		 * WSC v2.0.5 Section 11.3:
   1587 		 * "If the Registrar successfully runs the PBC method to
   1588 		 * completion with an Enrollee, that Enrollee's probe requests
   1589 		 * are removed from the Monitor Time check the next time the
   1590 		 * Registrar's PBC button is pressed."
   1591 		 */
   1592 		expiry_data.min_time = 0;
   1593 		expiry_data.mac = sta->addr;
   1594 		l_queue_foreach_remove(sta->ap->wsc_pbc_probes,
   1595 					ap_wsc_pbc_record_expire,
   1596 					&expiry_data);
   1597 
   1598 		event_data.mac = sta->addr;
   1599 		ap_event(sta->ap, AP_EVENT_REGISTRATION_SUCCESS, &event_data);
   1600 		break;
   1601 	default:
   1602 		break;
   1603 	}
   1604 
   1605 	va_end(args);
   1606 }
   1607 
   1608 static void ap_start_eap_wsc(struct sta_state *sta)
   1609 {
   1610 	struct ap_state *ap = sta->ap;
   1611 
   1612 	/*
   1613 	 * WSC v2.0.5 Section 8.2: "The AP is allowed to send
   1614 	 * EAP-Request/Identity to the station before EAPOL-Start is received
   1615 	 * if a WSC IE is included in the (re)association request and the
   1616 	 * WSC IE is version 2.0 or higher.
   1617 	 */
   1618 	bool wait_for_eapol_start = !sta->wsc_v2;
   1619 
   1620 	sta->wsc_settings = l_settings_new();
   1621 	l_settings_set_string(sta->wsc_settings, "Security", "EAP-Method",
   1622 				"WSC-R");
   1623 	l_settings_set_string(sta->wsc_settings, "WSC", "EnrolleeMAC",
   1624 				util_address_to_string(sta->addr));
   1625 	l_settings_set_bytes(sta->wsc_settings, "WSC", "UUID-R",
   1626 				ap->wsc_uuid_r, 16);
   1627 	l_settings_set_bytes(sta->wsc_settings, "WSC", "UUID-E",
   1628 				sta->wsc_uuid_e, 16);
   1629 	l_settings_set_uint(sta->wsc_settings, "WSC", "RFBand",
   1630 				WSC_RF_BAND_2_4_GHZ);
   1631 	l_settings_set_uint(sta->wsc_settings, "WSC", "ConfigurationMethods",
   1632 				WSC_CONFIGURATION_METHOD_PUSH_BUTTON);
   1633 	l_settings_set_string(sta->wsc_settings, "WSC", "WPA2-SSID", ap->ssid);
   1634 
   1635 	if (ap->passphrase[0])
   1636 		l_settings_set_string(sta->wsc_settings,
   1637 					"WSC", "WPA2-Passphrase",
   1638 					ap->passphrase);
   1639 	else
   1640 		l_settings_set_bytes(sta->wsc_settings,
   1641 					"WSC", "WPA2-PSK", ap->psk, 32);
   1642 
   1643 	sta->hs = netdev_handshake_state_new(ap->netdev);
   1644 	handshake_state_set_authenticator(sta->hs, true);
   1645 	handshake_state_set_event_func(sta->hs, ap_wsc_handshake_event, sta);
   1646 	handshake_state_set_8021x_config(sta->hs, sta->wsc_settings);
   1647 
   1648 	ap_start_handshake(sta, wait_for_eapol_start, NULL);
   1649 }
   1650 
   1651 static struct l_genl_msg *ap_build_cmd_del_key(struct ap_state *ap)
   1652 {
   1653 	uint32_t ifindex = netdev_get_ifindex(ap->netdev);
   1654 	struct l_genl_msg *msg;
   1655 
   1656 	msg = l_genl_msg_new_sized(NL80211_CMD_DEL_KEY, 128);
   1657 
   1658 	l_genl_msg_append_attr(msg, NL80211_ATTR_IFINDEX, 4, &ifindex);
   1659 	l_genl_msg_enter_nested(msg, NL80211_ATTR_KEY);
   1660 	l_genl_msg_append_attr(msg, NL80211_KEY_IDX, 1, &ap->gtk_index);
   1661 	l_genl_msg_leave_nested(msg);
   1662 
   1663 	return msg;
   1664 }
   1665 
   1666 static struct l_genl_msg *ap_build_cmd_new_station(struct sta_state *sta)
   1667 {
   1668 	struct l_genl_msg *msg;
   1669 	uint32_t ifindex = netdev_get_ifindex(sta->ap->netdev);
   1670 	struct nl80211_sta_flag_update flags = {
   1671 		.mask = (1 << NL80211_STA_FLAG_AUTHORIZED) |
   1672 			(1 << NL80211_STA_FLAG_MFP),
   1673 		.set = (1 << NL80211_STA_FLAG_AUTHENTICATED) |
   1674 			(1 << NL80211_STA_FLAG_ASSOCIATED),
   1675 	};
   1676 
   1677 	/*
   1678 	 * Without this feature nl80211 rejects NEW_STATION if the mask contains
   1679 	 * auth/assoc flags
   1680 	 */
   1681 	if (wiphy_has_feature(netdev_get_wiphy(sta->ap->netdev),
   1682 				NL80211_FEATURE_FULL_AP_CLIENT_STATE))
   1683 		flags.mask |= (1 << NL80211_STA_FLAG_ASSOCIATED) |
   1684 				(1 << NL80211_STA_FLAG_AUTHENTICATED);
   1685 
   1686 	msg = l_genl_msg_new_sized(NL80211_CMD_NEW_STATION, 300);
   1687 
   1688 	l_genl_msg_append_attr(msg, NL80211_ATTR_IFINDEX, 4, &ifindex);
   1689 	l_genl_msg_append_attr(msg, NL80211_ATTR_MAC, 6, sta->addr);
   1690 	l_genl_msg_append_attr(msg, NL80211_ATTR_STA_FLAGS2, 8, &flags);
   1691 
   1692 	return msg;
   1693 }
   1694 
   1695 static void ap_gtk_op_cb(struct l_genl_msg *msg, void *user_data)
   1696 {
   1697 	if (l_genl_msg_get_error(msg) < 0) {
   1698 		uint8_t cmd = l_genl_msg_get_command(msg);
   1699 		const char *cmd_name =
   1700 			cmd == NL80211_CMD_NEW_KEY ? "NEW_KEY" :
   1701 			cmd == NL80211_CMD_SET_KEY ? "SET_KEY" :
   1702 			"DEL_KEY";
   1703 
   1704 		l_error("%s failed for the GTK: %i",
   1705 			cmd_name, l_genl_msg_get_error(msg));
   1706 	}
   1707 }
   1708 
   1709 static void ap_associate_sta_cb(struct l_genl_msg *msg, void *user_data)
   1710 {
   1711 	struct sta_state *sta = user_data;
   1712 	struct ap_state *ap = sta->ap;
   1713 
   1714 	if (l_genl_msg_get_error(msg) < 0) {
   1715 		l_error("NEW_STATION/SET_STATION failed: %i",
   1716 			l_genl_msg_get_error(msg));
   1717 		return;
   1718 	}
   1719 
   1720 	/*
   1721 	 * WSC v2.0.5 Section 8.2:
   1722 	 * "Therefore if a WSC IE is present in the (re)association request,
   1723 	 * the AP shall engage in EAP-WSC with the station and shall not
   1724 	 * attempt any other security handshake."
   1725 	 *
   1726 	 * So no need for group traffic, skip the GTK setup below.
   1727 	 */
   1728 	if (!sta->assoc_rsne) {
   1729 		ap_start_eap_wsc(sta);
   1730 		return;
   1731 	}
   1732 
   1733 	/*
   1734 	 * Set up the group key.  If this is our first STA then we have
   1735 	 * to add the new GTK to the kernel.  In theory we should be
   1736 	 * able to supply our own RSC (e.g. generated randomly) and use it
   1737 	 * immediately for our 4-Way Handshake without querying the kernel.
   1738 	 * However NL80211_CMD_NEW_KEY only lets us set the receive RSC --
   1739 	 * the Rx PN for CCMP and the Rx IV for TKIP -- and the
   1740 	 * transmit RSC always starts as all zeros.  There's effectively
   1741 	 * no way to set the Tx RSC or query the Rx RSC through nl80211.
   1742 	 * So we query the Tx RSC in both scenarios just in case some
   1743 	 * driver/hardware uses a different initial Tx RSC.
   1744 	 *
   1745 	 * Optimally we would get called back by the EAPoL state machine
   1746 	 * only when building the step 3 of 4 message to query the RSC as
   1747 	 * late as possible but that would complicate EAPoL.
   1748 	 */
   1749 	if (ap->group_cipher != IE_RSN_CIPHER_SUITE_NO_GROUP_TRAFFIC &&
   1750 			!ap->gtk_set) {
   1751 		enum crypto_cipher group_cipher =
   1752 			ie_rsn_cipher_suite_to_cipher(ap->group_cipher);
   1753 		int gtk_len = crypto_cipher_key_len(group_cipher);
   1754 
   1755 		/*
   1756 		 * Generate our GTK.  Not following the example derivation
   1757 		 * method in 802.11-2016 section 12.7.1.4 because a simple
   1758 		 * l_getrandom is just as good.
   1759 		 */
   1760 		l_getrandom(ap->gtk, gtk_len);
   1761 		ap->gtk_index = 1;
   1762 
   1763 		msg = nl80211_build_new_key_group(
   1764 						netdev_get_ifindex(ap->netdev),
   1765 						group_cipher, ap->gtk_index,
   1766 						ap->gtk, gtk_len, NULL,
   1767 						0, NULL);
   1768 
   1769 		if (!l_genl_family_send(ap->nl80211, msg, ap_gtk_op_cb, NULL,
   1770 					NULL)) {
   1771 			l_genl_msg_unref(msg);
   1772 			l_error("Issuing NEW_KEY failed");
   1773 			goto error;
   1774 		}
   1775 
   1776 		msg = nl80211_build_set_key(netdev_get_ifindex(ap->netdev),
   1777 						ap->gtk_index);
   1778 		if (!l_genl_family_send(ap->nl80211, msg, ap_gtk_op_cb, NULL,
   1779 					NULL)) {
   1780 			l_genl_msg_unref(msg);
   1781 			l_error("Issuing SET_KEY failed");
   1782 			goto error;
   1783 		}
   1784 
   1785 		/*
   1786 		 * Set the flag now because any new associating STA will
   1787 		 * just use NL80211_CMD_GET_KEY from now.
   1788 		 */
   1789 		ap->gtk_set = true;
   1790 	}
   1791 
   1792 	if (ap->group_cipher == IE_RSN_CIPHER_SUITE_NO_GROUP_TRAFFIC)
   1793 		ap_start_rsna(sta, NULL);
   1794 	else {
   1795 		msg = nl80211_build_get_key(netdev_get_ifindex(ap->netdev),
   1796 					ap->gtk_index);
   1797 		sta->gtk_query_cmd_id = l_genl_family_send(ap->nl80211, msg,
   1798 								ap_gtk_query_cb,
   1799 								sta, NULL);
   1800 		if (!sta->gtk_query_cmd_id) {
   1801 			l_genl_msg_unref(msg);
   1802 			l_error("Issuing GET_KEY failed");
   1803 			goto error;
   1804 		}
   1805 	}
   1806 
   1807 	return;
   1808 
   1809 error:
   1810 	ap_del_station(sta, MMPDU_REASON_CODE_UNSPECIFIED, true);
   1811 }
   1812 
   1813 static void ap_associate_sta(struct ap_state *ap, struct sta_state *sta)
   1814 {
   1815 	struct l_genl_msg *msg;
   1816 	uint32_t ifindex = netdev_get_ifindex(ap->netdev);
   1817 
   1818 	uint8_t rates[256];
   1819 	uint32_t r, minr, maxr, count = 0;
   1820 	uint16_t capability = l_get_le16(&sta->capability);
   1821 
   1822 	if (sta->associated)
   1823 		msg = nl80211_build_set_station_associated(ifindex, sta->addr);
   1824 	else
   1825 		msg = ap_build_cmd_new_station(sta);
   1826 
   1827 	sta->associated = true;
   1828 	sta->rsna = false;
   1829 
   1830 	minr = l_uintset_find_min(sta->rates);
   1831 	maxr = l_uintset_find_max(sta->rates);
   1832 
   1833 	for (r = minr; r <= maxr; r++)
   1834 		if (l_uintset_contains(sta->rates, r))
   1835 			rates[count++] = r;
   1836 
   1837 	l_genl_msg_append_attr(msg, NL80211_ATTR_STA_AID, 2, &sta->aid);
   1838 	l_genl_msg_append_attr(msg, NL80211_ATTR_STA_SUPPORTED_RATES,
   1839 				count, &rates);
   1840 	l_genl_msg_append_attr(msg, NL80211_ATTR_STA_LISTEN_INTERVAL, 2,
   1841 				&sta->listen_interval);
   1842 	l_genl_msg_append_attr(msg, NL80211_ATTR_STA_CAPABILITY, 2,
   1843 				&capability);
   1844 
   1845 	if (!l_genl_family_send(ap->nl80211, msg, ap_associate_sta_cb,
   1846 								sta, NULL)) {
   1847 		l_genl_msg_unref(msg);
   1848 		if (l_genl_msg_get_command(msg) == NL80211_CMD_NEW_STATION)
   1849 			l_error("Issuing NEW_STATION failed");
   1850 		else
   1851 			l_error("Issuing SET_STATION failed");
   1852 	}
   1853 }
   1854 
   1855 static bool ap_common_rates(struct l_uintset *ap_rates,
   1856 				struct l_uintset *sta_rates)
   1857 {
   1858 	uint32_t minr = l_uintset_find_min(ap_rates);
   1859 
   1860 	/* Our lowest rate is a Basic Rate so must be supported */
   1861 	if (l_uintset_contains(sta_rates, minr))
   1862 		return true;
   1863 
   1864 	return false;
   1865 }
   1866 
   1867 static void ap_success_assoc_resp_cb(int err, void *user_data)
   1868 {
   1869 	struct sta_state *sta = user_data;
   1870 	struct ap_state *ap = sta->ap;
   1871 
   1872 	sta->assoc_resp_cmd_id = 0;
   1873 
   1874 	if (err) {
   1875 		if (err == -ECOMM)
   1876 			l_error("AP (Re)Association Response received no ACK");
   1877 		else
   1878 			l_error("AP (Re)Association Response not sent %s (%i)",
   1879 				strerror(-err), -err);
   1880 
   1881 		/* If we were in State 3 or 4 go to back to State 2 */
   1882 		if (sta->associated)
   1883 			ap_del_station(sta, MMPDU_REASON_CODE_UNSPECIFIED,
   1884 					true);
   1885 
   1886 		return;
   1887 	}
   1888 
   1889 	/* If we were in State 2, 3 or 4 also go to State 3 */
   1890 	ap_associate_sta(ap, sta);
   1891 
   1892 	l_info("AP (Re)Association Response ACK received");
   1893 }
   1894 
   1895 static void ap_fail_assoc_resp_cb(int err, void *user_data)
   1896 {
   1897 	if (err == -ECOMM)
   1898 		l_error("AP (Re)Association Response with an error status "
   1899 			"received no ACK");
   1900 	else if (err)
   1901 		l_error("AP (Re)Association Response with an error status "
   1902 			"not sent: %s (%i)", strerror(-err), -err);
   1903 	else
   1904 		l_info("AP (Re)Association Response with an error status "
   1905 			"delivered OK");
   1906 }
   1907 
   1908 static uint32_t ap_assoc_resp(struct ap_state *ap, struct sta_state *sta,
   1909 				const uint8_t *dest,
   1910 				enum mmpdu_reason_code status_code,
   1911 				bool reassoc, const struct mmpdu_header *req,
   1912 				size_t req_len,
   1913 				const struct ie_fils_ip_addr_request_info *
   1914 				ip_req_info, frame_xchg_cb_t callback)
   1915 {
   1916 	const uint8_t *addr = netdev_get_address(ap->netdev);
   1917 	enum mpdu_management_subtype stype = reassoc ?
   1918 		MPDU_MANAGEMENT_SUBTYPE_REASSOCIATION_RESPONSE :
   1919 		MPDU_MANAGEMENT_SUBTYPE_ASSOCIATION_RESPONSE;
   1920 	L_AUTO_FREE_VAR(uint8_t *, mpdu_buf) =
   1921 		l_malloc(256 + ap_get_extra_ies_len(ap, stype, req, req_len));
   1922 	struct mmpdu_header *mpdu = (void *) mpdu_buf;
   1923 	struct mmpdu_association_response *resp;
   1924 	size_t ies_len = 0;
   1925 	size_t len;
   1926 	uint16_t capability = IE_BSS_CAP_ESS | IE_BSS_CAP_PRIVACY;
   1927 
   1928 	memset(mpdu, 0, sizeof(*mpdu));
   1929 
   1930 	/* Header */
   1931 	mpdu->fc.protocol_version = 0;
   1932 	mpdu->fc.type = MPDU_TYPE_MANAGEMENT;
   1933 	mpdu->fc.subtype = stype;
   1934 	memcpy(mpdu->address_1, dest, 6);	/* DA */
   1935 	memcpy(mpdu->address_2, addr, 6);	/* SA */
   1936 	memcpy(mpdu->address_3, addr, 6);	/* BSSID */
   1937 
   1938 	/* Association Response body */
   1939 	resp = (void *) mmpdu_body(mpdu);
   1940 	l_put_le16(capability, &resp->capability);
   1941 	resp->status_code = L_CPU_TO_LE16(status_code);
   1942 	resp->aid = sta ? L_CPU_TO_LE16(sta->aid | 0xc000) : 0;
   1943 
   1944 	/* Supported Rates IE */
   1945 	resp->ies[ies_len++] = IE_TYPE_SUPPORTED_RATES;
   1946 	len = ap_build_supported_rates(ap, resp->ies + ies_len + 1);
   1947 	resp->ies[ies_len++] = len;
   1948 	ies_len += len;
   1949 
   1950 	if (ap->supports_ht) {
   1951 		resp->ies[ies_len++] = IE_TYPE_HT_CAPABILITIES;
   1952 		len = ap_build_ht_capability(ap, resp->ies + ies_len + 1);
   1953 		resp->ies[ies_len++] = len;
   1954 		ies_len += len;
   1955 
   1956 		resp->ies[ies_len++] = IE_TYPE_HT_OPERATION;
   1957 		len = ap_build_ht_operation(ap, resp->ies + ies_len + 1);
   1958 		resp->ies[ies_len++] = len;
   1959 		ies_len += len;
   1960 	}
   1961 
   1962 	ies_len += ap_write_extra_ies(ap, stype, req, req_len,
   1963 					resp->ies + ies_len);
   1964 
   1965 	if (ip_req_info) {
   1966 		struct ie_fils_ip_addr_response_info ip_resp_info = {};
   1967 
   1968 		if (ip_req_info->ipv4 && sta && ap_sta_get_dhcp4_lease(sta)) {
   1969 			uint32_t lease_lifetime =
   1970 				l_dhcp_lease_get_lifetime(sta->ip_alloc_lease);
   1971 			uint32_t gw =
   1972 				l_dhcp_lease_get_gateway_u32(
   1973 							sta->ip_alloc_lease);
   1974 			char **lease_dns_str_list =
   1975 				l_dhcp_lease_get_dns(sta->ip_alloc_lease);
   1976 
   1977 			ip_resp_info.ipv4_addr = l_dhcp_lease_get_address_u32(
   1978 							sta->ip_alloc_lease);
   1979 			ip_resp_info.ipv4_prefix_len =
   1980 				l_dhcp_lease_get_prefix_length(
   1981 							sta->ip_alloc_lease);
   1982 
   1983 			if (lease_lifetime != 0xffffffff)
   1984 				ip_resp_info.ipv4_lifetime = lease_lifetime;
   1985 
   1986 			if (gw) {
   1987 				ip_resp_info.ipv4_gateway = gw;
   1988 				memcpy(ip_resp_info.ipv4_gateway_mac,
   1989 					ap->netconfig_gateway4_mac, 6);
   1990 			}
   1991 
   1992 			if (lease_dns_str_list && lease_dns_str_list[0]) {
   1993 				ip_resp_info.ipv4_dns =
   1994 					IP4_FROM_STR(lease_dns_str_list[0]);
   1995 				memcpy(ip_resp_info.ipv4_dns_mac,
   1996 					ap->netconfig_dns4_mac, 6);
   1997 			}
   1998 
   1999 			l_strv_free(lease_dns_str_list);
   2000 			sta->ip_alloc_sent = true;
   2001 		} else if (ip_req_info->ipv4 || ip_req_info->ipv6) {
   2002 			/*
   2003 			 * 802.11ai-2016 Section 11.47.3.3: "If the AP is unable
   2004 			 * to assign an IP address in the (Re)Association
   2005 			 * Response frame, then the AP sets the IP address
   2006 			 * assignment pending flag in the IP Address Response
   2007 			 * Control field of the FILS IP Address Assignment
   2008 			 * element to 1 and sets the IP address request timeout
   2009 			 * to 0 in (Re)Association Response frame."
   2010 			 */
   2011 			ip_resp_info.response_pending = 1;
   2012 			ip_resp_info.response_timeout = 0;
   2013 		}
   2014 
   2015 		ie_build_fils_ip_addr_response(&ip_resp_info,
   2016 							resp->ies + ies_len);
   2017 		ies_len += 2 + resp->ies[ies_len + 1];
   2018 	}
   2019 
   2020 	return ap_send_mgmt_frame(ap, mpdu, resp->ies + ies_len - mpdu_buf,
   2021 					callback, sta);
   2022 }
   2023 
   2024 static int ap_parse_supported_rates(struct ie_tlv_iter *iter,
   2025 					struct l_uintset **set)
   2026 {
   2027 	const uint8_t *rates;
   2028 	unsigned int len;
   2029 	unsigned int i;
   2030 
   2031 	len = ie_tlv_iter_get_length(iter);
   2032 
   2033 	if (ie_tlv_iter_get_tag(iter) == IE_TYPE_SUPPORTED_RATES && len == 0)
   2034 		return -EINVAL;
   2035 
   2036 	rates = ie_tlv_iter_get_data(iter);
   2037 
   2038 	if (!*set)
   2039 		*set = l_uintset_new(108);
   2040 
   2041 	for (i = 0; i < len; i++) {
   2042 		if (rates[i] == 0xff)
   2043 			continue;
   2044 
   2045 		l_uintset_put(*set, rates[i] & 0x7f);
   2046 	}
   2047 
   2048 	return 0;
   2049 }
   2050 
   2051 /*
   2052  * This handles both the Association and Reassociation Request frames.
   2053  * Association Request is documented in 802.11-2016 9.3.3.6 (frame format),
   2054  * 802.11-2016 11.3.5.3 (MLME/SME) and Reassociation in 802.11-2016
   2055  * 9.3.3.8 (frame format), 802.11-2016 11.3.5.3 (MLME/SME).
   2056  *
   2057  * The difference between Association and Reassociation procedures is
   2058  * documented in 11.3.5.1 "General" but seems inconsistent with specific
   2059  * instructions in 11.3.5.3 vs. 11.3.5.5 and 11.3.5.2 vs. 11.3.5.4.
   2060  * According to 11.3.5.1:
   2061  *  1. Reassociation requires the STA to be already associated in the ESS,
   2062  *     Association doesn't.
   2063  *  2. Unsuccessful Reassociation should not cause a state transition of
   2064  *     the authentication state between the two STAs.
   2065  *
   2066  * The first requirement is not present in 11.3.5.5 which is virtually
   2067  * identical with 11.3.5.3, but we do implement it.  Number 2 is also not
   2068  * reflected in 11.3.5.5 where the state transitions are the same as in
   2069  * 11.3.5.3 and 11.3.5.4 where the state transitions are the same as in
   2070  * 11.3.5.2 including f) "If a Reassociation Response frame is received
   2071  * with a status code other than SUCCESS [...] 1. [...] the state for
   2072  * the AP [...] shall be set to State 2 [...]"
   2073  *
   2074  * For the record here are the apparent differences between 802.11-2016
   2075  * 11.3.5.2 and 11.3.5.4 ignoring the s/Associate/Reassociate/ changes
   2076  * and the special case of Reassociation during a Fast Transition.
   2077  *  o Points c) and d) are switched around.
   2078  *  o On success, the STA is disassociated from all other APs in 11.3.5.2,
   2079  *    and from the previous AP in 11.3.5.4 c).  (Shouldn't make a
   2080  *    difference as there seems to be no way for the STA to become
   2081  *    associated with more than one AP)
   2082  *  o After Association a 4-Way Handshake is always performed, after
   2083  *    Reassociation it is only performed if STA was in State 3 according
   2084  *    to 11.3.5.4 g).  This is not reflected in 11.3.5.5 though.
   2085  *    Additionally 11.3.5.4 and 11.3.5.5 require the STA and AP
   2086  *    respectively to delete current PTKSA/GTKSA/IGTKSA at the beginning
   2087  *    of the procedure independent of the STA state so without a 4-Way
   2088  *    Handshake the two stations end up with no encryption keys.
   2089  *
   2090  * The main difference between 11.3.5.3 and 11.3.5.5 is presence of p).
   2091  */
   2092 static void ap_assoc_reassoc(struct sta_state *sta, bool reassoc,
   2093 				const struct mmpdu_field_capability *capability,
   2094 				uint16_t listen_interval,
   2095 				const uint8_t *ies, size_t ies_len,
   2096 				const struct mmpdu_header *req)
   2097 {
   2098 	struct ap_state *ap = sta->ap;
   2099 	const char *ssid = NULL;
   2100 	const uint8_t *rsn = NULL;
   2101 	size_t ssid_len = 0;
   2102 	_auto_(l_uintset_free) struct l_uintset *rates = NULL;
   2103 	struct ie_rsn_info rsn_info;
   2104 	int err;
   2105 	struct ie_tlv_iter iter;
   2106 	_auto_(l_free) uint8_t *wsc_data = NULL;
   2107 	ssize_t wsc_data_len;
   2108 	bool fils_ip_req = false;
   2109 	struct ie_fils_ip_addr_request_info fils_ip_req_info;
   2110 
   2111 	if (sta->assoc_resp_cmd_id)
   2112 		return;
   2113 
   2114 	if (reassoc && !sta->associated) {
   2115 		err = MMPDU_REASON_CODE_CLASS3_FRAME_FROM_NONASSOC_STA;
   2116 		goto unsupported;
   2117 	}
   2118 
   2119 	wsc_data = ie_tlv_extract_wsc_payload(ies, ies_len, &wsc_data_len);
   2120 
   2121 	ie_tlv_iter_init(&iter, ies, ies_len);
   2122 
   2123 	while (ie_tlv_iter_next(&iter))
   2124 		switch (ie_tlv_iter_get_tag(&iter)) {
   2125 		case IE_TYPE_SSID:
   2126 			ssid = (const char *) ie_tlv_iter_get_data(&iter);
   2127 			ssid_len = ie_tlv_iter_get_length(&iter);
   2128 			break;
   2129 
   2130 		case IE_TYPE_SUPPORTED_RATES:
   2131 		case IE_TYPE_EXTENDED_SUPPORTED_RATES:
   2132 			if (ap_parse_supported_rates(&iter, &rates) < 0) {
   2133 				err = MMPDU_REASON_CODE_INVALID_IE;
   2134 				goto bad_frame;
   2135 			}
   2136 
   2137 			break;
   2138 
   2139 		case IE_TYPE_RSN:
   2140 			/*
   2141 			 * WSC v2.0.5 Section 8.2:
   2142 			 * "Note that during the WSC association [...] the
   2143 			 * RSN IE and the WPA IE are irrelevant and shall be
   2144 			 * ignored by both the station and AP."
   2145 			 */
   2146 			if (wsc_data)
   2147 				break;
   2148 
   2149 			if (ie_parse_rsne(&iter, &rsn_info) < 0) {
   2150 				err = MMPDU_REASON_CODE_INVALID_IE;
   2151 				goto bad_frame;
   2152 			}
   2153 
   2154 			rsn = (const uint8_t *) ie_tlv_iter_get_data(&iter) - 2;
   2155 			break;
   2156 
   2157 		case IE_TYPE_FILS_IP_ADDRESS:
   2158 			if (fils_ip_req || ie_parse_fils_ip_addr_request(&iter,
   2159 						&fils_ip_req_info) < 0) {
   2160 				l_debug("Can't parse FILS IP Address Assignment"
   2161 					" IE, ignoring it");
   2162 				break;
   2163 			}
   2164 
   2165 			fils_ip_req = true;
   2166 			break;
   2167 		case IE_TYPE_HT_CAPABILITIES:
   2168 			if (ie_tlv_iter_get_length(&iter) != 26) {
   2169 				err = MMPDU_REASON_CODE_INVALID_IE;
   2170 				goto bad_frame;
   2171 			}
   2172 
   2173 			if (test_bit(ie_tlv_iter_get_data(&iter), 4))
   2174 				sta->ht_greenfield = true;
   2175 
   2176 			sta->ht_support = true;
   2177 			break;
   2178 		}
   2179 
   2180 	if (!rates || !ssid || (!wsc_data && !rsn) ||
   2181 			ssid_len != strlen(ap->ssid) ||
   2182 			memcmp(ssid, ap->ssid, ssid_len)) {
   2183 		err = MMPDU_REASON_CODE_INVALID_IE;
   2184 		goto bad_frame;
   2185 	}
   2186 
   2187 	if (!ap_common_rates(ap->rates, rates)) {
   2188 		err = MMPDU_REASON_CODE_UNSPECIFIED;
   2189 		goto unsupported;
   2190 	}
   2191 
   2192 	/* Is the client requesting RSNA establishment or WSC registration */
   2193 	if (!rsn) {
   2194 		struct wsc_association_request wsc_req;
   2195 		struct ap_event_registration_start_data event_data;
   2196 		struct ap_wsc_pbc_probe_record *record;
   2197 
   2198 		if (wsc_parse_association_request(wsc_data, wsc_data_len,
   2199 							&wsc_req) < 0) {
   2200 			err = MMPDU_REASON_CODE_INVALID_IE;
   2201 			goto bad_frame;
   2202 		}
   2203 
   2204 		if (wsc_req.request_type !=
   2205 				WSC_REQUEST_TYPE_ENROLLEE_OPEN_8021X) {
   2206 			err = MMPDU_REASON_CODE_INVALID_IE;
   2207 			goto bad_frame;
   2208 		}
   2209 
   2210 		if (!ap->wsc_pbc_timeout) {
   2211 			l_debug("WSC association from %s but we're not in "
   2212 				"PBC mode", util_address_to_string(sta->addr));
   2213 			err = MMPDU_REASON_CODE_UNSPECIFIED;
   2214 			goto bad_frame;
   2215 		}
   2216 
   2217 		if (l_queue_isempty(ap->wsc_pbc_probes)) {
   2218 			l_debug("%s tried to register as enrollee but we "
   2219 				"don't have their Probe Request record",
   2220 				util_address_to_string(sta->addr));
   2221 			err = MMPDU_REASON_CODE_UNSPECIFIED;
   2222 			goto bad_frame;
   2223 		}
   2224 
   2225 		/*
   2226 		 * For PBC, the Enrollee must have sent the only PBC Probe
   2227 		 * Request within the monitor time and walk time.
   2228 		 */
   2229 		record = l_queue_peek_head(ap->wsc_pbc_probes);
   2230 		if (memcmp(sta->addr, record->mac, 6)) {
   2231 			l_debug("Session overlap during %s's attempt to "
   2232 				"register as WSC enrollee",
   2233 				util_address_to_string(sta->addr));
   2234 			err = MMPDU_REASON_CODE_UNSPECIFIED;
   2235 			goto bad_frame;
   2236 		}
   2237 
   2238 		memcpy(sta->wsc_uuid_e, record->uuid_e, 16);
   2239 		sta->wsc_v2 = wsc_req.version2;
   2240 
   2241 		event_data.mac = sta->addr;
   2242 		event_data.assoc_ies = ies;
   2243 		event_data.assoc_ies_len = ies_len;
   2244 
   2245 		if (ap_event(ap, AP_EVENT_REGISTRATION_START, &event_data))
   2246 			return;
   2247 
   2248 		/*
   2249 		 * Since we're starting the PBC Registration Protocol
   2250 		 * we can now exit the "active PBC mode".
   2251 		 */
   2252 		ap_wsc_exit_pbc(ap);
   2253 	} else {
   2254 		if (rsn_info.mfpr && rsn_info.spp_a_msdu_required) {
   2255 			err = MMPDU_REASON_CODE_UNSPECIFIED;
   2256 			goto unsupported;
   2257 		}
   2258 
   2259 		if (__builtin_popcount(rsn_info.pairwise_ciphers) != 1 ||
   2260 				!(rsn_info.pairwise_ciphers & ap->ciphers)) {
   2261 			err = MMPDU_REASON_CODE_INVALID_PAIRWISE_CIPHER;
   2262 			goto unsupported;
   2263 		}
   2264 
   2265 		if (rsn_info.akm_suites != IE_RSN_AKM_SUITE_PSK) {
   2266 			err = MMPDU_REASON_CODE_INVALID_AKMP;
   2267 			goto unsupported;
   2268 		}
   2269 
   2270 		if (rsn_info.group_cipher != ap->group_cipher) {
   2271 			err = MMPDU_REASON_CODE_INVALID_GROUP_CIPHER;
   2272 			goto unsupported;
   2273 		}
   2274 	}
   2275 
   2276 	/* 802.11-2016 11.3.5.3 j) */
   2277 	if (sta->rsna)
   2278 		ap_drop_rsna(sta);
   2279 	else if (sta->associated)
   2280 		ap_stop_handshake(sta);
   2281 
   2282 	if (!sta->associated) {
   2283 		/*
   2284 		 * Everything fine so far, assign an AID, send response.
   2285 		 * According to 802.11-2016 11.3.5.3 l) we will only go to
   2286 		 * State 3 (set sta->associated) once we receive the station's
   2287 		 * ACK or gave up on resends.
   2288 		 */
   2289 		sta->aid = ++ap->last_aid;
   2290 	}
   2291 
   2292 	sta->capability = *capability;
   2293 	sta->listen_interval = listen_interval;
   2294 
   2295 	if (sta->rates)
   2296 		l_uintset_free(sta->rates);
   2297 
   2298 	sta->rates = l_steal_ptr(rates);
   2299 
   2300 	l_free(sta->assoc_ies);
   2301 
   2302 	if (rsn) {
   2303 		sta->assoc_ies = l_memdup(ies, ies_len);
   2304 		sta->assoc_ies_len = ies_len;
   2305 		sta->assoc_rsne = sta->assoc_ies + (rsn - ies);
   2306 	} else {
   2307 		sta->assoc_ies = NULL;
   2308 		sta->assoc_rsne = NULL;
   2309 	}
   2310 
   2311 	sta->assoc_resp_cmd_id = ap_assoc_resp(ap, sta, sta->addr, 0, reassoc,
   2312 						req, (void *) ies + ies_len -
   2313 						(void *) req, fils_ip_req ?
   2314 						&fils_ip_req_info : NULL,
   2315 						ap_success_assoc_resp_cb);
   2316 	if (!sta->assoc_resp_cmd_id)
   2317 		l_error("Sending success (Re)Association Response failed");
   2318 
   2319 	return;
   2320 
   2321 unsupported:
   2322 bad_frame:
   2323 	/*
   2324 	 * TODO: MFP
   2325 	 *
   2326 	 * 802.11-2016 11.3.5.3 m)
   2327 	 * "If the ResultCode in the MLME-ASSOCIATE.response primitive is
   2328 	 * not SUCCESS and management frame protection is in use the state
   2329 	 * for the STA shall be left unchanged.  If the ResultCode is not
   2330 	 * SUCCESS and management frame protection is not in use the state
   2331 	 * for the STA shall be set to State 3 if it was State 4."
   2332 	 *
   2333 	 * For now, we need to drop the RSNA.
   2334 	 */
   2335 	if (sta->rsna)
   2336 		ap_drop_rsna(sta);
   2337 	else if (sta->associated)
   2338 		ap_stop_handshake(sta);
   2339 
   2340 	if (!ap_assoc_resp(ap, sta, sta->addr, err, reassoc,
   2341 				req, (void *) ies + ies_len - (void *) req,
   2342 				NULL, ap_fail_assoc_resp_cb))
   2343 		l_error("Sending error (Re)Association Response failed");
   2344 }
   2345 
   2346 /* 802.11-2016 9.3.3.6 */
   2347 static void ap_assoc_req_cb(const struct mmpdu_header *hdr, const void *body,
   2348 				size_t body_len, int rssi, void *user_data)
   2349 {
   2350 	struct ap_state *ap = user_data;
   2351 	struct sta_state *sta;
   2352 	const uint8_t *from = hdr->address_2;
   2353 	const struct mmpdu_association_request *req = body;
   2354 	const uint8_t *bssid = netdev_get_address(ap->netdev);
   2355 
   2356 	l_info("AP Association Request from %s", util_address_to_string(from));
   2357 
   2358 	if (memcmp(hdr->address_1, bssid, 6) ||
   2359 			memcmp(hdr->address_3, bssid, 6))
   2360 		return;
   2361 
   2362 	sta = l_queue_find(ap->sta_states, ap_sta_match_addr, from);
   2363 	if (!sta) {
   2364 		if (!ap_assoc_resp(ap, NULL, from,
   2365 				MMPDU_REASON_CODE_STA_REQ_ASSOC_WITHOUT_AUTH,
   2366 				false, hdr, body + body_len - (void *) hdr,
   2367 				NULL, ap_fail_assoc_resp_cb))
   2368 			l_error("Sending error Association Response failed");
   2369 
   2370 		return;
   2371 	}
   2372 
   2373 	ap_assoc_reassoc(sta, false, &req->capability,
   2374 				L_LE16_TO_CPU(req->listen_interval),
   2375 				req->ies, body_len - sizeof(*req), hdr);
   2376 }
   2377 
   2378 /* 802.11-2016 9.3.3.8 */
   2379 static void ap_reassoc_req_cb(const struct mmpdu_header *hdr, const void *body,
   2380 				size_t body_len, int rssi, void *user_data)
   2381 {
   2382 	struct ap_state *ap = user_data;
   2383 	struct sta_state *sta;
   2384 	const uint8_t *from = hdr->address_2;
   2385 	const struct mmpdu_reassociation_request *req = body;
   2386 	const uint8_t *bssid = netdev_get_address(ap->netdev);
   2387 	int err;
   2388 
   2389 	l_info("AP Reassociation Request from %s",
   2390 		util_address_to_string(from));
   2391 
   2392 	if (memcmp(hdr->address_1, bssid, 6) ||
   2393 			memcmp(hdr->address_3, bssid, 6))
   2394 		return;
   2395 
   2396 	sta = l_queue_find(ap->sta_states, ap_sta_match_addr, from);
   2397 	if (!sta) {
   2398 		err = MMPDU_REASON_CODE_STA_REQ_ASSOC_WITHOUT_AUTH;
   2399 		goto bad_frame;
   2400 	}
   2401 
   2402 	if (memcmp(req->current_ap_address, bssid, 6)) {
   2403 		err = MMPDU_REASON_CODE_UNSPECIFIED;
   2404 		goto bad_frame;
   2405 	}
   2406 
   2407 	ap_assoc_reassoc(sta, true, &req->capability,
   2408 				L_LE16_TO_CPU(req->listen_interval),
   2409 				req->ies, body_len - sizeof(*req), hdr);
   2410 	return;
   2411 
   2412 bad_frame:
   2413 	if (!ap_assoc_resp(ap, NULL, from, err, true,
   2414 				hdr, body + body_len - (void *) hdr,
   2415 				NULL, ap_fail_assoc_resp_cb))
   2416 		l_error("Sending error Reassociation Response failed");
   2417 }
   2418 
   2419 static void ap_probe_resp_cb(int err, void *user_data)
   2420 {
   2421 	if (err == -ECOMM)
   2422 		l_error("AP Probe Response received no ACK");
   2423 	else if (err)
   2424 		l_error("AP Probe Response not sent: %s (%i)",
   2425 			strerror(-err), -err);
   2426 	else
   2427 		l_info("AP Probe Response delivered OK");
   2428 }
   2429 
   2430 /*
   2431  * Parse Probe Request according to 802.11-2016 9.3.3.10 and act according
   2432  * to 802.11-2016 11.1.4.3
   2433  */
   2434 static void ap_probe_req_cb(const struct mmpdu_header *hdr, const void *body,
   2435 				size_t body_len, int rssi, void *user_data)
   2436 {
   2437 	struct ap_state *ap = user_data;
   2438 	const struct mmpdu_probe_request *req = body;
   2439 	const char *ssid = NULL;
   2440 	const uint8_t *ssid_list = NULL;
   2441 	size_t ssid_len = 0, ssid_list_len = 0, len;
   2442 	uint8_t dsss_channel = 0;
   2443 	struct ie_tlv_iter iter;
   2444 	const uint8_t *bssid = netdev_get_address(ap->netdev);
   2445 	bool match = false;
   2446 	uint32_t resp_len;
   2447 	uint8_t *resp;
   2448 
   2449 	l_info("AP Probe Request from %s",
   2450 		util_address_to_string(hdr->address_2));
   2451 
   2452 	ie_tlv_iter_init(&iter, req->ies, body_len - sizeof(*req));
   2453 
   2454 	while (ie_tlv_iter_next(&iter))
   2455 		switch (ie_tlv_iter_get_tag(&iter)) {
   2456 		case IE_TYPE_SSID:
   2457 			ssid = (const char *) ie_tlv_iter_get_data(&iter);
   2458 			ssid_len = ie_tlv_iter_get_length(&iter);
   2459 			break;
   2460 
   2461 		case IE_TYPE_SSID_LIST:
   2462 			ssid_list = ie_tlv_iter_get_data(&iter);
   2463 			ssid_list_len = ie_tlv_iter_get_length(&iter);
   2464 			break;
   2465 
   2466 		case IE_TYPE_DSSS_PARAMETER_SET:
   2467 			if (ie_tlv_iter_get_length(&iter) != 1)
   2468 				return;
   2469 
   2470 			dsss_channel = ie_tlv_iter_get_data(&iter)[0];
   2471 			break;
   2472 		}
   2473 
   2474 	/*
   2475 	 * Check if we should reply to this Probe Request according to
   2476 	 * 802.11-2016 section 11.1.4.3.2.
   2477 	 */
   2478 
   2479 	if (memcmp(hdr->address_1, bssid, 6) &&
   2480 			!util_is_broadcast_address(hdr->address_1))
   2481 		return;
   2482 
   2483 	if (memcmp(hdr->address_3, bssid, 6) &&
   2484 			!util_is_broadcast_address(hdr->address_3))
   2485 		return;
   2486 
   2487 	if (!ssid || ssid_len == 0) /* Wildcard SSID */
   2488 		match = true;
   2489 	else if (ssid && ssid_len == strlen(ap->ssid) && /* One SSID */
   2490 			!memcmp(ssid, ap->ssid, ssid_len))
   2491 		match = true;
   2492 	else if (ssid && ssid_len == 7 && !memcmp(ssid, "DIRECT-", 7) &&
   2493 			!memcmp(ssid, ap->ssid, 7)) /* P2P wildcard */
   2494 		match = true;
   2495 	else if (ssid_list) { /* SSID List */
   2496 		ie_tlv_iter_init(&iter, ssid_list, ssid_list_len);
   2497 
   2498 		while (ie_tlv_iter_next(&iter)) {
   2499 			if (ie_tlv_iter_get_tag(&iter) != IE_TYPE_SSID)
   2500 				return;
   2501 
   2502 			ssid = (const char *) ie_tlv_iter_get_data(&iter);
   2503 			ssid_len = ie_tlv_iter_get_length(&iter);
   2504 
   2505 			if (ssid_len == strlen(ap->ssid) &&
   2506 					!memcmp(ssid, ap->ssid, ssid_len)) {
   2507 				match = true;
   2508 				break;
   2509 			}
   2510 		}
   2511 	}
   2512 
   2513 	if (dsss_channel != 0 && dsss_channel != ap->channel)
   2514 		match = false;
   2515 
   2516 	if (!match)
   2517 		return;
   2518 
   2519 	resp_len = 512 + ap_get_extra_ies_len(ap,
   2520 					MPDU_MANAGEMENT_SUBTYPE_PROBE_RESPONSE,
   2521 					hdr, body + body_len - (void *) hdr);
   2522 	resp = l_new(uint8_t, resp_len);
   2523 	len = ap_build_beacon_pr_head(ap,
   2524 					MPDU_MANAGEMENT_SUBTYPE_PROBE_RESPONSE,
   2525 					hdr->address_2, resp, resp_len);
   2526 	len += ap_build_beacon_pr_tail(ap,
   2527 					MPDU_MANAGEMENT_SUBTYPE_PROBE_RESPONSE,
   2528 					hdr, body + body_len - (void *) hdr,
   2529 					resp + len, resp_len - len);
   2530 
   2531 	ap_send_mgmt_frame(ap, (struct mmpdu_header *) resp, len,
   2532 				ap_probe_resp_cb, NULL);
   2533 	l_free(resp);
   2534 }
   2535 
   2536 /* 802.11-2016 9.3.3.5 (frame format), 802.11-2016 11.3.5.9 (MLME/SME) */
   2537 static void ap_disassoc_cb(const struct mmpdu_header *hdr, const void *body,
   2538 				size_t body_len, int rssi, void *user_data)
   2539 {
   2540 	struct ap_state *ap = user_data;
   2541 	struct sta_state *sta;
   2542 	const struct mmpdu_disassociation *disassoc = body;
   2543 	const uint8_t *bssid = netdev_get_address(ap->netdev);
   2544 
   2545 	l_info("AP Disassociation from %s, reason %i",
   2546 		util_address_to_string(hdr->address_2),
   2547 		(int) L_LE16_TO_CPU(disassoc->reason_code));
   2548 
   2549 	if (memcmp(hdr->address_1, bssid, 6) ||
   2550 			memcmp(hdr->address_3, bssid, 6))
   2551 		return;
   2552 
   2553 	sta = l_queue_find(ap->sta_states, ap_sta_match_addr, hdr->address_2);
   2554 
   2555 	if (sta && sta->assoc_resp_cmd_id) {
   2556 		l_genl_family_cancel(ap->nl80211, sta->assoc_resp_cmd_id);
   2557 		sta->assoc_resp_cmd_id = 0;
   2558 	}
   2559 
   2560 	if (!sta || !sta->associated)
   2561 		return;
   2562 
   2563 	ap_del_station(sta, L_LE16_TO_CPU(disassoc->reason_code), true);
   2564 }
   2565 
   2566 static void ap_auth_reply_cb(int err, void *user_data)
   2567 {
   2568 	if (err == -ECOMM)
   2569 		l_error("AP Authentication frame 2 received no ACK");
   2570 	else if (err)
   2571 		l_error("AP Authentication frame 2 not sent: %s (%i)",
   2572 			strerror(-err), -err);
   2573 	else
   2574 		l_info("AP Authentication frame 2 ACKed by STA");
   2575 }
   2576 
   2577 static void ap_auth_reply(struct ap_state *ap, const uint8_t *dest,
   2578 				enum mmpdu_reason_code status_code)
   2579 {
   2580 	const uint8_t *addr = netdev_get_address(ap->netdev);
   2581 	uint8_t mpdu_buf[64];
   2582 	struct mmpdu_header *mpdu = (struct mmpdu_header *) mpdu_buf;
   2583 	struct mmpdu_authentication *auth;
   2584 
   2585 	memset(mpdu, 0, sizeof(*mpdu));
   2586 
   2587 	/* Header */
   2588 	mpdu->fc.protocol_version = 0;
   2589 	mpdu->fc.type = MPDU_TYPE_MANAGEMENT;
   2590 	mpdu->fc.subtype = MPDU_MANAGEMENT_SUBTYPE_AUTHENTICATION;
   2591 	memcpy(mpdu->address_1, dest, 6);	/* DA */
   2592 	memcpy(mpdu->address_2, addr, 6);	/* SA */
   2593 	memcpy(mpdu->address_3, addr, 6);	/* BSSID */
   2594 
   2595 	/* Authentication body */
   2596 	auth = (void *) mmpdu_body(mpdu);
   2597 	auth->algorithm = L_CPU_TO_LE16(MMPDU_AUTH_ALGO_OPEN_SYSTEM);
   2598 	auth->transaction_sequence = L_CPU_TO_LE16(2);
   2599 	auth->status = L_CPU_TO_LE16(status_code);
   2600 
   2601 	ap_send_mgmt_frame(ap, mpdu, (uint8_t *) auth + 6 - mpdu_buf,
   2602 				ap_auth_reply_cb, NULL);
   2603 }
   2604 
   2605 /*
   2606  * 802.11-2016 9.3.3.12 (frame format), 802.11-2016 11.3.4.3 and
   2607  * 802.11-2016 12.3.3.2 (MLME/SME)
   2608  */
   2609 static void ap_auth_cb(const struct mmpdu_header *hdr, const void *body,
   2610 			size_t body_len, int rssi, void *user_data)
   2611 {
   2612 	struct ap_state *ap = user_data;
   2613 	const struct mmpdu_authentication *auth = body;
   2614 	const uint8_t *from = hdr->address_2;
   2615 	const uint8_t *bssid = netdev_get_address(ap->netdev);
   2616 	struct sta_state *sta;
   2617 
   2618 	l_info("AP Authentication from %s", util_address_to_string(from));
   2619 
   2620 	if (memcmp(hdr->address_1, bssid, 6) ||
   2621 			memcmp(hdr->address_3, bssid, 6))
   2622 		return;
   2623 
   2624 	if (ap->authorized_macs_num) {
   2625 		unsigned int i;
   2626 
   2627 		for (i = 0; i < ap->authorized_macs_num; i++)
   2628 			if (!memcmp(from, ap->authorized_macs + i * 6,
   2629 					6))
   2630 				break;
   2631 
   2632 		if (i == ap->authorized_macs_num) {
   2633 			ap_auth_reply(ap, from, MMPDU_REASON_CODE_UNSPECIFIED);
   2634 			return;
   2635 		}
   2636 	}
   2637 
   2638 	/* Only Open System authentication implemented here */
   2639 	if (L_LE16_TO_CPU(auth->algorithm) !=
   2640 			MMPDU_AUTH_ALGO_OPEN_SYSTEM) {
   2641 		ap_auth_reply(ap, from, MMPDU_REASON_CODE_UNSPECIFIED);
   2642 		return;
   2643 	}
   2644 
   2645 	if (L_LE16_TO_CPU(auth->transaction_sequence) != 1) {
   2646 		ap_auth_reply(ap, from, MMPDU_REASON_CODE_UNSPECIFIED);
   2647 		return;
   2648 	}
   2649 
   2650 	sta = l_queue_find(ap->sta_states, ap_sta_match_addr, from);
   2651 
   2652 	/*
   2653 	 * Figure 11-13 in 802.11-2016 11.3.2 shows a transition from
   2654 	 * States 3 / 4 to State 2 on "Successful 802.11 Authentication"
   2655 	 * however 11.3.4.2 and 11.3.4.3 clearly say the connection goes to
   2656 	 * State 2 only if it was in State 1:
   2657 	 *
   2658 	 * "c) [...] the state for the indicated STA shall be set to State 2
   2659 	 * if it was State 1; the state shall remain unchanged if it was other
   2660 	 * than State 1."
   2661 	 */
   2662 	if (sta)
   2663 		goto done;
   2664 
   2665 	/*
   2666 	 * Per 12.3.3.2.3 with Open System the state change is immediate,
   2667 	 * no waiting for the response to be ACKed as with the association
   2668 	 * frames.
   2669 	 */
   2670 	sta = l_new(struct sta_state, 1);
   2671 	memcpy(sta->addr, from, 6);
   2672 	sta->ap = ap;
   2673 
   2674 	if (!ap->sta_states)
   2675 		ap->sta_states = l_queue_new();
   2676 
   2677 	l_queue_push_tail(ap->sta_states, sta);
   2678 
   2679 	/*
   2680 	 * Nothing to do here netlink-wise as we can't receive any data
   2681 	 * frames until after association anyway.  We do need to add a
   2682 	 * timeout for the authentication and possibly the kernel could
   2683 	 * handle that if we registered the STA with NEW_STATION now (TODO)
   2684 	 */
   2685 
   2686 done:
   2687 	ap_auth_reply(ap, from, 0);
   2688 }
   2689 
   2690 /* 802.11-2016 9.3.3.13 (frame format), 802.11-2016 11.3.4.5 (MLME/SME) */
   2691 static void ap_deauth_cb(const struct mmpdu_header *hdr, const void *body,
   2692 				size_t body_len, int rssi, void *user_data)
   2693 {
   2694 	struct ap_state *ap = user_data;
   2695 	const struct mmpdu_deauthentication *deauth = body;
   2696 	const uint8_t *bssid = netdev_get_address(ap->netdev);
   2697 
   2698 	l_info("AP Deauthentication from %s, reason %i",
   2699 		util_address_to_string(hdr->address_2),
   2700 		(int) L_LE16_TO_CPU(deauth->reason_code));
   2701 
   2702 	if (memcmp(hdr->address_1, bssid, 6) ||
   2703 			memcmp(hdr->address_3, bssid, 6))
   2704 		return;
   2705 
   2706 	ap_station_disconnect(ap, hdr->address_2,
   2707 				L_LE16_TO_CPU(deauth->reason_code));
   2708 }
   2709 
   2710 static void do_debug(const char *str, void *user_data)
   2711 {
   2712 	const char *prefix = user_data;
   2713 
   2714 	l_info("%s%s", prefix, str);
   2715 }
   2716 
   2717 static void ap_start_failed(struct ap_state *ap, int err)
   2718 {
   2719 	struct ap_event_start_failed_data data = { err };
   2720 
   2721 	ap->in_event = true;
   2722 	ap->ops->handle_event(AP_EVENT_START_FAILED, &data, ap->user_data);
   2723 	ap_reset(ap);
   2724 	l_genl_family_free(ap->nl80211);
   2725 
   2726 	l_free(ap);
   2727 }
   2728 
   2729 static void ap_dhcp_event_cb(struct l_dhcp_server *server,
   2730 				enum l_dhcp_server_event event, void *user_data,
   2731 				const struct l_dhcp_lease *lease)
   2732 {
   2733 	struct ap_state *ap = user_data;
   2734 
   2735 	switch (event) {
   2736 	case L_DHCP_SERVER_EVENT_NEW_LEASE:
   2737 		ap_event(ap, AP_EVENT_DHCP_NEW_LEASE, lease);
   2738 		break;
   2739 
   2740 	case L_DHCP_SERVER_EVENT_LEASE_EXPIRED:
   2741 		ap_event(ap, AP_EVENT_DHCP_LEASE_EXPIRED, lease);
   2742 		break;
   2743 
   2744 	default:
   2745 		break;
   2746 	}
   2747 }
   2748 
   2749 static void ap_start_cb(struct l_genl_msg *msg, void *user_data)
   2750 {
   2751 	struct ap_state *ap = user_data;
   2752 
   2753 	ap->start_stop_cmd_id = 0;
   2754 
   2755 	if (l_genl_msg_get_error(msg) < 0) {
   2756 		l_error("START_AP failed: %i", l_genl_msg_get_error(msg));
   2757 		ap_start_failed(ap, l_genl_msg_get_error(msg));
   2758 		return;
   2759 	}
   2760 
   2761 	if (ap->netconfig_dhcp) {
   2762 		if (!l_dhcp_server_start(ap->netconfig_dhcp)) {
   2763 			l_error("DHCP server failed to start");
   2764 			ap_start_failed(ap, -EINVAL);
   2765 			return;
   2766 		}
   2767 
   2768 		if (!l_dhcp_server_set_event_handler(ap->netconfig_dhcp,
   2769 							ap_dhcp_event_cb,
   2770 							ap, NULL)) {
   2771 			l_error("l_dhcp_server_set_event_handler failed");
   2772 			ap_start_failed(ap, -EIO);
   2773 			return;
   2774 		}
   2775 	}
   2776 
   2777 	ap->started = true;
   2778 	ap_event(ap, AP_EVENT_STARTED, NULL);
   2779 }
   2780 
   2781 static struct l_genl_msg *ap_build_cmd_start_ap(struct ap_state *ap)
   2782 {
   2783 	struct l_genl_msg *cmd;
   2784 
   2785 	uint8_t head[256];
   2786 	size_t tail_len = 256 + ap_get_extra_ies_len(ap,
   2787 						MPDU_MANAGEMENT_SUBTYPE_BEACON,
   2788 						NULL, 0);
   2789 	L_AUTO_FREE_VAR(uint8_t *, tail) = l_malloc(tail_len);
   2790 	size_t head_len;
   2791 
   2792 	uint32_t dtim_period = 3;
   2793 	uint32_t ifindex = netdev_get_ifindex(ap->netdev);
   2794 	struct wiphy *wiphy = netdev_get_wiphy(ap->netdev);
   2795 	uint32_t hidden_ssid = NL80211_HIDDEN_SSID_NOT_IN_USE;
   2796 	unsigned int nl_ciphers_cnt = __builtin_popcount(ap->ciphers);
   2797 	uint32_t nl_ciphers[nl_ciphers_cnt];
   2798 	uint32_t group_nl_cipher =
   2799 		ie_rsn_cipher_suite_to_cipher(ap->group_cipher);
   2800 	uint32_t nl_akm = CRYPTO_AKM_PSK;
   2801 	uint32_t wpa_version = NL80211_WPA_VERSION_2;
   2802 	uint32_t auth_type = NL80211_AUTHTYPE_OPEN_SYSTEM;
   2803 	unsigned int i;
   2804 
   2805 	static const uint8_t bcast_addr[6] = {
   2806 		0xff, 0xff, 0xff, 0xff, 0xff, 0xff
   2807 	};
   2808 
   2809 	static const uint8_t zero_addr[6] = { 0 };
   2810 
   2811 	for (i = 0, nl_ciphers_cnt = 0; i < 8; i++)
   2812 		if (ap->ciphers & (1 << i))
   2813 			nl_ciphers[nl_ciphers_cnt++] =
   2814 				ie_rsn_cipher_suite_to_cipher(1 << i);
   2815 
   2816 	head_len = ap_build_beacon_pr_head(ap, MPDU_MANAGEMENT_SUBTYPE_BEACON,
   2817 						bcast_addr, head, sizeof(head));
   2818 	tail_len = ap_build_beacon_pr_tail(ap, MPDU_MANAGEMENT_SUBTYPE_BEACON,
   2819 						NULL, 0, tail, tail_len);
   2820 
   2821 	if (!head_len || !tail_len)
   2822 		return NULL;
   2823 
   2824 	cmd = l_genl_msg_new_sized(NL80211_CMD_START_AP, 256 + head_len +
   2825 					tail_len + strlen(ap->ssid));
   2826 
   2827 	/* SET_BEACON attrs */
   2828 	l_genl_msg_append_attr(cmd, NL80211_ATTR_BEACON_HEAD, head_len, head);
   2829 	l_genl_msg_append_attr(cmd, NL80211_ATTR_BEACON_TAIL, tail_len, tail);
   2830 	l_genl_msg_append_attr(cmd, NL80211_ATTR_IE, 0, "");
   2831 	l_genl_msg_append_attr(cmd, NL80211_ATTR_IE_PROBE_RESP, 0, "");
   2832 	l_genl_msg_append_attr(cmd, NL80211_ATTR_IE_ASSOC_RESP, 0, "");
   2833 
   2834 	/* START_AP attrs */
   2835 	l_genl_msg_append_attr(cmd, NL80211_ATTR_BEACON_INTERVAL, 4,
   2836 				&ap->beacon_interval);
   2837 	l_genl_msg_append_attr(cmd, NL80211_ATTR_DTIM_PERIOD, 4, &dtim_period);
   2838 	l_genl_msg_append_attr(cmd, NL80211_ATTR_IFINDEX, 4, &ifindex);
   2839 	l_genl_msg_append_attr(cmd, NL80211_ATTR_SSID, strlen(ap->ssid),
   2840 				ap->ssid);
   2841 	l_genl_msg_append_attr(cmd, NL80211_ATTR_HIDDEN_SSID, 4,
   2842 				&hidden_ssid);
   2843 	l_genl_msg_append_attr(cmd, NL80211_ATTR_CIPHER_SUITES_PAIRWISE,
   2844 				nl_ciphers_cnt * 4, nl_ciphers);
   2845 	l_genl_msg_append_attr(cmd, NL80211_ATTR_CIPHER_SUITE_GROUP, 4,
   2846 				&group_nl_cipher);
   2847 	l_genl_msg_append_attr(cmd, NL80211_ATTR_WPA_VERSIONS, 4, &wpa_version);
   2848 	l_genl_msg_append_attr(cmd, NL80211_ATTR_AKM_SUITES, 4, &nl_akm);
   2849 	l_genl_msg_append_attr(cmd, NL80211_ATTR_AUTH_TYPE, 4, &auth_type);
   2850 	l_genl_msg_append_attr(cmd, NL80211_ATTR_WIPHY_FREQ, 4,
   2851 				&ap->chandef.frequency);
   2852 	l_genl_msg_append_attr(cmd, NL80211_ATTR_CHANNEL_WIDTH, 4,
   2853 				&ap->chandef.channel_width);
   2854 	if (ap->chandef.center1_frequency)
   2855 		l_genl_msg_append_attr(cmd, NL80211_ATTR_CENTER_FREQ1, 4,
   2856 					&ap->chandef.center1_frequency);
   2857 
   2858 	if (wiphy_supports_probe_resp_offload(wiphy)) {
   2859 		uint8_t probe_resp[head_len + tail_len];
   2860 		uint8_t *ptr = probe_resp;
   2861 
   2862 		ptr += ap_build_beacon_pr_head(ap,
   2863 					MPDU_MANAGEMENT_SUBTYPE_PROBE_RESPONSE,
   2864 					zero_addr, ptr, sizeof(probe_resp));
   2865 		ptr += ap_build_beacon_pr_tail(ap,
   2866 					MPDU_MANAGEMENT_SUBTYPE_PROBE_RESPONSE,
   2867 					NULL, 0, ptr, sizeof(probe_resp) -
   2868 					(ptr - probe_resp));
   2869 
   2870 		l_genl_msg_append_attr(cmd, NL80211_ATTR_PROBE_RESP,
   2871 					ptr - probe_resp, probe_resp);
   2872 	}
   2873 
   2874 	if (wiphy_has_ext_feature(wiphy,
   2875 			NL80211_EXT_FEATURE_CONTROL_PORT_OVER_NL80211)) {
   2876 		l_genl_msg_append_attr(cmd, NL80211_ATTR_SOCKET_OWNER, 0, NULL);
   2877 		l_genl_msg_append_attr(cmd,
   2878 				NL80211_ATTR_CONTROL_PORT_OVER_NL80211,
   2879 				0, NULL);
   2880 	}
   2881 
   2882 	return cmd;
   2883 }
   2884 
   2885 static bool ap_start_send(struct ap_state *ap)
   2886 {
   2887 	struct l_genl_msg *cmd = ap_build_cmd_start_ap(ap);
   2888 
   2889 	if (!cmd) {
   2890 		l_error("ap_build_cmd_start_ap failed");
   2891 		return false;
   2892 	}
   2893 
   2894 	ap->start_stop_cmd_id = l_genl_family_send(ap->nl80211, cmd,
   2895 							ap_start_cb, ap, NULL);
   2896 	if (!ap->start_stop_cmd_id) {
   2897 		l_error("AP_START l_genl_family_send failed");
   2898 		l_genl_msg_unref(cmd);
   2899 		return false;
   2900 	}
   2901 
   2902 	return true;
   2903 }
   2904 
   2905 static void ap_ifaddr4_added_cb(int error, uint16_t type, const void *data,
   2906 				uint32_t len, void *user_data)
   2907 {
   2908 	struct ap_state *ap = user_data;
   2909 
   2910 	ap->rtnl_add_cmd = 0;
   2911 
   2912 	if (error) {
   2913 		l_error("Failed to set IP address");
   2914 		ap_start_failed(ap, error);
   2915 		return;
   2916 	}
   2917 
   2918 	if (!ap_start_send(ap))
   2919 		ap_start_failed(ap, -EIO);
   2920 }
   2921 
   2922 static bool ap_parse_new_station_ies(const void *data, uint16_t len,
   2923 					uint8_t **rsn_out,
   2924 					struct l_uintset **rates_out)
   2925 {
   2926 	struct ie_tlv_iter iter;
   2927 	uint8_t *rsn = NULL;
   2928 	struct l_uintset *rates = NULL;
   2929 
   2930 	ie_tlv_iter_init(&iter, data, len);
   2931 
   2932 	while (ie_tlv_iter_next(&iter)) {
   2933 		switch (ie_tlv_iter_get_tag(&iter)) {
   2934 		case IE_TYPE_RSN:
   2935 			if (rsn || ie_parse_rsne(&iter, NULL) < 0)
   2936 				goto parse_error;
   2937 
   2938 			rsn = l_memdup(ie_tlv_iter_get_data(&iter) - 2,
   2939 					ie_tlv_iter_get_length(&iter) + 2);
   2940 			break;
   2941 		case IE_TYPE_EXTENDED_SUPPORTED_RATES:
   2942 			if (rates || ap_parse_supported_rates(&iter, &rates) <
   2943 					0)
   2944 				goto parse_error;
   2945 
   2946 			break;
   2947 		}
   2948 	}
   2949 
   2950 	*rsn_out = rsn;
   2951 
   2952 	if (rates_out)
   2953 		*rates_out = rates;
   2954 	else
   2955 		l_uintset_free(rates);
   2956 
   2957 	return true;
   2958 
   2959 parse_error:
   2960 	if (rsn)
   2961 		l_free(rsn);
   2962 
   2963 	if (rates)
   2964 		l_uintset_free(rates);
   2965 
   2966 	return false;
   2967 }
   2968 
   2969 static void ap_handle_new_station(struct ap_state *ap, struct l_genl_msg *msg)
   2970 {
   2971 	struct sta_state *sta;
   2972 	struct l_genl_attr attr;
   2973 	uint16_t type;
   2974 	uint16_t len;
   2975 	const void *data;
   2976 	const uint8_t *mac = NULL;
   2977 	uint8_t *assoc_rsne = NULL;
   2978 
   2979 	if (!l_genl_attr_init(&attr, msg))
   2980 		return;
   2981 
   2982 	while (l_genl_attr_next(&attr, &type, &len, &data)) {
   2983 		switch (type) {
   2984 		case NL80211_ATTR_IE:
   2985 			if (assoc_rsne)
   2986 				goto cleanup;
   2987 
   2988 			if (!ap_parse_new_station_ies(data, len, &assoc_rsne,
   2989 							NULL))
   2990 				return;
   2991 			break;
   2992 		case NL80211_ATTR_MAC:
   2993 			if (len != 6)
   2994 				goto cleanup;
   2995 
   2996 			mac = data;
   2997 			break;
   2998 		}
   2999 	}
   3000 
   3001 	if (!assoc_rsne || !mac)
   3002 		goto cleanup;
   3003 
   3004 	/*
   3005 	 * Softmac's should already have a station created. The above check
   3006 	 * may also fail for softmac cards.
   3007 	 */
   3008 	sta = l_queue_find(ap->sta_states, ap_sta_match_addr, mac);
   3009 	if (sta)
   3010 		goto cleanup;
   3011 
   3012 	sta = l_new(struct sta_state, 1);
   3013 	memcpy(sta->addr, mac, 6);
   3014 	sta->ap = ap;
   3015 	sta->assoc_rsne = assoc_rsne;
   3016 	sta->aid = ++ap->last_aid;
   3017 
   3018 	sta->associated = true;
   3019 
   3020 	if (!ap->sta_states)
   3021 		ap->sta_states = l_queue_new();
   3022 
   3023 	l_queue_push_tail(ap->sta_states, sta);
   3024 
   3025 	if (ap->supports_ht)
   3026 		ap_update_beacon(ap);
   3027 
   3028 	msg = nl80211_build_set_station_unauthorized(
   3029 					netdev_get_ifindex(ap->netdev), mac);
   3030 
   3031 	if (!l_genl_family_send(ap->nl80211, msg, ap_associate_sta_cb,
   3032 								sta, NULL)) {
   3033 		l_genl_msg_unref(msg);
   3034 		l_error("Issuing SET_STATION failed");
   3035 		ap_del_station(sta, MMPDU_REASON_CODE_UNSPECIFIED, true);
   3036 	}
   3037 
   3038 	return;
   3039 
   3040 cleanup:
   3041 	l_free(assoc_rsne);
   3042 }
   3043 
   3044 static void ap_handle_del_station(struct ap_state *ap, struct l_genl_msg *msg)
   3045 {
   3046 	struct l_genl_attr attr;
   3047 	uint16_t type;
   3048 	uint16_t len;
   3049 	const void *data;
   3050 	uint8_t mac[6];
   3051 	uint16_t reason = MMPDU_REASON_CODE_UNSPECIFIED;
   3052 
   3053 	if (!l_genl_attr_init(&attr, msg))
   3054 		return;
   3055 
   3056 	while (l_genl_attr_next(&attr, &type, &len, &data)) {
   3057 		switch (type) {
   3058 		case NL80211_ATTR_MAC:
   3059 			if (len != 6)
   3060 				return;
   3061 
   3062 			memcpy(mac, data, 6);
   3063 			break;
   3064 		case NL80211_ATTR_REASON_CODE:
   3065 			if (len != 2)
   3066 				return;
   3067 
   3068 			reason = l_get_u16(data);
   3069 		}
   3070 	}
   3071 
   3072 	ap_station_disconnect(ap, mac, reason);
   3073 }
   3074 
   3075 static void ap_mlme_notify(struct l_genl_msg *msg, void *user_data)
   3076 {
   3077 	struct ap_state *ap = user_data;
   3078 	uint32_t ifindex;
   3079 
   3080 	if (nl80211_parse_attrs(msg, NL80211_ATTR_IFINDEX, &ifindex,
   3081 				NL80211_ATTR_UNSPEC) < 0 ||
   3082 			ifindex != netdev_get_ifindex(ap->netdev))
   3083 		return;
   3084 
   3085 	switch (l_genl_msg_get_command(msg)) {
   3086 	case NL80211_CMD_STOP_AP:
   3087 		ap->in_event = true;
   3088 
   3089 		if (ap->start_stop_cmd_id) {
   3090 			struct ap_event_start_failed_data data = { -ECANCELED };
   3091 
   3092 			l_genl_family_cancel(ap->nl80211,
   3093 						ap->start_stop_cmd_id);
   3094 			ap->start_stop_cmd_id = 0;
   3095 			ap->ops->handle_event(AP_EVENT_START_FAILED, &data,
   3096 						ap->user_data);
   3097 		} else if (ap->started) {
   3098 			ap->started = false;
   3099 			ap->ops->handle_event(AP_EVENT_STOPPING, NULL,
   3100 						ap->user_data);
   3101 		}
   3102 
   3103 		ap_reset(ap);
   3104 		l_genl_family_free(ap->nl80211);
   3105 		l_free(ap);
   3106 		break;
   3107 	case NL80211_CMD_NEW_STATION:
   3108 		ap_handle_new_station(ap, msg);
   3109 		break;
   3110 	case NL80211_CMD_DEL_STATION:
   3111 		ap_handle_del_station(ap, msg);
   3112 		break;
   3113 	}
   3114 }
   3115 
   3116 static void ap_get_gateway4_mac_cb(int error, const uint8_t *hwaddr,
   3117 					size_t hwaddr_len, void *user_data)
   3118 {
   3119 	struct ap_state *ap = user_data;
   3120 
   3121 	ap->rtnl_get_gateway4_mac_cmd = 0;
   3122 
   3123 	if (error) {
   3124 		l_debug("Error: %s (%i)", strerror(-error), -error);
   3125 		return;
   3126 	}
   3127 
   3128 	if (L_WARN_ON(unlikely(hwaddr_len != 6)))
   3129 		return;
   3130 
   3131 	l_debug("Resolved mac to " MAC, MAC_STR(hwaddr));
   3132 	memcpy(ap->netconfig_gateway4_mac, hwaddr, 6);
   3133 }
   3134 
   3135 static void ap_get_dns4_mac_cb(int error, const uint8_t *hwaddr,
   3136 					size_t hwaddr_len, void *user_data)
   3137 {
   3138 	struct ap_state *ap = user_data;
   3139 
   3140 	ap->rtnl_get_dns4_mac_cmd = 0;
   3141 
   3142 	if (error) {
   3143 		l_debug("Error: %s (%i)", strerror(-error), -error);
   3144 		return;
   3145 	}
   3146 
   3147 	if (L_WARN_ON(unlikely(hwaddr_len != 6)))
   3148 		return;
   3149 
   3150 	l_debug("Resolved mac to " MAC, MAC_STR(hwaddr));
   3151 	memcpy(ap->netconfig_dns4_mac, hwaddr, 6);
   3152 }
   3153 
   3154 static void ap_query_macs(struct ap_state *ap, const char *addr_str,
   3155 				uint8_t prefix_len, const char *gateway_str,
   3156 				const char **dns_str_list)
   3157 {
   3158 	uint32_t local = IP4_FROM_STR(addr_str);
   3159 	uint32_t gateway = 0;
   3160 	uint32_t dns = 0;
   3161 	uint32_t ifindex = netdev_get_ifindex(ap->netdev);
   3162 
   3163 	/*
   3164 	 * For simplicity only check the ARP/NDP tables to see if we already
   3165 	 * have the MACs that we need.  There doesn't seem to be an API to
   3166 	 * actually resolve addresses that are not in these tables other than
   3167 	 * by triggering IP traffic to those hosts, such as a ping.  In a PC
   3168 	 * or mobile device scenario we're likely to have these MACs already,
   3169 	 * otherwise we give up as this is a pretty low-priority feature.
   3170 	 */
   3171 
   3172 	if (gateway_str) {
   3173 		gateway = IP4_FROM_STR(gateway_str);
   3174 		if (L_WARN_ON(unlikely(!gateway)))
   3175 			return;
   3176 
   3177 		if (gateway == local)
   3178 			memcpy(ap->netconfig_gateway4_mac,
   3179 				netdev_get_address(ap->netdev), 6);
   3180 		else {
   3181 			ap->rtnl_get_gateway4_mac_cmd =
   3182 				l_rtnl_neighbor_get_hwaddr(rtnl, ifindex,
   3183 							AF_INET, &gateway,
   3184 							ap_get_gateway4_mac_cb,
   3185 							ap, NULL);
   3186 			if (!ap->rtnl_get_gateway4_mac_cmd)
   3187 				l_debug("l_rtnl_neighbor_get_hwaddr() failed "
   3188 					"for the gateway IP");
   3189 		}
   3190 	}
   3191 
   3192 	if (dns_str_list) {
   3193 		dns = IP4_FROM_STR(dns_str_list[0]);
   3194 		if (L_WARN_ON(unlikely(!dns)))
   3195 			return;
   3196 
   3197 		/* TODO: can also skip query if dns == gateway */
   3198 		if (dns == local)
   3199 			memcpy(ap->netconfig_dns4_mac,
   3200 				netdev_get_address(ap->netdev), 6);
   3201 		else if (util_ip_subnet_match(prefix_len, &dns, &local)) {
   3202 			ap->rtnl_get_dns4_mac_cmd =
   3203 				l_rtnl_neighbor_get_hwaddr(rtnl, ifindex,
   3204 							AF_INET, &dns,
   3205 							ap_get_dns4_mac_cb,
   3206 							ap, NULL);
   3207 			if (!ap->rtnl_get_dns4_mac_cmd)
   3208 				l_debug("l_rtnl_neighbor_get_hwaddr() failed "
   3209 					"for the DNS IP");
   3210 		}
   3211 	}
   3212 }
   3213 
   3214 #define AP_DEFAULT_IPV4_PREFIX_LEN 28
   3215 
   3216 static int ap_setup_netconfig4(struct ap_state *ap, const char **addr_str_list,
   3217 				uint8_t prefix_len, const char *gateway_str,
   3218 				const char **ip_range,
   3219 				const char **dns_str_list,
   3220 				unsigned int lease_time)
   3221 {
   3222 	uint32_t ifindex = netdev_get_ifindex(ap->netdev);
   3223 	struct l_rtnl_address *existing_addr = ip_pool_get_addr4(ifindex);
   3224 	struct l_rtnl_address *new_addr = NULL;
   3225 	int ret;
   3226 	struct in_addr ia;
   3227 	struct l_dhcp_server *dhcp = NULL;
   3228 	bool r;
   3229 	char addr_str_buf[INET_ADDRSTRLEN];
   3230 
   3231 	dhcp = l_dhcp_server_new(ifindex);
   3232 	if (!dhcp) {
   3233 		l_error("Failed to create DHCP server on ifindex %u", ifindex);
   3234 		ret = -EIO;
   3235 		goto cleanup;
   3236 	}
   3237 
   3238 	if (getenv("IWD_DHCP_DEBUG"))
   3239 		l_dhcp_server_set_debug(dhcp, do_debug,
   3240 					"[DHCPv4 SERV] ", NULL);
   3241 
   3242 	/*
   3243 	 * The address pool specified for this AP (if any) has the priority,
   3244 	 * next is the address currently set on the interface (if any) and
   3245 	 * last is the global AP address pool (APRanges setting).
   3246 	 */
   3247 	if (addr_str_list) {
   3248 		if (!prefix_len)
   3249 			prefix_len = AP_DEFAULT_IPV4_PREFIX_LEN;
   3250 
   3251 		ret = ip_pool_select_addr4(addr_str_list, prefix_len,
   3252 						&new_addr);
   3253 	} else if (existing_addr &&
   3254 			l_rtnl_address_get_prefix_length(existing_addr) <
   3255 			31) {
   3256 		if (!prefix_len)
   3257 			prefix_len = l_rtnl_address_get_prefix_length(
   3258 								existing_addr);
   3259 
   3260 		if (!l_rtnl_address_get_address(existing_addr, addr_str_buf)) {
   3261 			ret = -EIO;
   3262 			goto cleanup;
   3263 		}
   3264 
   3265 		new_addr = l_rtnl_address_new(addr_str_buf, prefix_len);
   3266 		ret = 0;
   3267 	} else {
   3268 		if (!prefix_len)
   3269 			prefix_len = AP_DEFAULT_IPV4_PREFIX_LEN;
   3270 
   3271 		ret = ip_pool_select_addr4((const char **) global_addr4_strs,
   3272 						prefix_len, &new_addr);
   3273 	}
   3274 
   3275 	if (ret)
   3276 		goto cleanup;
   3277 
   3278 	ret = -EIO;
   3279 
   3280 	/*
   3281 	 * l_dhcp_server_start() would retrieve the current IPv4 from
   3282 	 * the interface but set it anyway in case there are multiple
   3283 	 * addresses, saves one ioctl too.
   3284 	 */
   3285 	if (!l_rtnl_address_get_address(new_addr, addr_str_buf)) {
   3286 		l_error("l_rtnl_address_get_address failed");
   3287 		goto cleanup;
   3288 	}
   3289 
   3290 	if (!l_dhcp_server_set_ip_address(dhcp, addr_str_buf)) {
   3291 		l_error("l_dhcp_server_set_ip_address failed");
   3292 		goto cleanup;
   3293 	}
   3294 
   3295 	ia.s_addr = htonl(util_netmask_from_prefix(prefix_len));
   3296 
   3297 	if (!l_dhcp_server_set_netmask(dhcp, inet_ntoa(ia))) {
   3298 		l_error("l_dhcp_server_set_netmask failed");
   3299 		goto cleanup;
   3300 	}
   3301 
   3302 	if (gateway_str && !l_dhcp_server_set_gateway(dhcp, gateway_str)) {
   3303 		l_error("l_dhcp_server_set_gateway failed");
   3304 		goto cleanup;
   3305 	}
   3306 
   3307 	if (ip_range) {
   3308 		r = l_dhcp_server_set_ip_range(dhcp, ip_range[0], ip_range[1]);
   3309 		if (!r) {
   3310 			l_error("l_dhcp_server_set_ip_range failed");
   3311 			goto cleanup;
   3312 		}
   3313 	}
   3314 
   3315 	if (dns_str_list) {
   3316 		r = l_dhcp_server_set_dns(dhcp, (char **) dns_str_list);
   3317 		if (!r) {
   3318 			l_error("l_dhcp_server_set_dns failed");
   3319 			goto cleanup;
   3320 		}
   3321 	}
   3322 
   3323 	if (lease_time && !l_dhcp_server_set_lease_time(dhcp, lease_time)) {
   3324 		l_error("l_dhcp_server_set_lease_time failed");
   3325 		goto cleanup;
   3326 	}
   3327 
   3328 	ap->netconfig_set_addr4 = true;
   3329 	ap->netconfig_addr4 = l_steal_ptr(new_addr);
   3330 	ap->netconfig_dhcp = l_steal_ptr(dhcp);
   3331 	ret = 0;
   3332 
   3333 	if (existing_addr && l_rtnl_address_get_prefix_length(existing_addr) >
   3334 			prefix_len) {
   3335 		char addr_str_buf2[INET_ADDRSTRLEN];
   3336 
   3337 		if (l_rtnl_address_get_address(existing_addr, addr_str_buf2) &&
   3338 				!strcmp(addr_str_buf, addr_str_buf2))
   3339 			ap->netconfig_set_addr4 = false;
   3340 	}
   3341 
   3342 	ap_query_macs(ap, addr_str_buf, prefix_len, gateway_str, dns_str_list);
   3343 
   3344 cleanup:
   3345 	l_dhcp_server_destroy(dhcp);
   3346 	l_rtnl_address_free(new_addr);
   3347 	l_rtnl_address_free(existing_addr);
   3348 	return ret;
   3349 }
   3350 
   3351 static int ap_load_ipv4(struct ap_state *ap, const struct l_settings *config)
   3352 {
   3353 	int ret = -EINVAL;
   3354 	char **addr_str_list = NULL;
   3355 	uint32_t static_addr = 0;
   3356 	uint8_t prefix_len = 0;
   3357 	char *gateway_str = NULL;
   3358 	char **ip_range = NULL;
   3359 	char **dns_str_list = NULL;
   3360 	unsigned int lease_time = 0;
   3361 	struct in_addr ia;
   3362 
   3363 	if (!l_settings_has_group(config, "IPv4") || !netconfig_enabled())
   3364 		return 0;
   3365 
   3366 	if (l_settings_has_key(config, "IPv4", "Address")) {
   3367 		addr_str_list = l_settings_get_string_list(config, "IPv4",
   3368 								"Address", ',');
   3369 		if (!addr_str_list || !*addr_str_list) {
   3370 			l_error("Can't parse the profile [IPv4].Address "
   3371 				"setting as a string list");
   3372 			goto done;
   3373 		}
   3374 
   3375 		/* Check for the static IP syntax: Address=<IP> */
   3376 		if (l_strv_length(addr_str_list) == 1 &&
   3377 				inet_pton(AF_INET, *addr_str_list, &ia) == 1)
   3378 			static_addr = ntohl(ia.s_addr);
   3379 	}
   3380 
   3381 	if (l_settings_has_key(config, "IPv4", "Netmask")) {
   3382 		L_AUTO_FREE_VAR(char *, netmask_str) =
   3383 			l_settings_get_string(config, "IPv4", "Netmask");
   3384 
   3385 		if (inet_pton(AF_INET, netmask_str, &ia) != 1) {
   3386 			l_error("Can't parse the profile [IPv4].Netmask "
   3387 				"setting");
   3388 			goto done;
   3389 		}
   3390 
   3391 		prefix_len = __builtin_popcount(ia.s_addr);
   3392 
   3393 		if (ntohl(ia.s_addr) != util_netmask_from_prefix(prefix_len)) {
   3394 			l_error("Invalid profile [IPv4].Netmask value");
   3395 			goto done;
   3396 		}
   3397 	}
   3398 
   3399 	if (l_settings_has_key(config, "IPv4", "Gateway")) {
   3400 		gateway_str = l_settings_get_string(config, "IPv4", "Gateway");
   3401 		if (!gateway_str) {
   3402 			l_error("Invalid profile [IPv4].Gateway value");
   3403 			goto done;
   3404 		}
   3405 	}
   3406 
   3407 	if (l_settings_get_value(config, "IPv4", "IPRange")) {
   3408 		int i;
   3409 		uint32_t netmask;
   3410 		uint8_t tmp_len = prefix_len ?: AP_DEFAULT_IPV4_PREFIX_LEN;
   3411 
   3412 		ip_range = l_settings_get_string_list(config, "IPv4",
   3413 							"IPRange", ',');
   3414 
   3415 		if (!static_addr) {
   3416 			l_error("[IPv4].IPRange only makes sense in an AP "
   3417 				"profile if a static local address has also "
   3418 				"been specified");
   3419 			goto done;
   3420 		}
   3421 
   3422 		if (!ip_range || l_strv_length(ip_range) != 2) {
   3423 			l_error("Can't parse the profile [IPv4].IPRange "
   3424 				"setting as two address strings");
   3425 			goto done;
   3426 		}
   3427 
   3428 		netmask = util_netmask_from_prefix(tmp_len);
   3429 
   3430 		for (i = 0; i < 2; i++) {
   3431 			struct in_addr range_addr;
   3432 
   3433 			if (inet_pton(AF_INET, ip_range[i], &range_addr) != 1) {
   3434 				l_error("Can't parse address in "
   3435 					"[IPv4].IPRange[%i]", i + 1);
   3436 				goto done;
   3437 			}
   3438 
   3439 			if ((static_addr ^ ntohl(range_addr.s_addr)) &
   3440 					netmask) {
   3441 				ia.s_addr = htonl(static_addr);
   3442 				l_error("[IPv4].IPRange[%i] is not in the "
   3443 					"%s/%i subnet", i + 1, inet_ntoa(ia),
   3444 					tmp_len);
   3445 				goto done;
   3446 			}
   3447 		}
   3448 	}
   3449 
   3450 	if (l_settings_has_key(config, "IPv4", "DNSList")) {
   3451 		dns_str_list = l_settings_get_string_list(config, "IPv4",
   3452 								"DNSList", ',');
   3453 		if (!dns_str_list || !*dns_str_list) {
   3454 			l_error("Can't parse the profile [IPv4].DNSList "
   3455 				"setting as a string list");
   3456 			goto done;
   3457 		}
   3458 	}
   3459 
   3460 	if (l_settings_has_key(config, "IPv4", "LeaseTime")) {
   3461 		if (!l_settings_get_uint(config, "IPv4", "LeaseTime",
   3462 						&lease_time) ||
   3463 				lease_time < 1) {
   3464 			l_error("Error parsing [IPv4].LeaseTime as a positive "
   3465 				"integer");
   3466 			goto done;
   3467 		}
   3468 	}
   3469 
   3470 	ret = ap_setup_netconfig4(ap, (const char **) addr_str_list, prefix_len,
   3471 					gateway_str, (const char **) ip_range,
   3472 					(const char **) dns_str_list,
   3473 					lease_time);
   3474 
   3475 done:
   3476 	l_strv_free(addr_str_list);
   3477 	l_free(gateway_str);
   3478 	l_strv_free(ip_range);
   3479 	l_strv_free(dns_str_list);
   3480 	return ret;
   3481 }
   3482 
   3483 static bool ap_load_psk(struct ap_state *ap, const struct l_settings *config)
   3484 {
   3485 	L_AUTO_FREE_VAR(char *, passphrase) =
   3486 		l_settings_get_string(config, "Security", "Passphrase");
   3487 	int err;
   3488 
   3489 	if (passphrase) {
   3490 		if (strlen(passphrase) > 63) {
   3491 			l_error("AP [Security].Passphrase must not exceed "
   3492 				"63 characters");
   3493 			return false;
   3494 		}
   3495 
   3496 		strcpy(ap->passphrase, passphrase);
   3497 	}
   3498 
   3499 	if (l_settings_has_key(config, "Security", "PreSharedKey")) {
   3500 		size_t psk_len;
   3501 		L_AUTO_FREE_VAR(uint8_t *, psk) = l_settings_get_bytes(config,
   3502 								"Security",
   3503 								"PreSharedKey",
   3504 								&psk_len);
   3505 
   3506 		if (!psk || psk_len != 32) {
   3507 			l_error("AP [Security].PreSharedKey must be a 32-byte "
   3508 				"hexstring");
   3509 			return false;
   3510 		}
   3511 
   3512 		memcpy(ap->psk, psk, 32);
   3513 		return true;
   3514 	}
   3515 
   3516 	if (!passphrase) {
   3517 		l_error("AP requires at least one of [Security].PreSharedKey, "
   3518 			"[Security].Passphrase to be present");
   3519 		return false;
   3520 	}
   3521 
   3522 	err = crypto_psk_from_passphrase(passphrase, (uint8_t *) ap->ssid,
   3523 						strlen(ap->ssid), ap->psk);
   3524 	if (err < 0) {
   3525 		l_error("AP couldn't generate the PSK from given "
   3526 			"[Security].Passphrase value: %s (%i)",
   3527 			strerror(-err), -err);
   3528 		return false;
   3529 	}
   3530 
   3531 	return true;
   3532 }
   3533 
   3534 /*
   3535  * Note: only PTK/GTK ciphers are supported here since this is all these are
   3536  *       used for.
   3537  */
   3538 static enum ie_rsn_cipher_suite ap_string_to_cipher(const char *str)
   3539 {
   3540 	if (!strcmp(str, "UseGroupCipher"))
   3541 		return IE_RSN_CIPHER_SUITE_USE_GROUP_CIPHER;
   3542 	else if (!strcmp(str, "TKIP"))
   3543 		return IE_RSN_CIPHER_SUITE_TKIP;
   3544 	else if (!strcmp(str, "CCMP-128") || !strcmp(str, "CCMP"))
   3545 		return IE_RSN_CIPHER_SUITE_CCMP;
   3546 	else if (!strcmp(str, "GCMP-128") || !strcmp(str, "GCMP"))
   3547 		return IE_RSN_CIPHER_SUITE_GCMP;
   3548 	else if (!strcmp(str, "GCMP-256"))
   3549 		return IE_RSN_CIPHER_SUITE_GCMP_256;
   3550 	else if (!strcmp(str, "CCMP-256"))
   3551 		return IE_RSN_CIPHER_SUITE_CCMP_256;
   3552 	else
   3553 		return 0;
   3554 }
   3555 
   3556 static char **ap_ciphers_to_strv(uint16_t ciphers)
   3557 {
   3558 	uint16_t i;
   3559 	char **list = l_strv_new();
   3560 
   3561 	for (i = 0; i < 16; i++) {
   3562 		if (!(ciphers & (1 << i)))
   3563 			continue;
   3564 
   3565 		list = l_strv_append(list,
   3566 					ie_rsn_cipher_suite_to_string(1 << i));
   3567 	}
   3568 
   3569 	return list;
   3570 }
   3571 
   3572 static bool ap_validate_band_channel(struct ap_state *ap)
   3573 {
   3574 	struct wiphy *wiphy = netdev_get_wiphy(ap->netdev);
   3575 	uint32_t freq;
   3576 	const struct band_freq_attrs *attr;
   3577 
   3578 	if (!(wiphy_get_supported_bands(wiphy) & ap->band)) {
   3579 		l_error("AP hardware does not support band");
   3580 		return -EINVAL;
   3581 	}
   3582 
   3583 	freq = band_channel_to_freq(ap->channel, ap->band);
   3584 	if (!freq) {
   3585 		l_error("AP invalid band (%s) and channel (%u) combination",
   3586 			(ap->band & BAND_FREQ_5_GHZ) ? "5GHz" : "2.4GHz",
   3587 			ap->channel);
   3588 		return false;
   3589 	}
   3590 
   3591 	attr = wiphy_get_frequency_info(wiphy, freq);
   3592 	if (!attr || attr->disabled) {
   3593 		l_error("AP frequency %u disabled or unsupported", freq);
   3594 		return false;
   3595 	}
   3596 
   3597 	if (ap->supports_ht) {
   3598 		if (band_freq_to_ht_chandef(freq, attr, &ap->chandef) < 0) {
   3599 			/*
   3600 			 * This is unlikely ever to fail since there are no
   3601 			 * 20Mhz restrictions, but just in case fall back to
   3602 			 * non-HT.
   3603 			 */
   3604 			ap->supports_ht = false;
   3605 
   3606 			l_warn("AP could not find HT chandef for frequency %u"
   3607 				" using 20Mhz no-HT", freq);
   3608 
   3609 			goto no_ht;
   3610 		}
   3611 	} else {
   3612 no_ht:
   3613 		ap->chandef.frequency = freq;
   3614 		ap->chandef.channel_width = BAND_CHANDEF_WIDTH_20NOHT;
   3615 	}
   3616 
   3617 	l_debug("AP using frequency %u and channel width %s",
   3618 			ap->chandef.frequency,
   3619 			band_chandef_width_to_string(
   3620 				ap->chandef.channel_width));
   3621 
   3622 	return true;
   3623 }
   3624 
   3625 static int ap_load_config(struct ap_state *ap, const struct l_settings *config,
   3626 				bool *out_cck_rates)
   3627 {
   3628 	struct wiphy *wiphy = netdev_get_wiphy(ap->netdev);
   3629 	size_t len;
   3630 	L_AUTO_FREE_VAR(char *, strval) = NULL;
   3631 	_auto_(l_strv_free) char **ciphers_str = NULL;
   3632 	uint16_t cipher_mask;
   3633 	int err;
   3634 	int i;
   3635 
   3636 	strval = l_settings_get_string(config, "General", "SSID");
   3637 	if (L_WARN_ON(!strval))
   3638 		return -ENOMSG;
   3639 
   3640 	len = strlen(strval);
   3641 	if (len < 1 || len > SSID_MAX_SIZE) {
   3642 		l_error("AP SSID length outside the [1, 32] range");
   3643 		return -EINVAL;
   3644 	}
   3645 
   3646 	if (L_WARN_ON(!l_utf8_validate(strval, len, NULL)))
   3647 		return -EINVAL;
   3648 
   3649 	strcpy(ap->ssid, strval);
   3650 	l_free(l_steal_ptr(strval));
   3651 
   3652 	if (!ap_load_psk(ap, config))
   3653 		return -EINVAL;
   3654 
   3655 	/*
   3656 	 * This looks at the network configuration settings in @config and
   3657 	 * relevant global settings and if it determines that netconfig is to
   3658 	 * be enabled for the AP, it both creates the DHCP server object and
   3659 	 * processes IP settings, applying the defaults where needed.
   3660 	 */
   3661 	err = ap_load_ipv4(ap, config);
   3662 	if (err)
   3663 		return err;
   3664 
   3665 	if (l_settings_has_key(config, "General", "Channel")) {
   3666 		unsigned int uintval;
   3667 
   3668 		if (!l_settings_get_uint(config, "General", "Channel",
   3669 						&uintval)) {
   3670 			l_error("AP Channel value unsupported");
   3671 			return -EINVAL;
   3672 		}
   3673 
   3674 		ap->channel = uintval;
   3675 
   3676 		/*
   3677 		 * 6GHz is not supported so we can use only a channel number to
   3678 		 * distinguish between 2.4 and 5GHz.
   3679 		 */
   3680 		if (ap->channel >= 36)
   3681 			ap->band = BAND_FREQ_5_GHZ;
   3682 		else
   3683 			ap->band = BAND_FREQ_2_4_GHZ;
   3684 	} else {
   3685 		/* TODO: Start a Get Survey to decide the channel */
   3686 		ap->channel = 6;
   3687 		ap->band = BAND_FREQ_2_4_GHZ;
   3688 	}
   3689 
   3690 	if (l_settings_has_key(config, "General", "DisableHT")) {
   3691 		bool boolval;
   3692 
   3693 		if (!l_settings_get_bool(config, "General", "DisableHT",
   3694 						&boolval)) {
   3695 			l_error("AP [General].DisableHT not a valid boolean");
   3696 			return -EINVAL;
   3697 		}
   3698 
   3699 		ap->supports_ht = !boolval;
   3700 	} else
   3701 		ap->supports_ht = wiphy_get_ht_capabilities(wiphy, ap->band,
   3702 							NULL) != NULL;
   3703 
   3704 	if (!ap_validate_band_channel(ap)) {
   3705 		l_error("AP Band and Channel combination invalid");
   3706 		return -EINVAL;
   3707 	}
   3708 
   3709 	strval = l_settings_get_string(config, "WSC", "DeviceName");
   3710 	if (strval) {
   3711 		len = strlen(strval);
   3712 
   3713 		if (len > 32) {
   3714 			l_error("AP WSC name length outside the [1, 32] range");
   3715 			return -EINVAL;
   3716 		}
   3717 
   3718 		if (!l_utf8_validate(strval, len, NULL)) {
   3719 			l_error("AP WSC name doesn't validate as UTF-8");
   3720 			return -EINVAL;
   3721 		}
   3722 
   3723 		strcpy(ap->wsc_name, strval);
   3724 		l_free(l_steal_ptr(strval));
   3725 	} else
   3726 		memcpy(ap->wsc_name, ap->ssid, 33);
   3727 
   3728 	strval = l_settings_get_string(config, "WSC", "PrimaryDeviceType");
   3729 	if (strval) {
   3730 		bool ok = wsc_device_type_from_setting_str(strval,
   3731 						&ap->wsc_primary_device_type);
   3732 
   3733 		if (!ok) {
   3734 			l_error("AP [WSC].PrimaryDeviceType format unknown");
   3735 			return -EINVAL;
   3736 		}
   3737 
   3738 		l_free(l_steal_ptr(strval));
   3739 	} else {
   3740 		/* Make ourselves a WFA standard PC by default */
   3741 		ap->wsc_primary_device_type.category = 1;
   3742 		memcpy(ap->wsc_primary_device_type.oui, wsc_wfa_oui, 3);
   3743 		ap->wsc_primary_device_type.oui_type = 0x04;
   3744 		ap->wsc_primary_device_type.subcategory = 1;
   3745 	}
   3746 
   3747 	if (l_settings_get_value(config, "WSC", "AuthorizedMACs")) {
   3748 		char **strvval;
   3749 		unsigned int i;
   3750 
   3751 		strvval = l_settings_get_string_list(config, "WSC",
   3752 							"AuthorizedMACs", ',');
   3753 		if (!strvval) {
   3754 			l_error("AP Authorized MACs list format wrong");
   3755 			return -EINVAL;
   3756 		}
   3757 
   3758 		ap->authorized_macs_num = l_strv_length(strvval);
   3759 		ap->authorized_macs = l_malloc(ap->authorized_macs_num * 6);
   3760 
   3761 		for (i = 0; strvval[i]; i++)
   3762 			if (!util_string_to_address(strvval[i],
   3763 						ap->authorized_macs + i * 6)) {
   3764 				l_error("Bad authorized MAC format: %s",
   3765 					strvval[i]);
   3766 				l_strfreev(strvval);
   3767 				return -EINVAL;
   3768 			}
   3769 
   3770 		l_strfreev(strvval);
   3771 	}
   3772 
   3773 	if (l_settings_has_key(config, "General", "RekeyTimeout")) {
   3774 		unsigned int uintval;
   3775 
   3776 		if (!l_settings_get_uint(config, "General",
   3777 						"RekeyTimeout", &uintval)) {
   3778 			l_error("AP [General].RekeyTimeout is not valid");
   3779 			return -EINVAL;
   3780 		}
   3781 
   3782 		ap->rekey_time = uintval * L_USEC_PER_SEC;
   3783 	} else
   3784 		ap->rekey_time = 0;
   3785 
   3786 	/*
   3787 	 * Since 5GHz won't ever support only CCK rates we can ignore this
   3788 	 * setting on that band.
   3789 	 */
   3790 	if (ap->band & BAND_FREQ_5_GHZ)
   3791 		*out_cck_rates = false;
   3792 	else if (l_settings_get_value(config, "General", "NoCCKRates")) {
   3793 		bool boolval;
   3794 
   3795 		if (!l_settings_get_bool(config, "General", "NoCCKRates",
   3796 						&boolval)) {
   3797 			l_error("AP [General].NoCCKRates not a valid "
   3798 				"boolean");
   3799 			return -EINVAL;
   3800 		}
   3801 
   3802 		*out_cck_rates = !boolval;
   3803 	} else
   3804 		*out_cck_rates = true;
   3805 
   3806 	cipher_mask = wiphy_get_supported_ciphers(wiphy, IE_GROUP_CIPHERS);
   3807 
   3808 	/* If the config sets a group cipher use that directly */
   3809 	strval = l_settings_get_string(config, "Security", "GroupCipher");
   3810 	if (strval) {
   3811 		enum ie_rsn_cipher_suite cipher = ap_string_to_cipher(strval);
   3812 
   3813 		if (!cipher || !(cipher & cipher_mask)) {
   3814 			l_error("Unsupported or unknown group cipher %s",
   3815 					strval);
   3816 			return -ENOTSUP;
   3817 		}
   3818 
   3819 		ap->group_cipher = cipher;
   3820 		l_free(l_steal_ptr(strval));
   3821 	} else {
   3822 		/* No config override, use CCMP (or TKIP if not supported) */
   3823 		if (cipher_mask & IE_RSN_CIPHER_SUITE_CCMP)
   3824 			ap->group_cipher = IE_RSN_CIPHER_SUITE_CCMP;
   3825 		else
   3826 			ap->group_cipher = IE_RSN_CIPHER_SUITE_TKIP;
   3827 	}
   3828 
   3829 	cipher_mask = wiphy_get_supported_ciphers(wiphy, IE_PAIRWISE_CIPHERS);
   3830 
   3831 	ciphers_str = l_settings_get_string_list(config, "Security",
   3832 						"PairwiseCiphers", ',');
   3833 	for (i = 0; ciphers_str && ciphers_str[i]; i++) {
   3834 		enum ie_rsn_cipher_suite cipher =
   3835 					ap_string_to_cipher(ciphers_str[i]);
   3836 
   3837 		/*
   3838 		 * Constrain list to only values in both supported ciphers and
   3839 		 * the cipher list provided.
   3840 		 */
   3841 		if (!cipher || !(cipher & cipher_mask)) {
   3842 			l_error("Unsupported or unknown pairwise cipher %s",
   3843 					ciphers_str[i]);
   3844 			return -ENOTSUP;
   3845 		}
   3846 
   3847 		ap->ciphers |= cipher;
   3848 	}
   3849 
   3850 	if (!ap->ciphers) {
   3851 		/*
   3852 		 * Default behavior if no ciphers are specified, disable TKIP
   3853 		 * for security if CCMP is available
   3854 		 */
   3855 		if (cipher_mask & IE_RSN_CIPHER_SUITE_CCMP)
   3856 			cipher_mask &= ~IE_RSN_CIPHER_SUITE_TKIP;
   3857 
   3858 		ap->ciphers = cipher_mask;
   3859 	}
   3860 
   3861 	return 0;
   3862 }
   3863 
   3864 static void ap_pre_scan_trigger(int err, void *user_data)
   3865 {
   3866 	struct ap_state *ap = user_data;
   3867 
   3868 	if (err < 0) {
   3869 		l_error("AP pre-scan failed: %i", err);
   3870 		ap_start_failed(ap, err);
   3871 		return;
   3872 	}
   3873 }
   3874 
   3875 static bool ap_check_channel(struct ap_state *ap)
   3876 {
   3877 	const struct band_freq_attrs *freq_attr;
   3878 
   3879 	freq_attr = wiphy_get_frequency_info(netdev_get_wiphy(ap->netdev),
   3880 				band_channel_to_freq(ap->channel, ap->band));
   3881 	if (L_WARN_ON(!freq_attr))
   3882 		return false;
   3883 
   3884 	/* Check if disabled/no-IR */
   3885 	if (freq_attr->disabled || freq_attr->no_ir)
   3886 		return false;
   3887 
   3888 	return true;
   3889 }
   3890 
   3891 static bool ap_pre_scan_notify(int err, struct l_queue *bss_list,
   3892 				const struct scan_freq_set *freqs,
   3893 				void *user_data)
   3894 {
   3895 	struct ap_state *ap = user_data;
   3896 
   3897 	if (!ap_check_channel(ap)) {
   3898 		l_error("Unable to channel %u even after pre-scan",
   3899 			ap->channel);
   3900 		goto error;
   3901 	}
   3902 
   3903 	if (ap_start_send(ap))
   3904 		return false;
   3905 
   3906 error:
   3907 	ap_start_failed(ap, -ENOTSUP);
   3908 	return false;
   3909 }
   3910 
   3911 static void ap_pre_scan_destroy(void *user_data)
   3912 {
   3913 	struct ap_state *ap = user_data;
   3914 
   3915 	ap->pre_scan_cmd_id = 0;
   3916 }
   3917 
   3918 static bool ap_pre_scan(struct ap_state *ap)
   3919 {
   3920 	ap->pre_scan_cmd_id = scan_passive(netdev_get_wdev_id(ap->netdev),
   3921 						NULL, ap_pre_scan_trigger,
   3922 						ap_pre_scan_notify,
   3923 						ap, ap_pre_scan_destroy);
   3924 
   3925 	return ap->pre_scan_cmd_id != 0;
   3926 }
   3927 
   3928 /*
   3929  * Start a simple independent WPA2 AP on given netdev.
   3930  *
   3931  * @ops.handle_event is required and must react to AP_EVENT_START_FAILED
   3932  * and AP_EVENT_STOPPING by forgetting the ap_state struct, which is
   3933  * going to be freed automatically.
   3934  * In the @config struct the [General].SSID key is required and one of
   3935  * [Security].Passphrase and [Security].PreSharedKey must be filled in.
   3936  * All other fields are optional.
   3937  */
   3938 struct ap_state *ap_start(struct netdev *netdev, struct l_settings *config,
   3939 				const struct ap_ops *ops, int *err_out,
   3940 				void *user_data)
   3941 {
   3942 	struct ap_state *ap;
   3943 	struct wiphy *wiphy = netdev_get_wiphy(netdev);
   3944 	uint64_t wdev_id = netdev_get_wdev_id(netdev);
   3945 	int err;
   3946 	bool cck_rates = true;
   3947 	const uint8_t *rates;
   3948 	unsigned int num_rates;
   3949 	unsigned int i;
   3950 
   3951 	if (L_WARN_ON(!config)) {
   3952 		if (err_out)
   3953 			*err_out = -EINVAL;
   3954 
   3955 		return NULL;
   3956 	}
   3957 
   3958 	ap = l_new(struct ap_state, 1);
   3959 	ap->nl80211 = l_genl_family_new(iwd_get_genl(), NL80211_GENL_NAME);
   3960 	ap->netdev = netdev;
   3961 	ap->ops = ops;
   3962 	ap->user_data = user_data;
   3963 
   3964 	err = ap_load_config(ap, config, &cck_rates);
   3965 	if (err)
   3966 		goto error;
   3967 
   3968 	err = -EINVAL;
   3969 
   3970 	ap->beacon_interval = 100;
   3971 	ap->networks = l_queue_new();
   3972 
   3973 	wsc_uuid_from_addr(netdev_get_address(netdev), ap->wsc_uuid_r);
   3974 
   3975 	rates = wiphy_get_supported_rates(wiphy, ap->band, &num_rates);
   3976 	if (!rates)
   3977 		goto error;
   3978 
   3979 	ap->rates = l_uintset_new(200);
   3980 
   3981 	for (i = 0; i < num_rates; i++) {
   3982 		if (cck_rates && !L_IN_SET(rates[i], 2, 4, 11, 22))
   3983 			continue;
   3984 
   3985 		l_uintset_put(ap->rates, rates[i]);
   3986 	}
   3987 
   3988 	if (!frame_watch_add(wdev_id, 0, 0x0000 |
   3989 			(MPDU_MANAGEMENT_SUBTYPE_ASSOCIATION_REQUEST << 4),
   3990 			NULL, 0, false, ap_assoc_req_cb, ap, NULL))
   3991 		goto error;
   3992 
   3993 	if (!frame_watch_add(wdev_id, 0, 0x0000 |
   3994 			(MPDU_MANAGEMENT_SUBTYPE_REASSOCIATION_REQUEST << 4),
   3995 			NULL, 0, false, ap_reassoc_req_cb, ap, NULL))
   3996 		goto error;
   3997 
   3998 	if (!wiphy_supports_probe_resp_offload(wiphy)) {
   3999 		if (!frame_watch_add(wdev_id, 0, 0x0000 |
   4000 				(MPDU_MANAGEMENT_SUBTYPE_PROBE_REQUEST << 4),
   4001 				NULL, 0, false, ap_probe_req_cb, ap, NULL))
   4002 			goto error;
   4003 	}
   4004 
   4005 	if (!frame_watch_add(wdev_id, 0, 0x0000 |
   4006 				(MPDU_MANAGEMENT_SUBTYPE_DISASSOCIATION << 4),
   4007 				NULL, 0, false, ap_disassoc_cb, ap, NULL))
   4008 		goto error;
   4009 
   4010 	if (!frame_watch_add(wdev_id, 0, 0x0000 |
   4011 				(MPDU_MANAGEMENT_SUBTYPE_AUTHENTICATION << 4),
   4012 				NULL, 0, false, ap_auth_cb, ap, NULL))
   4013 		goto error;
   4014 
   4015 	if (!frame_watch_add(wdev_id, 0, 0x0000 |
   4016 				(MPDU_MANAGEMENT_SUBTYPE_DEAUTHENTICATION << 4),
   4017 				NULL, 0, false, ap_deauth_cb, ap, NULL))
   4018 		goto error;
   4019 
   4020 	ap->mlme_watch = l_genl_family_register(ap->nl80211, "mlme",
   4021 						ap_mlme_notify, ap, NULL);
   4022 	if (!ap->mlme_watch)
   4023 		l_error("Registering for MLME notification failed");
   4024 
   4025 	if (ap->netconfig_set_addr4) {
   4026 		ap->rtnl_add_cmd = l_rtnl_ifaddr_add(rtnl,
   4027 						netdev_get_ifindex(netdev),
   4028 						ap->netconfig_addr4,
   4029 						ap_ifaddr4_added_cb, ap, NULL);
   4030 		if (!ap->rtnl_add_cmd) {
   4031 			l_error("Failed to add the IPv4 address");
   4032 			goto error;
   4033 		}
   4034 
   4035 		return ap;
   4036 	}
   4037 
   4038 	if (!ap_check_channel(ap)) {
   4039 		l_debug("Channel %u is disabled/no-IR, pre-scanning",
   4040 			ap->channel);
   4041 
   4042 		if (ap_pre_scan(ap)) {
   4043 			if (err_out)
   4044 				*err_out = 0;
   4045 
   4046 			return ap;
   4047 		}
   4048 
   4049 		goto error;
   4050 	}
   4051 
   4052 	if (ap_start_send(ap)) {
   4053 		if (err_out)
   4054 			*err_out = 0;
   4055 
   4056 		return ap;
   4057 	}
   4058 
   4059 error:
   4060 	if (err_out)
   4061 		*err_out = err;
   4062 
   4063 	ap_reset(ap);
   4064 	l_genl_family_free(ap->nl80211);
   4065 	l_free(ap);
   4066 	return NULL;
   4067 }
   4068 
   4069 static void ap_stop_cb(struct l_genl_msg *msg, void *user_data)
   4070 {
   4071 	struct ap_state *ap = user_data;
   4072 	int error = l_genl_msg_get_error(msg);
   4073 
   4074 	ap->start_stop_cmd_id = 0;
   4075 
   4076 	if (error < 0)
   4077 		l_error("STOP_AP failed: %s (%i)", strerror(-error), -error);
   4078 
   4079 	if (ap->stopped_func)
   4080 		ap->stopped_func(ap->user_data);
   4081 
   4082 	l_genl_family_free(ap->nl80211);
   4083 	l_free(ap);
   4084 }
   4085 
   4086 static struct l_genl_msg *ap_build_cmd_stop_ap(struct ap_state *ap)
   4087 {
   4088 	struct l_genl_msg *cmd;
   4089 	uint32_t ifindex = netdev_get_ifindex(ap->netdev);
   4090 
   4091 	cmd = l_genl_msg_new_sized(NL80211_CMD_STOP_AP, 16);
   4092 	l_genl_msg_append_attr(cmd, NL80211_ATTR_IFINDEX, 4, &ifindex);
   4093 
   4094 	return cmd;
   4095 }
   4096 
   4097 /*
   4098  * Schedule the running @ap to be stopped and freed.  The original
   4099  * ops and user_data are forgotten and a new callback can be
   4100  * provided if the caller needs to know when the interface becomes
   4101  * free, for example for a new ap_start call.
   4102  *
   4103  * The user must forget @ap when @stopped_func is called.  If the
   4104  * @user_data ends up being destroyed before that, ap_free(ap) should
   4105  * be used to prevent @stopped_func from being called.
   4106  * If @stopped_func is not provided, the caller must forget @ap
   4107  * immediately.
   4108  */
   4109 void ap_shutdown(struct ap_state *ap, ap_stopped_func_t stopped_func,
   4110 			void *user_data)
   4111 {
   4112 	struct l_genl_msg *cmd;
   4113 
   4114 	if (ap->started) {
   4115 		ap->started = false;
   4116 
   4117 		if (ap_event(ap, AP_EVENT_STOPPING, NULL))
   4118 			return;
   4119 	}
   4120 
   4121 	ap_reset(ap);
   4122 
   4123 	if (ap->gtk_set) {
   4124 		ap->gtk_set = false;
   4125 
   4126 		cmd = ap_build_cmd_del_key(ap);
   4127 		if (!cmd) {
   4128 			l_error("ap_build_cmd_del_key failed");
   4129 			goto free_ap;
   4130 		}
   4131 
   4132 		if (!l_genl_family_send(ap->nl80211, cmd, ap_gtk_op_cb, NULL,
   4133 					NULL)) {
   4134 			l_genl_msg_unref(cmd);
   4135 			l_error("Issuing DEL_KEY failed");
   4136 			goto free_ap;
   4137 		}
   4138 	}
   4139 
   4140 	cmd = ap_build_cmd_stop_ap(ap);
   4141 	if (!cmd) {
   4142 		l_error("ap_build_cmd_stop_ap failed");
   4143 		goto free_ap;
   4144 	}
   4145 
   4146 	ap->start_stop_cmd_id = l_genl_family_send(ap->nl80211, cmd, ap_stop_cb,
   4147 							ap, NULL);
   4148 	if (!ap->start_stop_cmd_id) {
   4149 		l_genl_msg_unref(cmd);
   4150 		l_error("Sending STOP_AP failed");
   4151 		goto free_ap;
   4152 	}
   4153 
   4154 	ap->stopped_func = stopped_func;
   4155 	ap->user_data = user_data;
   4156 	return;
   4157 
   4158 free_ap:
   4159 	if (stopped_func)
   4160 		stopped_func(user_data);
   4161 
   4162 	l_genl_family_free(ap->nl80211);
   4163 	l_free(ap);
   4164 }
   4165 
   4166 /* Free @ap without a graceful shutdown */
   4167 void ap_free(struct ap_state *ap)
   4168 {
   4169 	ap_reset(ap);
   4170 
   4171 	if (ap->in_event) {
   4172 		ap->free_pending = true;
   4173 		return;
   4174 	}
   4175 
   4176 	l_genl_family_free(ap->nl80211);
   4177 	l_free(ap);
   4178 }
   4179 
   4180 bool ap_station_disconnect(struct ap_state *ap, const uint8_t *mac,
   4181 				enum mmpdu_reason_code reason)
   4182 {
   4183 	struct sta_state *sta;
   4184 
   4185 	if (!ap->started)
   4186 		return false;
   4187 
   4188 	sta = l_queue_remove_if(ap->sta_states, ap_sta_match_addr, mac);
   4189 	if (!sta)
   4190 		return false;
   4191 
   4192 	if (ap->supports_ht)
   4193 		ap_update_beacon(ap);
   4194 
   4195 	ap_del_station(sta, reason, false);
   4196 	ap_sta_free(sta);
   4197 	return true;
   4198 }
   4199 
   4200 static void ap_wsc_pbc_timeout_cb(struct l_timeout *timeout, void *user_data)
   4201 {
   4202 	struct ap_state *ap = user_data;
   4203 
   4204 	l_debug("PBC mode timeout");
   4205 	ap_wsc_exit_pbc(ap);
   4206 }
   4207 
   4208 static void ap_wsc_pbc_timeout_destroy(void *user_data)
   4209 {
   4210 	struct ap_state *ap = user_data;
   4211 
   4212 	ap->wsc_pbc_timeout = NULL;
   4213 }
   4214 
   4215 bool ap_push_button(struct ap_state *ap)
   4216 {
   4217 	if (!ap->started)
   4218 		return false;
   4219 
   4220 	if (l_queue_length(ap->wsc_pbc_probes) > 1) {
   4221 		l_debug("Can't start PBC mode due to Session Overlap");
   4222 		return false;
   4223 	}
   4224 
   4225 	/*
   4226 	 * WSC v2.0.5 Section 11.3: "Multiple presses of the button are
   4227 	 * permitted.  If a PBC button on an Enrollee or Registrar is
   4228 	 * pressed again during Walk Time, the timers for that device are
   4229 	 * restarted at that time [...]"
   4230 	 */
   4231 	if (ap->wsc_pbc_timeout) {
   4232 		l_timeout_modify(ap->wsc_pbc_timeout, AP_WSC_PBC_WALK_TIME);
   4233 		return true;
   4234 	}
   4235 
   4236 	ap->wsc_pbc_timeout = l_timeout_create(AP_WSC_PBC_WALK_TIME,
   4237 						ap_wsc_pbc_timeout_cb, ap,
   4238 						ap_wsc_pbc_timeout_destroy);
   4239 	ap->wsc_dpid = WSC_DEVICE_PASSWORD_ID_PUSH_BUTTON;
   4240 	ap_update_beacon(ap);
   4241 	return true;
   4242 }
   4243 
   4244 struct ap_if_data {
   4245 	struct netdev *netdev;
   4246 	struct ap_state *ap;
   4247 	struct l_dbus_message *pending;
   4248 };
   4249 
   4250 static void ap_properties_changed(struct ap_if_data *ap_if)
   4251 {
   4252 	l_dbus_property_changed(dbus_get_bus(),
   4253 				netdev_get_path(ap_if->netdev),
   4254 				IWD_AP_INTERFACE, "Started");
   4255 	l_dbus_property_changed(dbus_get_bus(),
   4256 				netdev_get_path(ap_if->netdev),
   4257 				IWD_AP_INTERFACE, "Name");
   4258 	l_dbus_property_changed(dbus_get_bus(),
   4259 				netdev_get_path(ap_if->netdev),
   4260 				IWD_AP_INTERFACE, "Frequency");
   4261 	l_dbus_property_changed(dbus_get_bus(),
   4262 				netdev_get_path(ap_if->netdev),
   4263 				IWD_AP_INTERFACE, "PairwiseCiphers");
   4264 	l_dbus_property_changed(dbus_get_bus(),
   4265 				netdev_get_path(ap_if->netdev),
   4266 				IWD_AP_INTERFACE, "GroupCipher");
   4267 	l_dbus_property_changed(dbus_get_bus(),
   4268 				netdev_get_path(ap_if->netdev),
   4269 				IWD_AP_INTERFACE, "Scanning");
   4270 }
   4271 
   4272 static void ap_if_event_func(enum ap_event_type type, const void *event_data,
   4273 				void *user_data)
   4274 {
   4275 	struct ap_if_data *ap_if = user_data;
   4276 	struct l_dbus_message *reply;
   4277 
   4278 	switch (type) {
   4279 	case AP_EVENT_START_FAILED:
   4280 	{
   4281 		const struct ap_event_start_failed_data *data = event_data;
   4282 
   4283 		if (L_WARN_ON(!ap_if->pending))
   4284 			break;
   4285 
   4286 		reply = dbus_error_from_errno(data->error, ap_if->pending);
   4287 		dbus_pending_reply(&ap_if->pending, reply);
   4288 		ap_if->ap = NULL;
   4289 		break;
   4290 	}
   4291 
   4292 	case AP_EVENT_STARTED:
   4293 		if (L_WARN_ON(!ap_if->pending))
   4294 			break;
   4295 
   4296 		l_dbus_object_add_interface(dbus_get_bus(),
   4297 						netdev_get_path(ap_if->netdev),
   4298 						IWD_AP_DIAGNOSTIC_INTERFACE,
   4299 						ap_if);
   4300 
   4301 		reply = l_dbus_message_new_method_return(ap_if->pending);
   4302 		dbus_pending_reply(&ap_if->pending, reply);
   4303 
   4304 		ap_properties_changed(ap_if);
   4305 
   4306 		l_rtnl_set_linkmode_and_operstate(rtnl,
   4307 					netdev_get_ifindex(ap_if->netdev),
   4308 					IF_LINK_MODE_DEFAULT, IF_OPER_UP,
   4309 					NULL, NULL, NULL);
   4310 		break;
   4311 
   4312 	case AP_EVENT_STOPPING:
   4313 		l_dbus_object_remove_interface(dbus_get_bus(),
   4314 						netdev_get_path(ap_if->netdev),
   4315 						IWD_AP_DIAGNOSTIC_INTERFACE);
   4316 
   4317 		ap_properties_changed(ap_if);
   4318 
   4319 		l_rtnl_set_linkmode_and_operstate(rtnl,
   4320 					netdev_get_ifindex(ap_if->netdev),
   4321 					IF_LINK_MODE_DORMANT, IF_OPER_DOWN,
   4322 					NULL, NULL, NULL);
   4323 
   4324 		if (!ap_if->pending)
   4325 			ap_if->ap = NULL;
   4326 
   4327 		break;
   4328 
   4329 	case AP_EVENT_STATION_ADDED:
   4330 	case AP_EVENT_STATION_REMOVED:
   4331 	case AP_EVENT_REGISTRATION_START:
   4332 	case AP_EVENT_REGISTRATION_SUCCESS:
   4333 	case AP_EVENT_PBC_MODE_EXIT:
   4334 	case AP_EVENT_DHCP_NEW_LEASE:
   4335 	case AP_EVENT_DHCP_LEASE_EXPIRED:
   4336 		/* Ignored */
   4337 		break;
   4338 	}
   4339 }
   4340 
   4341 static const struct ap_ops ap_dbus_ops = {
   4342 	.handle_event = ap_if_event_func,
   4343 };
   4344 
   4345 static struct l_dbus_message *ap_dbus_start(struct l_dbus *dbus,
   4346 		struct l_dbus_message *message, void *user_data)
   4347 {
   4348 	struct ap_if_data *ap_if = user_data;
   4349 	const char *ssid, *wpa2_passphrase;
   4350 	struct l_settings *config;
   4351 	int err;
   4352 
   4353 	if (ap_if->ap && ap_if->ap->started)
   4354 		return dbus_error_already_exists(message);
   4355 
   4356 	if (ap_if->ap || ap_if->pending)
   4357 		return dbus_error_busy(message);
   4358 
   4359 	if (!l_dbus_message_get_arguments(message, "ss",
   4360 						&ssid, &wpa2_passphrase))
   4361 		return dbus_error_invalid_args(message);
   4362 
   4363 	config = l_settings_new();
   4364 	l_settings_set_string(config, "General", "SSID", ssid);
   4365 	l_settings_set_string(config, "Security", "Passphrase",
   4366 				wpa2_passphrase);
   4367 	l_settings_add_group(config, "IPv4");
   4368 
   4369 	ap_if->ap = ap_start(ap_if->netdev, config, &ap_dbus_ops, &err, ap_if);
   4370 	l_settings_free(config);
   4371 
   4372 	if (!ap_if->ap)
   4373 		return dbus_error_from_errno(err, message);
   4374 
   4375 	ap_if->pending = l_dbus_message_ref(message);
   4376 	return NULL;
   4377 }
   4378 
   4379 static void ap_dbus_stop_cb(void *user_data)
   4380 {
   4381 	struct ap_if_data *ap_if = user_data;
   4382 	struct l_dbus_message *reply;
   4383 
   4384 	if (L_WARN_ON(!ap_if->pending))
   4385 		return;
   4386 
   4387 	reply = l_dbus_message_new_method_return(ap_if->pending);
   4388 	dbus_pending_reply(&ap_if->pending, reply);
   4389 	ap_if->ap = NULL;
   4390 }
   4391 
   4392 static struct l_dbus_message *ap_dbus_stop(struct l_dbus *dbus,
   4393 		struct l_dbus_message *message, void *user_data)
   4394 {
   4395 	struct ap_if_data *ap_if = user_data;
   4396 
   4397 	if (!ap_if->ap) {
   4398 		if (ap_if->pending)
   4399 			return dbus_error_busy(message);
   4400 
   4401 		/* already stopped, no-op */
   4402 		return l_dbus_message_new_method_return(message);
   4403 	}
   4404 
   4405 	if (ap_if->pending) {
   4406 		struct l_dbus_message *reply;
   4407 
   4408 		reply = dbus_error_aborted(ap_if->pending);
   4409 		dbus_pending_reply(&ap_if->pending, reply);
   4410 	}
   4411 
   4412 	ap_if->pending = l_dbus_message_ref(message);
   4413 	ap_shutdown(ap_if->ap, ap_dbus_stop_cb, ap_if);
   4414 	return NULL;
   4415 }
   4416 
   4417 static struct l_dbus_message *ap_dbus_start_profile(struct l_dbus *dbus,
   4418 						struct l_dbus_message *message,
   4419 						void *user_data)
   4420 {
   4421 	struct ap_if_data *ap_if = user_data;
   4422 	const char *ssid;
   4423 	_auto_(l_settings_free) struct l_settings *config = NULL;
   4424 	char *config_path;
   4425 	int err;
   4426 
   4427 	if (ap_if->ap && ap_if->ap->started)
   4428 		return dbus_error_already_exists(message);
   4429 
   4430 	if (ap_if->ap || ap_if->pending)
   4431 		return dbus_error_busy(message);
   4432 
   4433 	if (!l_dbus_message_get_arguments(message, "s", &ssid))
   4434 		return dbus_error_invalid_args(message);
   4435 
   4436 	config = l_settings_new();
   4437 	config_path = storage_get_path("ap/%s.ap", ssid);
   4438 	err = l_settings_load_from_file(config, config_path) ? 0 : -EIO;
   4439 	l_free(config_path);
   4440 
   4441 	if (err)
   4442 		goto error;
   4443 
   4444 	/*
   4445 	 * Since [General].SSID is not an allowed setting for a profile on
   4446 	 * disk, we're free to potentially overwrite it with the SSID that
   4447 	 * the DBus user asked for.
   4448 	 */
   4449 	l_settings_set_string(config, "General", "SSID", ssid);
   4450 
   4451 	ap_if->ap = ap_start(ap_if->netdev, config, &ap_dbus_ops, &err, ap_if);
   4452 	if (!ap_if->ap)
   4453 		goto error;
   4454 
   4455 	ap_if->pending = l_dbus_message_ref(message);
   4456 	return NULL;
   4457 
   4458 error:
   4459 	return dbus_error_from_errno(err, message);
   4460 }
   4461 
   4462 static void ap_set_scanning(struct ap_state *ap, bool scanning)
   4463 {
   4464 	if (ap->scanning == scanning)
   4465 		return;
   4466 
   4467 	ap->scanning = scanning;
   4468 
   4469 	l_dbus_property_changed(dbus_get_bus(), netdev_get_path(ap->netdev),
   4470 					IWD_AP_INTERFACE, "Scanning");
   4471 }
   4472 
   4473 static void ap_scan_triggered(int err, void *user_data)
   4474 {
   4475 	struct ap_state *ap = user_data;
   4476 	struct l_dbus_message *reply;
   4477 
   4478 	if (err < 0) {
   4479 		reply = dbus_error_from_errno(err, ap->scan_pending);
   4480 		dbus_pending_reply(&ap->scan_pending, reply);
   4481 		return;
   4482 	}
   4483 
   4484 	l_debug("AP scan triggered for %s", netdev_get_name(ap->netdev));
   4485 
   4486 	reply = l_dbus_message_new_method_return(ap->scan_pending);
   4487 	l_dbus_message_set_arguments(reply, "");
   4488 	dbus_pending_reply(&ap->scan_pending, reply);
   4489 
   4490 	ap_set_scanning(ap, true);
   4491 }
   4492 
   4493 static bool ap_scan_notify(int err, struct l_queue *bss_list,
   4494 				const struct scan_freq_set *freqs,
   4495 				void *user_data)
   4496 {
   4497 	struct ap_state *ap = user_data;
   4498 	const struct l_queue_entry *bss_entry;
   4499 
   4500 	ap_set_scanning(ap, false);
   4501 
   4502 	/* Remove all networks, then re-populate with fresh BSS list */
   4503 	l_queue_clear(ap->networks, l_free);
   4504 
   4505 	for (bss_entry = l_queue_get_entries(bss_list); bss_entry;
   4506 						bss_entry = bss_entry->next) {
   4507 		struct scan_bss *bss = bss_entry->data;
   4508 
   4509 		ap_network_append(ap, bss);
   4510 	}
   4511 
   4512 	l_debug("");
   4513 
   4514 	return false;
   4515 }
   4516 
   4517 static void ap_scan_destroy(void *user_data)
   4518 {
   4519 	struct ap_state *ap = user_data;
   4520 
   4521 	ap->scan_id = 0;
   4522 }
   4523 
   4524 static struct l_dbus_message *ap_dbus_scan(struct l_dbus *dbus,
   4525 						struct l_dbus_message *message,
   4526 						void *user_data)
   4527 {
   4528 	struct ap_if_data *ap_if = user_data;
   4529 	uint64_t wdev_id = netdev_get_wdev_id(ap_if->netdev);
   4530 	struct scan_parameters params = { 0};
   4531 
   4532 	if (wiphy_has_feature(wiphy_find_by_wdev(wdev_id),
   4533 				NL80211_FEATURE_AP_SCAN))
   4534 		params.ap_scan = true;
   4535 
   4536 	/*
   4537 	 * TODO: There is really nothing preventing scanning while stopped.
   4538 	 *       The only consideration would be if a scan is ongoing and the
   4539 	 *       AP is started. Queuing Start() as wiphy work may be required to
   4540 	 *       handle this case if needed. For now just limit to started APs.
   4541 	 */
   4542 	if (!ap_if->ap || !ap_if->ap->started)
   4543 		return dbus_error_not_available(message);
   4544 
   4545 	if (ap_if->ap->scan_id)
   4546 		return dbus_error_busy(message);
   4547 
   4548 	ap_if->ap->scan_id = scan_active_full(wdev_id, &params,
   4549 						ap_scan_triggered,
   4550 						ap_scan_notify,
   4551 						ap_if->ap, ap_scan_destroy);
   4552 	if (!ap_if->ap->scan_id)
   4553 		return dbus_error_failed(message);
   4554 
   4555 	ap_if->ap->scan_pending = l_dbus_message_ref(message);
   4556 
   4557 	return NULL;
   4558 }
   4559 
   4560 static void dbus_append_network(struct l_dbus_message_builder *builder,
   4561 					struct ap_network *network)
   4562 {
   4563 	l_dbus_message_builder_enter_array(builder, "{sv}");
   4564 	dbus_append_dict_basic(builder, "Name", 's', network->ssid);
   4565 	dbus_append_dict_basic(builder, "SignalStrength", 'n',
   4566 					&network->signal);
   4567 	dbus_append_dict_basic(builder, "Type", 's',
   4568 					security_to_str(network->security));
   4569 	l_dbus_message_builder_leave_array(builder);
   4570 }
   4571 
   4572 static struct l_dbus_message *ap_dbus_get_networks(struct l_dbus *dbus,
   4573 						struct l_dbus_message *message,
   4574 						void *user_data)
   4575 {
   4576 	struct ap_if_data *ap_if = user_data;
   4577 	struct l_dbus_message *reply;
   4578 	struct l_dbus_message_builder *builder;
   4579 	const struct l_queue_entry *entry;
   4580 
   4581 	if (!ap_if->ap || !ap_if->ap->started)
   4582 		return dbus_error_not_available(message);
   4583 
   4584 	reply = l_dbus_message_new_method_return(message);
   4585 	builder = l_dbus_message_builder_new(reply);
   4586 
   4587 	l_dbus_message_builder_enter_array(builder, "a{sv}");
   4588 
   4589 	for (entry = l_queue_get_entries(ap_if->ap->networks); entry;
   4590 							entry = entry->next) {
   4591 		struct ap_network *network = entry->data;
   4592 
   4593 		dbus_append_network(builder, network);
   4594 	}
   4595 
   4596 	l_dbus_message_builder_leave_array(builder);
   4597 	l_dbus_message_builder_finalize(builder);
   4598 	l_dbus_message_builder_destroy(builder);
   4599 
   4600 	return reply;
   4601 }
   4602 
   4603 static bool ap_dbus_property_get_started(struct l_dbus *dbus,
   4604 					struct l_dbus_message *message,
   4605 					struct l_dbus_message_builder *builder,
   4606 					void *user_data)
   4607 {
   4608 	struct ap_if_data *ap_if = user_data;
   4609 	bool started = ap_if->ap && ap_if->ap->started;
   4610 
   4611 	l_dbus_message_builder_append_basic(builder, 'b', &started);
   4612 
   4613 	return true;
   4614 }
   4615 
   4616 static bool ap_dbus_property_get_name(struct l_dbus *dbus,
   4617 					struct l_dbus_message *message,
   4618 					struct l_dbus_message_builder *builder,
   4619 					void *user_data)
   4620 {
   4621 	struct ap_if_data *ap_if = user_data;
   4622 
   4623 	if (!ap_if->ap || !ap_if->ap->started)
   4624 		return false;
   4625 
   4626 	l_dbus_message_builder_append_basic(builder, 's',
   4627 						ap_if->ap->ssid);
   4628 
   4629 	return true;
   4630 }
   4631 
   4632 static bool ap_dbus_property_get_scanning(struct l_dbus *dbus,
   4633 					struct l_dbus_message *message,
   4634 					struct l_dbus_message_builder *builder,
   4635 					void *user_data)
   4636 {
   4637 	struct ap_if_data *ap_if = user_data;
   4638 	bool bval;
   4639 
   4640 	if (!ap_if->ap || !ap_if->ap->started)
   4641 		return false;
   4642 
   4643 	bval = ap_if->ap->scanning;
   4644 
   4645 	l_dbus_message_builder_append_basic(builder, 'b', &bval);
   4646 
   4647 	return true;
   4648 }
   4649 
   4650 static bool ap_dbus_property_get_freq(struct l_dbus *dbus,
   4651 					struct l_dbus_message *message,
   4652 					struct l_dbus_message_builder *builder,
   4653 					void *user_data)
   4654 {
   4655 	struct ap_if_data *ap_if = user_data;
   4656 	uint32_t freq;
   4657 
   4658 	if (!ap_if->ap || !ap_if->ap->started)
   4659 		return false;
   4660 
   4661 	freq = band_channel_to_freq(ap_if->ap->channel, ap_if->ap->band);
   4662 
   4663 	l_dbus_message_builder_append_basic(builder, 'u', &freq);
   4664 
   4665 	return true;
   4666 }
   4667 
   4668 static bool ap_dbus_property_get_pairwise(struct l_dbus *dbus,
   4669 					struct l_dbus_message *message,
   4670 					struct l_dbus_message_builder *builder,
   4671 					void *user_data)
   4672 {
   4673 	struct ap_if_data *ap_if = user_data;
   4674 	char **ciphers;
   4675 	size_t i;
   4676 
   4677 	if (!ap_if->ap || !ap_if->ap->started)
   4678 		return false;
   4679 
   4680 	ciphers = ap_ciphers_to_strv(ap_if->ap->ciphers);
   4681 
   4682 	l_dbus_message_builder_enter_array(builder, "s");
   4683 
   4684 	for (i = 0; ciphers[i]; i++)
   4685 		l_dbus_message_builder_append_basic(builder, 's', ciphers[i]);
   4686 
   4687 	l_dbus_message_builder_leave_array(builder);
   4688 
   4689 	l_strv_free(ciphers);
   4690 
   4691 	return true;
   4692 }
   4693 
   4694 static bool ap_dbus_property_get_group(struct l_dbus *dbus,
   4695 					struct l_dbus_message *message,
   4696 					struct l_dbus_message_builder *builder,
   4697 					void *user_data)
   4698 {
   4699 	struct ap_if_data *ap_if = user_data;
   4700 	char **cipher;
   4701 
   4702 	if (!ap_if->ap || !ap_if->ap->started)
   4703 		return false;
   4704 
   4705 	cipher = ap_ciphers_to_strv(ap_if->ap->group_cipher);
   4706 
   4707 	/* Group cipher will only ever be a single value */
   4708 	l_dbus_message_builder_append_basic(builder, 's', cipher[0]);
   4709 	l_strv_free(cipher);
   4710 
   4711 	return true;
   4712 }
   4713 
   4714 static void ap_setup_interface(struct l_dbus_interface *interface)
   4715 {
   4716 	l_dbus_interface_method(interface, "Start", 0, ap_dbus_start, "",
   4717 			"ss", "ssid", "wpa2_passphrase");
   4718 	l_dbus_interface_method(interface, "Stop", 0, ap_dbus_stop, "", "");
   4719 	l_dbus_interface_method(interface, "StartProfile", 0,
   4720 					ap_dbus_start_profile, "", "s",
   4721 					"ssid");
   4722 	l_dbus_interface_method(interface, "Scan", 0, ap_dbus_scan, "", "");
   4723 	l_dbus_interface_method(interface, "GetOrderedNetworks", 0,
   4724 					ap_dbus_get_networks, "aa{sv}",
   4725 					"", "networks");
   4726 
   4727 	l_dbus_interface_property(interface, "Started", 0, "b",
   4728 					ap_dbus_property_get_started, NULL);
   4729 	l_dbus_interface_property(interface, "Name", 0, "s",
   4730 					ap_dbus_property_get_name, NULL);
   4731 	l_dbus_interface_property(interface, "Scanning", 0, "b",
   4732 					ap_dbus_property_get_scanning, NULL);
   4733 	l_dbus_interface_property(interface, "Frequency", 0, "u",
   4734 					ap_dbus_property_get_freq, NULL);
   4735 	l_dbus_interface_property(interface, "PairwiseCiphers", 0, "as",
   4736 					ap_dbus_property_get_pairwise, NULL);
   4737 	l_dbus_interface_property(interface, "GroupCipher", 0, "s",
   4738 					ap_dbus_property_get_group, NULL);
   4739 }
   4740 
   4741 static void ap_destroy_interface(void *user_data)
   4742 {
   4743 	struct ap_if_data *ap_if = user_data;
   4744 
   4745 	if (ap_if->pending) {
   4746 		struct l_dbus_message *reply;
   4747 
   4748 		reply = dbus_error_aborted(ap_if->pending);
   4749 		dbus_pending_reply(&ap_if->pending, reply);
   4750 	}
   4751 
   4752 	if (ap_if->ap)
   4753 		ap_free(ap_if->ap);
   4754 
   4755 	l_free(ap_if);
   4756 }
   4757 
   4758 struct diagnostic_data {
   4759 	struct l_dbus_message *pending;
   4760 	struct l_dbus_message_builder *builder;
   4761 };
   4762 
   4763 static void ap_get_station_cb(const struct diagnostic_station_info *info,
   4764 				void *user_data)
   4765 {
   4766 	struct diagnostic_data *data = user_data;
   4767 
   4768 	/* First station info */
   4769 	if (!data->builder) {
   4770 		struct l_dbus_message *reply =
   4771 				l_dbus_message_new_method_return(data->pending);
   4772 
   4773 		data->builder = l_dbus_message_builder_new(reply);
   4774 
   4775 		l_dbus_message_builder_enter_array(data->builder, "a{sv}");
   4776 	}
   4777 
   4778 	l_dbus_message_builder_enter_array(data->builder, "{sv}");
   4779 	dbus_append_dict_basic(data->builder, "Address", 's',
   4780 					util_address_to_string(info->addr));
   4781 
   4782 	diagnostic_info_to_dict(info, data->builder);
   4783 
   4784 	l_dbus_message_builder_leave_array(data->builder);
   4785 }
   4786 
   4787 static void ap_get_station_destroy(void *user_data)
   4788 {
   4789 	struct diagnostic_data *data = user_data;
   4790 	struct l_dbus_message *reply;
   4791 
   4792 	if (!data->builder) {
   4793 		reply = l_dbus_message_new_method_return(data->pending);
   4794 
   4795 		data->builder = l_dbus_message_builder_new(reply);
   4796 
   4797 		l_dbus_message_builder_enter_array(data->builder, "a{sv}");
   4798 	}
   4799 
   4800 	l_dbus_message_builder_leave_array(data->builder);
   4801 	reply = l_dbus_message_builder_finalize(data->builder);
   4802 	l_dbus_message_builder_destroy(data->builder);
   4803 
   4804 	dbus_pending_reply(&data->pending, reply);
   4805 
   4806 	l_free(data);
   4807 }
   4808 
   4809 static struct l_dbus_message *ap_dbus_get_diagnostics(struct l_dbus *dbus,
   4810 		struct l_dbus_message *message, void *user_data)
   4811 {
   4812 	struct ap_if_data *ap_if = user_data;
   4813 	struct diagnostic_data *data;
   4814 	int ret;
   4815 
   4816 	data = l_new(struct diagnostic_data, 1);
   4817 	data->pending = l_dbus_message_ref(message);
   4818 
   4819 	ret = netdev_get_all_stations(ap_if->ap->netdev, ap_get_station_cb,
   4820 					data, ap_get_station_destroy);
   4821 
   4822 	if (ret < 0) {
   4823 		l_dbus_message_unref(data->pending);
   4824 		l_free(data);
   4825 		return dbus_error_from_errno(ret, message);
   4826 	}
   4827 
   4828 	return NULL;
   4829 }
   4830 
   4831 static void ap_setup_diagnostic_interface(struct l_dbus_interface *interface)
   4832 {
   4833 	l_dbus_interface_method(interface, "GetDiagnostics", 0,
   4834 				ap_dbus_get_diagnostics,
   4835 				"aa{sv}", "", "diagnostic");
   4836 }
   4837 
   4838 static void ap_diagnostic_interface_destroy(void *user_data)
   4839 {
   4840 }
   4841 
   4842 static void ap_add_interface(struct netdev *netdev)
   4843 {
   4844 	struct ap_if_data *ap_if;
   4845 
   4846 	/*
   4847 	 * TODO: Check wiphy supported channels and NL80211_ATTR_TX_FRAME_TYPES
   4848 	 */
   4849 
   4850 	/* just allocate/set device, Start method will complete setup */
   4851 	ap_if = l_new(struct ap_if_data, 1);
   4852 	ap_if->netdev = netdev;
   4853 
   4854 	/* setup ap dbus interface */
   4855 	l_dbus_object_add_interface(dbus_get_bus(),
   4856 			netdev_get_path(netdev), IWD_AP_INTERFACE, ap_if);
   4857 }
   4858 
   4859 static void ap_remove_interface(struct netdev *netdev)
   4860 {
   4861 	l_dbus_object_remove_interface(dbus_get_bus(),
   4862 			netdev_get_path(netdev), IWD_AP_INTERFACE);
   4863 	l_dbus_object_remove_interface(dbus_get_bus(),
   4864 			netdev_get_path(netdev), IWD_AP_DIAGNOSTIC_INTERFACE);
   4865 }
   4866 
   4867 static void ap_netdev_watch(struct netdev *netdev,
   4868 				enum netdev_watch_event event, void *userdata)
   4869 {
   4870 	switch (event) {
   4871 	case NETDEV_WATCH_EVENT_UP:
   4872 #ifdef HAVE_DBUS
   4873 	case NETDEV_WATCH_EVENT_NEW:
   4874 		if (netdev_get_iftype(netdev) == NETDEV_IFTYPE_AP &&
   4875 				netdev_get_is_up(netdev))
   4876 			ap_add_interface(netdev);
   4877 		break;
   4878 	case NETDEV_WATCH_EVENT_DOWN:
   4879 	case NETDEV_WATCH_EVENT_DEL:
   4880 		ap_remove_interface(netdev);
   4881 		break;
   4882 #endif
   4883 	default:
   4884 		break;
   4885 	}
   4886 }
   4887 
   4888 static int ap_init(void)
   4889 {
   4890 	const struct l_settings *settings = iwd_get_config();
   4891 
   4892 	netdev_watch = netdev_watch_add(ap_netdev_watch, NULL, NULL);
   4893 
   4894 #ifdef HAVE_DBUS
   4895 	l_dbus_register_interface(dbus_get_bus(), IWD_AP_INTERFACE,
   4896 			ap_setup_interface, ap_destroy_interface, false);
   4897 	l_dbus_register_interface(dbus_get_bus(), IWD_AP_DIAGNOSTIC_INTERFACE,
   4898 			ap_setup_diagnostic_interface,
   4899 			ap_diagnostic_interface_destroy, false);
   4900 #endif
   4901 
   4902 	/*
   4903 	 * Enable network configuration and DHCP only if
   4904 	 * [General].EnableNetworkConfiguration is true.
   4905 	 */
   4906 	if (netconfig_enabled()) {
   4907 		global_addr4_strs =
   4908 			l_settings_get_string_list(settings, "IPv4",
   4909 							"APAddressPool", ',');
   4910 		if (global_addr4_strs && !global_addr4_strs[0]) {
   4911 			l_error("Can't parse the [IPv4].APAddressPool "
   4912 					"setting as a string list");
   4913 			l_strv_free(global_addr4_strs);
   4914 			global_addr4_strs = NULL;
   4915 		}
   4916 
   4917 		/* Fall back to 192.168.0.0/16 */
   4918 		if (!global_addr4_strs)
   4919 			global_addr4_strs =
   4920 				l_strv_append(NULL, "192.168.0.0/16");
   4921 	}
   4922 
   4923 	rtnl = iwd_get_rtnl();
   4924 
   4925 	return 0;
   4926 }
   4927 
   4928 static void ap_exit(void)
   4929 {
   4930 	netdev_watch_remove(netdev_watch);
   4931 #ifdef HAVE_DBUS
   4932 	l_dbus_unregister_interface(dbus_get_bus(), IWD_AP_INTERFACE);
   4933 #endif
   4934 
   4935 	l_strv_free(global_addr4_strs);
   4936 }
   4937 
   4938 IWD_MODULE(ap, ap_init, ap_exit)
   4939 IWD_MODULE_DEPENDS(ap, netdev);