eiwd

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

p2p.c (149001B)


      1 /*
      2  *
      3  *  Wireless daemon for Linux
      4  *
      5  *  Copyright (C) 2020  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 <stdlib.h>
     29 #include <linux/rtnetlink.h>
     30 #include <linux/if_ether.h>
     31 #include <unistd.h>
     32 #include <limits.h>
     33 #include <stdio.h>
     34 #include <time.h>
     35 #include <errno.h>
     36 #include <netinet/in.h>
     37 #include <arpa/inet.h>
     38 #include <linux/if.h>
     39 #include <sys/param.h>
     40 
     41 #include <ell/ell.h>
     42 
     43 #include "linux/nl80211.h"
     44 
     45 #include "ell/useful.h"
     46 #include "src/missing.h"
     47 #include "src/iwd.h"
     48 #include "src/wiphy.h"
     49 #include "src/scan.h"
     50 #include "src/p2putil.h"
     51 #include "src/ie.h"
     52 #include "src/util.h"
     53 #include "src/dbus.h"
     54 #include "src/netdev.h"
     55 #include "src/mpdu.h"
     56 #include "src/common.h"
     57 #include "src/wsc.h"
     58 #include "src/handshake.h"
     59 #include "src/crypto.h"
     60 #include "src/module.h"
     61 #include "src/frame-xchg.h"
     62 #include "src/nl80211util.h"
     63 #include "src/netconfig.h"
     64 #include "src/ap.h"
     65 #include "src/p2p.h"
     66 #include "src/band.h"
     67 
     68 struct p2p_device {
     69 	uint64_t wdev_id;
     70 	uint8_t addr[6];
     71 	struct l_genl_family *nl80211;
     72 	struct wiphy *wiphy;
     73 	unsigned int connections_left;
     74 	struct p2p_capability_attr capability;
     75 	struct p2p_device_info_attr device_info;
     76 	uint32_t start_stop_cmd_id;
     77 	l_dbus_property_complete_cb_t pending_complete;
     78 	struct l_dbus_message *pending_message;
     79 
     80 	uint8_t listen_country[3];
     81 	uint8_t listen_oper_class;
     82 	uint32_t listen_channel;
     83 	unsigned int scan_interval;
     84 	time_t next_scan_ts;
     85 	struct l_timeout *scan_timeout;
     86 	uint32_t scan_id;
     87 	unsigned int chans_per_scan;
     88 	unsigned int scan_chan_idx;
     89 	uint64_t roc_cookie;
     90 	unsigned int listen_duration;
     91 	struct l_queue *discovery_users;
     92 	struct l_queue *peer_list;
     93 	unsigned int next_tie_breaker;
     94 
     95 	struct p2p_peer *conn_peer;
     96 	uint16_t conn_config_method;
     97 	char *conn_pin;
     98 	uint8_t conn_addr[6];
     99 	uint16_t conn_password_id;
    100 	unsigned int conn_num;
    101 	struct scan_bss *conn_wsc_bss;
    102 	struct netdev *conn_netdev;
    103 	uint32_t conn_netdev_watch_id;
    104 	uint32_t conn_new_intf_cmd_id;
    105 	struct wsc_enrollee *conn_enrollee;
    106 	struct netconfig *conn_netconfig;
    107 	struct l_settings *conn_netconfig_settings;
    108 	struct l_timeout *conn_dhcp_timeout;
    109 	char *conn_peer_ip;
    110 	struct p2p_wfd_properties *conn_own_wfd;
    111 	uint8_t conn_psk[32];
    112 	int conn_retry_count;
    113 
    114 	struct l_timeout *conn_peer_config_timeout;
    115 	unsigned long conn_config_delay;
    116 	struct l_timeout *conn_go_neg_req_timeout;
    117 	uint8_t conn_go_dialog_token;
    118 	unsigned int conn_go_scan_retry;
    119 	uint32_t conn_go_oper_freq;
    120 	uint8_t conn_peer_interface_addr[6];
    121 	struct p2p_capability_attr conn_peer_capability;
    122 	struct p2p_device_info_attr conn_peer_dev_info;
    123 
    124 	struct p2p_group_id_attr go_group_id;
    125 	struct ap_state *group;
    126 
    127 	bool enabled : 1;
    128 	bool have_roc_cookie : 1;
    129 	/*
    130 	 * We need to track @disconnecting because while a connect action is
    131 	 * always triggered by a DBus message, meaning that @pending_message
    132 	 * is going to be non-NULL, a disconnect may also be a result of an
    133 	 * error at a layer higher than netdev and may last until
    134 	 * netdev_disconnect, or similar, finishes.
    135 	 */
    136 	bool disconnecting : 1;
    137 	bool is_go : 1;
    138 	bool conn_go_tie_breaker : 1;
    139 	bool conn_peer_added : 1;
    140 };
    141 
    142 struct p2p_discovery_user {
    143 	char *client;
    144 	struct p2p_device *dev;
    145 	unsigned int disconnect_watch;
    146 };
    147 
    148 struct p2p_peer {
    149 	struct scan_bss *bss;
    150 	struct p2p_device *dev;
    151 	struct wsc_dbus wsc;
    152 	char *name;
    153 	struct wsc_primary_device_type primary_device_type;
    154 	const uint8_t *device_addr;
    155 	struct p2p_wfd_properties *wfd;
    156 	/* Whether peer is currently a GO */
    157 	bool group;
    158 };
    159 
    160 struct p2p_wfd_properties {
    161 	bool available;
    162 	bool source;
    163 	bool sink;
    164 	uint16_t port;
    165 	uint16_t throughput;
    166 	bool audio;
    167 	bool uibc;
    168 	bool cp;
    169 	bool r2;
    170 	uint16_t raw_dev_info;
    171 	uint8_t associated_bssid[6];
    172 	uint8_t raw_coupled_sink_status;
    173 	uint8_t coupled_sink_mac[6];
    174 };
    175 
    176 static struct l_queue *p2p_device_list;
    177 static unsigned int p2p_dhcp_timeout_val;
    178 static struct l_settings *p2p_dhcp_settings;
    179 static struct p2p_wfd_properties *p2p_own_wfd;
    180 static unsigned int p2p_wfd_disconnect_watch;
    181 
    182 /*
    183  * For now we only scan the common 2.4GHz channels, to be replaced with
    184  * a query of actual allowed channels per band and reg-domain.
    185  */
    186 static const int channels_social[] = { 1, 6, 11 };
    187 static const int channels_scan_2_4_other[] = { 2, 3, 4, 5, 7, 8, 9, 10 };
    188 
    189 /*
    190  * The client side generally receives more testing and we know of fewer
    191  * problematic drivers so set a low default Group Owner intent value.
    192  */
    193 #define P2P_GO_INTENT 2
    194 
    195 static bool p2p_device_match(const void *a, const void *b)
    196 {
    197 	const struct p2p_device *dev = a;
    198 	const uint64_t *wdev_id = b;
    199 
    200 	return dev->wdev_id == *wdev_id;
    201 }
    202 
    203 struct p2p_device *p2p_device_find(uint64_t wdev_id)
    204 {
    205 	return l_queue_find(p2p_device_list, p2p_device_match, &wdev_id);
    206 }
    207 
    208 static const char *p2p_device_get_path(const struct p2p_device *dev)
    209 {
    210 	return wiphy_get_path(dev->wiphy);
    211 }
    212 
    213 static bool p2p_discovery_user_match(const void *a, const void *b)
    214 {
    215 	const struct p2p_discovery_user *user = a;
    216 
    217 	return !strcmp(user->client, b);
    218 }
    219 
    220 static void p2p_discovery_user_free(void *data)
    221 {
    222 	struct p2p_discovery_user *user = data;
    223 
    224 #ifdef HAVE_DBUS
    225 	if (user->disconnect_watch)
    226 		l_dbus_remove_watch(dbus_get_bus(), user->disconnect_watch);
    227 #endif
    228 
    229 	l_free(user->client);
    230 	l_free(user);
    231 }
    232 
    233 static inline bool p2p_peer_operational(struct p2p_peer *peer)
    234 {
    235 	return peer && peer->dev->conn_netdev && !peer->dev->disconnecting &&
    236 		((!peer->dev->is_go && !peer->dev->conn_wsc_bss) ||
    237 		 (peer->dev->is_go && peer->dev->conn_peer_added));
    238 }
    239 
    240 static bool p2p_peer_match(const void *a, const void *b)
    241 {
    242 	const struct p2p_peer *peer = a;
    243 	const uint8_t *addr = b;
    244 
    245 	return !memcmp(peer->bss->addr, addr, 6);
    246 }
    247 
    248 static const char *p2p_peer_get_path(const struct p2p_peer *peer)
    249 {
    250 	static char path[256];
    251 
    252 	snprintf(path, sizeof(path),
    253 			"%s/p2p_peers/%02x_%02x_%02x_%02x_%02x_%02x",
    254 			p2p_device_get_path(peer->dev),
    255 			peer->bss->addr[0], peer->bss->addr[1],
    256 			peer->bss->addr[2], peer->bss->addr[3],
    257 			peer->bss->addr[4], peer->bss->addr[5]);
    258 	return path;
    259 }
    260 
    261 static void p2p_peer_free(void *user_data)
    262 {
    263 	struct p2p_peer *peer = user_data;
    264 
    265 	scan_bss_free(peer->bss);
    266 	l_free(peer->wfd);
    267 	l_free(peer->name);
    268 	l_free(peer);
    269 }
    270 
    271 static void p2p_peer_put(void *user_data)
    272 {
    273 	struct p2p_peer *peer = user_data;
    274 
    275 	/*
    276 	 * Removes all interfaces with one call, no need to call
    277 	 * wsc_dbus_remove_interface.
    278 	 */
    279 #ifdef HAVE_DBUS
    280 	l_dbus_unregister_object(dbus_get_bus(), p2p_peer_get_path(peer));
    281 #endif
    282 	p2p_peer_free(peer);
    283 }
    284 
    285 static void p2p_device_discovery_start(struct p2p_device *dev);
    286 static void p2p_device_discovery_stop(struct p2p_device *dev);
    287 
    288 /* Callers should reserve 32 bytes, 64 with non-NULL @wfd_clients */
    289 static size_t p2p_build_wfd_ie(const struct p2p_wfd_properties *wfd,
    290 				const struct p2p_peer *wfd_client, uint8_t *buf)
    291 {
    292 	/*
    293 	 * Wi-Fi Display Technical Specification v2.1.0
    294 	 * Probe req: Section 5.2.2
    295 	 * Negotiation req: Section 5.2.6.1
    296 	 * Negotiation resp: Section 5.2.6.2
    297 	 * Negotiation confirm: Section 5.2.6.3
    298 	 * Provision disc req: Section 5.2.6.6
    299 	 */
    300 	size_t size = 0;
    301 	uint16_t dev_type =
    302 		wfd->source ? (wfd->sink ? WFD_DEV_INFO_TYPE_DUAL_ROLE :
    303 			WFD_DEV_INFO_TYPE_SOURCE) :
    304 		WFD_DEV_INFO_TYPE_PRIMARY_SINK;
    305 
    306 	buf[size++] = IE_TYPE_VENDOR_SPECIFIC;
    307 	size++;			/* IE Data length */
    308 	buf[size++] = wifi_alliance_oui[0];
    309 	buf[size++] = wifi_alliance_oui[1];
    310 	buf[size++] = wifi_alliance_oui[2];
    311 	buf[size++] = 0x0a;	/* OUI Type: WFD */
    312 
    313 	buf[size++] = WFD_SUBELEM_WFD_DEVICE_INFORMATION;
    314 	buf[size++] = 0;	/* WFD Subelement length */
    315 	buf[size++] = 6;
    316 	buf[size++] = 0x00;	/* WFD Device Information bitmap: */
    317 	buf[size++] = dev_type |
    318 		(wfd->available ? WFD_DEV_INFO_SESSION_AVAILABLE :
    319 		 WFD_DEV_INFO_SESSION_NOT_AVAILABLE) |
    320 		(wfd->audio ? 0 : WFD_DEV_INFO_NO_AUDIO_AT_PRIMARY_SINK) |
    321 		(wfd->cp ? WFD_DEV_INFO_CONTENT_PROTECTION_SUPPORT : 0);
    322 	buf[size++] = wfd->port >> 8; /* Session Mgmt Ctrl Port */
    323 	buf[size++] = wfd->port & 255;
    324 	buf[size++] = wfd->throughput >> 8; /* Maximum throughput */
    325 	buf[size++] = wfd->throughput & 255;
    326 
    327 	if (wfd->uibc) {
    328 		buf[size++] = WFD_SUBELEM_EXTENDED_CAPABILITY;
    329 		buf[size++] = 0;	/* WFD Subelement length */
    330 		buf[size++] = 2;
    331 		buf[size++] = 0x00;	/* WFD Extended Capability Bitmap: */
    332 		buf[size++] = 0x01;	/* UIBC Support */
    333 	}
    334 
    335 	/*
    336 	 * Wi-Fi Display Technical Specification v2.1.0 section 5.2.3:
    337 	 * "If a WFD Capable GO has at least one associated client that is
    338 	 * WFD capable, the WFD capable GO shall include the WFD Session
    339 	 * Information subelement in the WFD IE in the Probe Response
    340 	 * frames it transmits."
    341 	 */
    342 	if (wfd_client && !L_WARN_ON(!wfd_client->wfd)) {
    343 		buf[size++] = WFD_SUBELEM_SESION_INFORMATION;
    344 		buf[size++] = 0;		/* WFD Subelement length */
    345 		buf[size++] = 23;
    346 		memcpy(buf + size, wfd_client->device_addr, 6);
    347 		size += 6;
    348 		memcpy(buf + size, wfd_client->wfd->associated_bssid, 6);
    349 		size += 6;
    350 		buf[size++] = wfd_client->wfd->raw_dev_info >> 8;
    351 		buf[size++] = wfd_client->wfd->raw_dev_info & 255;
    352 		buf[size++] = wfd_client->wfd->throughput >> 8;
    353 		buf[size++] = wfd_client->wfd->throughput & 255;
    354 		buf[size++] = wfd_client->wfd->raw_coupled_sink_status;
    355 		memcpy(buf + size, wfd_client->wfd->coupled_sink_mac, 6);
    356 		size += 6;
    357 	}
    358 
    359 	if (wfd->r2) {
    360 		buf[size++] = WFD_SUBELEM_R2_DEVICE_INFORMATION;
    361 		buf[size++] = 0;	/* WFD Subelement length */
    362 		buf[size++] = 2;
    363 		buf[size++] = 0x00;	/* WFD R2 Device Information bitmap: */
    364 		buf[size++] = wfd->source ? wfd->sink ? 3 : 0 : 1;
    365 	}
    366 
    367 	buf[1] = size - 2;
    368 	return size;
    369 }
    370 
    371 static bool p2p_extract_wfd_properties(const uint8_t *ie, size_t ie_size,
    372 					struct p2p_wfd_properties *out)
    373 {
    374 	struct wfd_subelem_iter iter;
    375 	const uint8_t *devinfo = NULL;
    376 	const uint8_t *associated_bssid = NULL;
    377 	const uint8_t *coupled_sink_info = NULL;
    378 	const uint8_t *ext_caps = NULL;
    379 	const uint8_t *r2 = NULL;
    380 
    381 	if (!ie)
    382 		return false;
    383 
    384 	wfd_subelem_iter_init(&iter, ie, ie_size);
    385 
    386 	while (wfd_subelem_iter_next(&iter)) {
    387 		enum wfd_subelem_type type = wfd_subelem_iter_get_type(&iter);
    388 		size_t len = wfd_subelem_iter_get_length(&iter);
    389 		const uint8_t *data = wfd_subelem_iter_get_data(&iter);
    390 
    391 		switch (type) {
    392 #define SUBELEM_CHECK(var, expected_len, name)		\
    393 			if (len != expected_len) {	\
    394 				l_debug(name " length wrong in WFD IE");\
    395 				return false;		\
    396 			}				\
    397 							\
    398 			if (var) {			\
    399 				l_debug("Duplicate" name " in WFD IE");\
    400 				return false;		\
    401 			}				\
    402 							\
    403 			var = data;
    404 		case WFD_SUBELEM_WFD_DEVICE_INFORMATION:
    405 			SUBELEM_CHECK(devinfo, 6, "Device Information");
    406 			break;
    407 		case WFD_SUBELEM_ASSOCIATED_BSSID:
    408 			SUBELEM_CHECK(associated_bssid, 6, "Associated BSSID");
    409 			break;
    410 		case WFD_SUBELEM_COUPLED_SINK_INFORMATION:
    411 			SUBELEM_CHECK(coupled_sink_info, 7,
    412 					"Coupled Sink Information");
    413 			break;
    414 		case WFD_SUBELEM_EXTENDED_CAPABILITY:
    415 			SUBELEM_CHECK(ext_caps, 2, "Extended Capability");
    416 			break;
    417 		case WFD_SUBELEM_R2_DEVICE_INFORMATION:
    418 			SUBELEM_CHECK(r2, 2, "R2 Device Information");
    419 			break;
    420 #undef SUBELEM_CHECK
    421 		default:
    422 			/* Skip unknown IEs */
    423 			break;
    424 		}
    425 	}
    426 
    427 	if (devinfo) {
    428 		uint16_t capability = l_get_be16(devinfo + 0);
    429 		bool source;
    430 		bool sink;
    431 		uint16_t port;
    432 
    433 		source = (capability & WFD_DEV_INFO_DEVICE_TYPE) ==
    434 			WFD_DEV_INFO_TYPE_SOURCE ||
    435 			(capability & WFD_DEV_INFO_DEVICE_TYPE) ==
    436 			WFD_DEV_INFO_TYPE_DUAL_ROLE;
    437 		sink = (capability & WFD_DEV_INFO_DEVICE_TYPE) ==
    438 			WFD_DEV_INFO_TYPE_PRIMARY_SINK ||
    439 			(capability & WFD_DEV_INFO_DEVICE_TYPE) ==
    440 			WFD_DEV_INFO_TYPE_DUAL_ROLE;
    441 
    442 		if (!source && !sink)
    443 			return false;
    444 
    445 		port = l_get_be16(devinfo + 2);
    446 
    447 		if (source && port == 0) {
    448 			l_debug("0 port number in WFD IE Device Information");
    449 			return false;
    450 		}
    451 
    452 		memset(out, 0, sizeof(*out));
    453 		out->available =
    454 			(capability & WFD_DEV_INFO_SESSION_AVAILABILITY) ==
    455 			WFD_DEV_INFO_SESSION_AVAILABLE;
    456 		out->source = source;
    457 		out->sink = sink;
    458 		out->port = port;
    459 		out->cp = capability & WFD_DEV_INFO_CONTENT_PROTECTION_SUPPORT;
    460 		out->audio = !sink ||
    461 			!(capability & WFD_DEV_INFO_NO_AUDIO_AT_PRIMARY_SINK);
    462 		out->raw_dev_info = l_get_be16(devinfo);
    463 	} else {
    464 		l_error("Device Information missing in WFD IE");
    465 		return false;
    466 	}
    467 
    468 	if (associated_bssid)
    469 		memcpy(out->associated_bssid, associated_bssid, 6);
    470 
    471 	if (coupled_sink_info) {
    472 		out->raw_coupled_sink_status = coupled_sink_info[0];
    473 		memcpy(out->coupled_sink_mac, coupled_sink_info + 1, 6);
    474 	}
    475 
    476 	if (ext_caps && (l_get_be16(ext_caps) & 1))
    477 		out->uibc = 1;
    478 
    479 	if (r2) {
    480 		uint8_t role = l_get_be16(r2) & 3;
    481 
    482 		if ((out->source && role != 0 && role != 3) ||
    483 				(out->sink && role != 1 && role != 3))
    484 			l_debug("Invalid role in WFD R2 Device Information");
    485 		else
    486 			out->r2 = true;
    487 	}
    488 
    489 	return true;
    490 }
    491 
    492 static bool p2p_device_validate_conn_wfd(struct p2p_device *dev,
    493 						const uint8_t *ie,
    494 						ssize_t ie_size)
    495 {
    496 	struct p2p_wfd_properties wfd;
    497 
    498 	if (!dev->conn_own_wfd)
    499 		return true;
    500 
    501 	/*
    502 	 * WFD IEs are optional in Association Request/Response and P2P Public
    503 	 * Action frames for R2 devices and required for R1 devices.
    504 	 * Wi-Fi Display Technical Specification v2.1.0 section 5.2:
    505 	 * "A WFD R2 Device shall include the WFD IE in Beacon, Probe
    506 	 * Request/Response, Association Request/Response and P2P Public Action
    507 	 * frames in order to be interoperable with R1 devices. If a WFD R2
    508 	 * Device discovers that the peer device is also a WFD R2 Device, then
    509 	 * it may include the WFD IE in Association Request/Response and P2P
    510 	 * Public Action frames."
    511 	 */
    512 	if (!ie)
    513 		return dev->conn_own_wfd->r2;
    514 
    515 	if (!p2p_extract_wfd_properties(ie, ie_size, &wfd)) {
    516 		l_error("Could not parse the WFD IE contents");
    517 		return false;
    518 	}
    519 
    520 	if ((dev->conn_own_wfd->source && !wfd.sink) ||
    521 			(dev->conn_own_wfd->sink && !wfd.source)) {
    522 		l_error("Wrong role in peer's WFD IE");
    523 		return false;
    524 	}
    525 
    526 	if (wfd.r2 != dev->conn_own_wfd->r2) {
    527 		l_error("Wrong version in peer's WFD IE");
    528 		return false;
    529 	}
    530 
    531 	/*
    532 	 * Ignore the session available state because it's not 100% clear
    533 	 * at what point the peer switches to SESSION_NOT_AVAILABLE in its
    534 	 * Device Information.
    535 	 * But we might want to check that other bits have not changed from
    536 	 * what the peer reported during discovery.
    537 	 * Wi-Fi Display Technical Specification v2.1.0 section 4.5.2.1:
    538 	 * "The content of the WFD Device Information subelement should be
    539 	 * immutable during the period of P2P connection establishment, with
    540 	 * [...] exceptions [...]"
    541 	 */
    542 
    543 	return true;
    544 }
    545 
    546 /* TODO: convert to iovecs */
    547 static uint8_t *p2p_build_scan_ies(struct p2p_device *dev, uint8_t *buf,
    548 					size_t buf_len, size_t *out_len)
    549 {
    550 	struct p2p_probe_req p2p_info = {};
    551 	struct wsc_probe_request wsc_info = {};
    552 	L_AUTO_FREE_VAR(uint8_t *, p2p_ie) = NULL;
    553 	size_t p2p_ie_size;
    554 	uint8_t *wsc_data;
    555 	size_t wsc_data_size;
    556 	L_AUTO_FREE_VAR(uint8_t *, wsc_ie) = NULL;
    557 	size_t wsc_ie_size;
    558 	uint8_t wfd_ie[32];
    559 	size_t wfd_ie_size;
    560 	const uint8_t *addr;
    561 
    562 	p2p_info.capability = dev->capability;
    563 	memcpy(p2p_info.listen_channel.country, dev->listen_country, 3);
    564 	p2p_info.listen_channel.oper_class = dev->listen_oper_class;
    565 	p2p_info.listen_channel.channel_num = dev->listen_channel;
    566 
    567 	/*
    568 	 * Note that through an attribute we can also request Group Owners
    569 	 * to send us info on clients within their groups and could also
    570 	 * show those on D-Bus.  Doesn't seem useful at this time but may
    571 	 * be desired at some point.
    572 	 */
    573 
    574 	p2p_ie = p2p_build_probe_req(&p2p_info, &p2p_ie_size);
    575 	if (!p2p_ie)
    576 		return NULL;
    577 
    578 	wsc_info.version2 = true;
    579 	wsc_info.request_type = WSC_REQUEST_TYPE_ENROLLEE_INFO;
    580 	wsc_info.config_methods = dev->device_info.wsc_config_methods;
    581 
    582 	/*
    583 	 * If we're doing the provisioning scan, we need to use the same UUID-E
    584 	 * that we'll use in the WSC enrollee registration protocol because the
    585 	 * GO might validate it.
    586 	 */
    587 	addr = dev->conn_peer ? dev->conn_addr : dev->addr;
    588 
    589 	if (!wsc_uuid_from_addr(addr, wsc_info.uuid_e))
    590 		return NULL;
    591 
    592 	wsc_info.primary_device_type = dev->device_info.primary_device_type;
    593 	wsc_info.rf_bands = WSC_RF_BAND_2_4_GHZ;
    594 	wsc_info.association_state = WSC_ASSOCIATION_STATE_NOT_ASSOCIATED;
    595 	wsc_info.configuration_error = WSC_CONFIGURATION_ERROR_NO_ERROR;
    596 	wsc_info.device_password_id = WSC_DEVICE_PASSWORD_ID_DEFAULT;
    597 	l_strlcpy(wsc_info.device_name, dev->device_info.device_name,
    598 			sizeof(wsc_info.device_name));
    599 
    600 	wsc_data = wsc_build_probe_request(&wsc_info, &wsc_data_size);
    601 	if (!wsc_data)
    602 		return NULL;
    603 
    604 	wsc_ie = ie_tlv_encapsulate_wsc_payload(wsc_data, wsc_data_size,
    605 						&wsc_ie_size);
    606 	l_free(wsc_data);
    607 
    608 	if (!wsc_ie)
    609 		return NULL;
    610 
    611 	if (p2p_own_wfd)
    612 		wfd_ie_size = p2p_build_wfd_ie(p2p_own_wfd, NULL, wfd_ie);
    613 	else
    614 		wfd_ie_size = 0;
    615 
    616 	if (buf_len < wsc_ie_size + p2p_ie_size + wfd_ie_size)
    617 		return NULL;
    618 
    619 	memcpy(buf + 0, wsc_ie, wsc_ie_size);
    620 	memcpy(buf + wsc_ie_size, p2p_ie, p2p_ie_size);
    621 
    622 	if (wfd_ie_size)
    623 		memcpy(buf + wsc_ie_size + p2p_ie_size, wfd_ie, wfd_ie_size);
    624 
    625 	*out_len = wsc_ie_size + p2p_ie_size + wfd_ie_size;
    626 	return buf;
    627 }
    628 
    629 static void p2p_connection_reset(struct p2p_device *dev)
    630 {
    631 	struct p2p_peer *peer = dev->conn_peer;
    632 
    633 	if (!peer)
    634 		return;
    635 
    636 	/*
    637 	 * conn_peer is currently not refcounted and we make sure it's always
    638 	 * on the dev->peer_list so we can just drop our reference.  Since we
    639 	 * may not have been scanning for a while, don't drop the peer object
    640 	 * now just because it's not been seen in scan results recently, its
    641 	 * age will be checked on the next scan.
    642 	 */
    643 	dev->conn_peer = NULL;
    644 	dev->disconnecting = false;
    645 	dev->connections_left++;
    646 
    647 	if (dev->conn_pin) {
    648 		explicit_bzero(dev->conn_pin, strlen(dev->conn_pin));
    649 		l_free(dev->conn_pin);
    650 		dev->conn_pin = NULL;
    651 	}
    652 
    653 	l_dbus_property_changed(dbus_get_bus(), p2p_device_get_path(dev),
    654 				IWD_P2P_INTERFACE, "AvailableConnections");
    655 
    656 	l_timeout_remove(dev->conn_peer_config_timeout);
    657 	l_timeout_remove(dev->conn_go_neg_req_timeout);
    658 	l_timeout_remove(dev->conn_dhcp_timeout);
    659 
    660 	if (dev->conn_netconfig) {
    661 		netconfig_destroy(dev->conn_netconfig);
    662 		dev->conn_netconfig = NULL;
    663 		l_settings_free(dev->conn_netconfig_settings);
    664 	}
    665 
    666 	l_free(dev->conn_peer_ip);
    667 	dev->conn_peer_ip = NULL;
    668 
    669 	if (dev->conn_new_intf_cmd_id)
    670 		/*
    671 		 * Note this may result in the interface being created
    672 		 * and unused, we don't have its ifindex or wdev_id here
    673 		 * to be able to delete it.  Could use a separate netlink
    674 		 * socket for each connection or disallowing .Disconnect
    675 		 * calls while this command runs.
    676 		 */
    677 		l_genl_family_cancel(dev->nl80211, dev->conn_new_intf_cmd_id);
    678 
    679 	if (dev->conn_enrollee)
    680 		wsc_enrollee_cancel(dev->conn_enrollee, false);
    681 
    682 	if (dev->group) {
    683 		ap_free(dev->group);
    684 		dev->group = NULL;
    685 		dev->conn_peer_added = false;
    686 	}
    687 
    688 	dev->capability.group_caps = 0;
    689 
    690 	if (dev->conn_netdev) {
    691 		struct l_genl_msg *msg;
    692 		uint64_t wdev_id = netdev_get_wdev_id(dev->conn_netdev);
    693 
    694 		msg = l_genl_msg_new(NL80211_CMD_DEL_INTERFACE);
    695 		l_genl_msg_append_attr(msg, NL80211_ATTR_WDEV, 8, &wdev_id);
    696 
    697 		if (!l_genl_family_send(dev->nl80211, msg, NULL, NULL, NULL)) {
    698 			l_genl_msg_unref(msg);
    699 			l_error("Sending DEL_INTERFACE for %s failed",
    700 				netdev_get_name(dev->conn_netdev));
    701 		}
    702 
    703 		netdev_destroy(dev->conn_netdev);
    704 		dev->conn_netdev = NULL;
    705 	}
    706 
    707 	/*
    708 	 * Removing the netdev above makes sure that both the WSC connection
    709 	 * and the final WPA2 connection (wsc.c and netdev.c) no longer need
    710 	 * the bss so we can free it now -- if it wasn't freed as a result
    711 	 * of wsc_enrollee_cancel or netdev_destroy triggering
    712 	 * p2p_peer_provision_done in the first place.
    713 	 */
    714 	if (dev->conn_wsc_bss) {
    715 		scan_bss_free(dev->conn_wsc_bss);
    716 		dev->conn_wsc_bss = NULL;
    717 	}
    718 
    719 	netdev_watch_remove(dev->conn_netdev_watch_id);
    720 
    721 	frame_watch_group_remove(dev->wdev_id, FRAME_GROUP_P2P_CONNECT);
    722 	frame_xchg_stop_wdev(dev->wdev_id);
    723 
    724 	if (!dev->enabled || (dev->enabled && dev->start_stop_cmd_id)) {
    725 		/*
    726 		 * The device has been disabled in the mean time, all peers
    727 		 * have been removed except this one.  Now it's safe to
    728 		 * drop this peer from the scan results too.
    729 		 */
    730 		l_queue_destroy(dev->peer_list, p2p_peer_put);
    731 		dev->peer_list = NULL;
    732 	}
    733 
    734 	if (dev->conn_own_wfd) {
    735 		l_free(dev->conn_own_wfd);
    736 		dev->conn_own_wfd = NULL;
    737 
    738 		if (p2p_own_wfd)
    739 			p2p_own_wfd->available = true;
    740 	}
    741 
    742 	explicit_bzero(dev->conn_psk, 32);
    743 	dev->conn_retry_count = 0;
    744 	dev->is_go = false;
    745 
    746 	if (dev->enabled && !dev->start_stop_cmd_id &&
    747 			!l_queue_isempty(dev->discovery_users))
    748 		p2p_device_discovery_start(dev);
    749 }
    750 
    751 static void p2p_connect_failed(struct p2p_device *dev)
    752 {
    753 	struct p2p_peer *peer = dev->conn_peer;
    754 
    755 	if (!peer)
    756 		return;
    757 
    758 	/* Are we in the scan for the WSC provision bss */
    759 	if (dev->scan_id)
    760 		scan_cancel(dev->wdev_id, dev->scan_id);
    761 
    762 	if (l_queue_isempty(dev->discovery_users))
    763 		p2p_device_discovery_stop(dev);
    764 
    765 	if (peer->wsc.pending_connect)
    766 		dbus_pending_reply(&peer->wsc.pending_connect,
    767 				dbus_error_failed(peer->wsc.pending_connect));
    768 
    769 	p2p_connection_reset(dev);
    770 }
    771 
    772 static void p2p_peer_frame_xchg(struct p2p_peer *peer, struct iovec *tx_body,
    773 				const uint8_t *bssid,
    774 				unsigned int retry_interval,
    775 				unsigned int resp_timeout,
    776 				unsigned int retries_on_ack, bool own_channel,
    777 				uint32_t group_id, frame_xchg_cb_t cb, ...)
    778 {
    779 	struct p2p_device *dev = peer->dev;
    780 	struct iovec *frame;
    781 	const struct iovec *iov;
    782 	struct mmpdu_header *header;
    783 	uint8_t header_buf[32] __attribute__ ((aligned));
    784 	int iov_cnt;
    785 	uint32_t freq;
    786 	va_list args;
    787 
    788 	/* Header */
    789 	memset(header_buf, 0, sizeof(header_buf));
    790 	header = (void *) header_buf;
    791 	header->fc.protocol_version = 0;
    792 	header->fc.type = MPDU_TYPE_MANAGEMENT;
    793 	header->fc.subtype = MPDU_MANAGEMENT_SUBTYPE_ACTION;
    794 	/* Section 2.4.3 */
    795 	memcpy(header->address_1, peer->device_addr, 6);	/* DA */
    796 	memcpy(header->address_2, dev->addr, 6);		/* SA */
    797 	memcpy(header->address_3, bssid, 6);			/* BSSID */
    798 
    799 	for (iov = tx_body, iov_cnt = 0; iov->iov_base; iov++)
    800 		iov_cnt++;
    801 
    802 	frame = l_new(struct iovec, iov_cnt + 2);
    803 	frame[0].iov_base = header_buf;
    804 	frame[0].iov_len = (const uint8_t *) mmpdu_body(header) - header_buf;
    805 	memcpy(frame + 1, tx_body, sizeof(struct iovec) * iov_cnt);
    806 
    807 	freq = own_channel ?
    808 		band_channel_to_freq(dev->listen_channel, BAND_FREQ_2_4_GHZ) :
    809 		peer->bss->frequency;
    810 
    811 	va_start(args, cb);
    812 
    813 	frame_xchg_startv(dev->wdev_id, frame, freq,
    814 				retry_interval, resp_timeout, retries_on_ack,
    815 				group_id, cb, dev, NULL, args);
    816 	va_end(args);
    817 
    818 	l_free(frame);
    819 }
    820 
    821 static const struct frame_xchg_prefix p2p_frame_go_neg_req = {
    822 	/* Management -> Public Action -> P2P -> GO Negotiation Request */
    823 	.frame_type = 0x00d0,
    824 	.data = (uint8_t []) {
    825 		0x04, 0x09, 0x50, 0x6f, 0x9a, 0x09,
    826 		P2P_ACTION_GO_NEGOTIATION_REQ
    827 	},
    828 	.len = 7,
    829 };
    830 
    831 static const struct frame_xchg_prefix p2p_frame_go_neg_resp = {
    832 	/* Management -> Public Action -> P2P -> GO Negotiation Response */
    833 	.frame_type = 0x00d0,
    834 	.data = (uint8_t []) {
    835 		0x04, 0x09, 0x50, 0x6f, 0x9a, 0x09,
    836 		P2P_ACTION_GO_NEGOTIATION_RESP
    837 	},
    838 	.len = 7,
    839 };
    840 
    841 static const struct frame_xchg_prefix p2p_frame_go_neg_confirm = {
    842 	/* Management -> Public Action -> P2P -> GO Negotiation Confirm */
    843 	.frame_type = 0x00d0,
    844 	.data = (uint8_t []) {
    845 		0x04, 0x09, 0x50, 0x6f, 0x9a, 0x09,
    846 		P2P_ACTION_GO_NEGOTIATION_CONFIRM
    847 	},
    848 	.len = 7,
    849 };
    850 
    851 static const struct frame_xchg_prefix p2p_frame_pd_resp = {
    852 	/* Management -> Public Action -> P2P -> Provision Discovery Response */
    853 	.frame_type = 0x00d0,
    854 	.data = (uint8_t []) {
    855 		0x04, 0x09, 0x50, 0x6f, 0x9a, 0x09,
    856 		P2P_ACTION_PROVISION_DISCOVERY_RESP
    857 	},
    858 	.len = 7,
    859 };
    860 
    861 static void p2p_peer_connect_done(struct p2p_device *dev)
    862 {
    863 	struct p2p_peer *peer = dev->conn_peer;
    864 
    865 	if (!dev->is_go) {
    866 		/* We can free anything potentially needed for a retry */
    867 		scan_bss_free(dev->conn_wsc_bss);
    868 		dev->conn_wsc_bss = NULL;
    869 		explicit_bzero(dev->conn_psk, 32);
    870 	}
    871 
    872 	dbus_pending_reply(&peer->wsc.pending_connect,
    873 				l_dbus_message_new_method_return(
    874 						peer->wsc.pending_connect));
    875 	l_dbus_property_changed(dbus_get_bus(),
    876 				p2p_peer_get_path(dev->conn_peer),
    877 				IWD_P2P_PEER_INTERFACE, "Connected");
    878 	l_dbus_property_changed(dbus_get_bus(),
    879 				p2p_peer_get_path(dev->conn_peer),
    880 				IWD_P2P_PEER_INTERFACE,
    881 				"ConnectedInterface");
    882 	l_dbus_property_changed(dbus_get_bus(),
    883 				p2p_peer_get_path(dev->conn_peer),
    884 				IWD_P2P_PEER_INTERFACE,
    885 				"ConnectedIP");
    886 }
    887 
    888 static void p2p_group_event(enum ap_event_type type, const void *event_data,
    889 				void *user_data)
    890 {
    891 	struct p2p_device *dev = user_data;
    892 
    893 	l_debug("type=%i", type);
    894 
    895 	switch (type) {
    896 	case AP_EVENT_START_FAILED:
    897 	case AP_EVENT_STOPPING:
    898 		dev->group = NULL;
    899 		p2p_connect_failed(dev);
    900 		break;
    901 
    902 	case AP_EVENT_STARTED:
    903 		ap_push_button(dev->group);
    904 		break;
    905 
    906 	case AP_EVENT_STATION_ADDED:
    907 	{
    908 		const struct ap_event_station_added_data *data = event_data;
    909 		L_AUTO_FREE_VAR(uint8_t *, wfd_data) = NULL;
    910 		ssize_t wfd_data_len = 0;
    911 		struct p2p_association_req req_info;
    912 		int r;
    913 
    914 		/*
    915 		 * We don't need to validate most of the Association Request
    916 		 * P2P IE contents as we already have all the information there
    917 		 * may be but we need to save some of the attributes because
    918 		 * section 3.2.3 requires that our Group Info includes
    919 		 * specifically the data from the association, not any of the
    920 		 * earlier exchanges:
    921 		 * "When a P2P Client associates with a P2P Group Owner, it
    922 		 * provides [...] the P2P Device Info attribute (see Section
    923 		 * 4.1.15) and the P2P Capability attribute (see Section 4.1.4)
    924 		 * in the P2P IE in the Association Request frame.  This
    925 		 * information shall be used by the P2P Group Owner for Group
    926 		 * Information Advertisement.
    927 		 */
    928 		r = p2p_parse_association_req(data->assoc_ies,
    929 						data->assoc_ies_len, &req_info);
    930 		if (r < 0) {
    931 			l_error("Can't parse P2P Association Request: %s (%i)",
    932 				strerror(-r), -r);
    933 			goto invalid_ie;
    934 		}
    935 
    936 		/*
    937 		 * Most of this duplicates the information we already have in
    938 		 * dev->conn_peer.
    939 		 */
    940 		dev->conn_peer_capability = req_info.capability;
    941 		dev->conn_peer_dev_info = req_info.device_info;
    942 		p2p_clear_association_req(&req_info);
    943 
    944 		if (dev->conn_own_wfd)
    945 			wfd_data = ie_tlv_extract_wfd_payload(data->assoc_ies,
    946 							data->assoc_ies_len,
    947 							&wfd_data_len);
    948 
    949 		if (!p2p_device_validate_conn_wfd(dev, wfd_data,
    950 							wfd_data_len))
    951 			goto invalid_ie;
    952 
    953 		/* Take the chance to update WFD attributes for Session Info */
    954 		if (wfd_data)
    955 			p2p_extract_wfd_properties(wfd_data, wfd_data_len,
    956 							dev->conn_peer->wfd);
    957 
    958 		/* Setup is progressing so re-arm the timeout */
    959 		l_timeout_modify(dev->conn_dhcp_timeout, p2p_dhcp_timeout_val);
    960 		break;
    961 	}
    962 
    963 	case AP_EVENT_STATION_REMOVED:
    964 		dev->conn_peer_added = false;
    965 		p2p_connect_failed(dev);
    966 		break;
    967 
    968 	case AP_EVENT_REGISTRATION_START:
    969 		/* Don't validate the P2P IE or WFD IE at this stage */
    970 		break;
    971 	case AP_EVENT_REGISTRATION_SUCCESS:
    972 		/* Update the Group Formation bit in our beacons */
    973 		dev->capability.group_caps &= ~P2P_GROUP_CAP_GROUP_FORMATION;
    974 		ap_update_beacon(dev->group);
    975 		break;
    976 	case AP_EVENT_PBC_MODE_EXIT:
    977 		break;
    978 
    979 	case AP_EVENT_DHCP_NEW_LEASE:
    980 	{
    981 		const struct l_dhcp_lease *lease = event_data;
    982 
    983 		if (dev->conn_peer_added)
    984 			break;
    985 
    986 		l_rtnl_set_linkmode_and_operstate(iwd_get_rtnl(),
    987 					netdev_get_ifindex(dev->conn_netdev),
    988 					IF_LINK_MODE_DEFAULT, IF_OPER_UP,
    989 					NULL, NULL, NULL);
    990 
    991 		dev->conn_peer_added = true;
    992 		dev->conn_peer_ip = l_dhcp_lease_get_address(lease);
    993 		l_timeout_remove(dev->conn_dhcp_timeout);
    994 		p2p_peer_connect_done(dev);
    995 		break;
    996 	}
    997 
    998 	case AP_EVENT_DHCP_LEASE_EXPIRED:
    999 		/*
   1000 		 * Only one DHCP lease allowed for now, as soon as it expires
   1001 		 * the connection is considered to be down.
   1002 		 */
   1003 		p2p_connect_failed(dev);
   1004 		break;
   1005 	};
   1006 
   1007 	return;
   1008 
   1009 invalid_ie:
   1010 	ap_station_disconnect(dev->group, dev->conn_peer_interface_addr,
   1011 				MMPDU_REASON_CODE_INVALID_IE);
   1012 	p2p_connect_failed(dev);
   1013 }
   1014 
   1015 static size_t p2p_group_get_p2p_ie_len(struct p2p_device *dev,
   1016 					enum mpdu_management_subtype type,
   1017 					const struct mmpdu_header *client_frame,
   1018 					size_t client_frame_len)
   1019 {
   1020 	switch (type) {
   1021 	case MPDU_MANAGEMENT_SUBTYPE_ASSOCIATION_RESPONSE:
   1022 	case MPDU_MANAGEMENT_SUBTYPE_REASSOCIATION_RESPONSE:
   1023 	case MPDU_MANAGEMENT_SUBTYPE_PROBE_RESPONSE:
   1024 	case MPDU_MANAGEMENT_SUBTYPE_BEACON:
   1025 		return 256;
   1026 	default:
   1027 		return 0;
   1028 	}
   1029 }
   1030 
   1031 static size_t p2p_group_write_p2p_ie(struct p2p_device *dev,
   1032 					enum mpdu_management_subtype type,
   1033 					const struct mmpdu_header *client_frame,
   1034 					size_t client_frame_len,
   1035 					uint8_t *out_buf)
   1036 {
   1037 	L_AUTO_FREE_VAR(uint8_t *, p2p_ie) = NULL;
   1038 	size_t p2p_ie_len;
   1039 
   1040 	switch (type) {
   1041 	case MPDU_MANAGEMENT_SUBTYPE_ASSOCIATION_RESPONSE:
   1042 	case MPDU_MANAGEMENT_SUBTYPE_REASSOCIATION_RESPONSE:
   1043 	{
   1044 		/*
   1045 		 * Wi-Fi P2P Technical Specification v1.7 Section 4.2.5:
   1046 		 * "If neither P2P attribute is required according to the
   1047 		 * conditions in Table 55, then a P2P IE containing no P2P
   1048 		 * attributes is included."
   1049 		 * This is going to be our case.
   1050 		 */
   1051 		struct p2p_association_resp info = {};
   1052 
   1053 		p2p_ie = p2p_build_association_resp(&info, &p2p_ie_len);
   1054 		break;
   1055 	}
   1056 
   1057 	case MPDU_MANAGEMENT_SUBTYPE_PROBE_RESPONSE:
   1058 	{
   1059 		L_AUTO_FREE_VAR(uint8_t *, tmp) = NULL;
   1060 		struct p2p_probe_resp info = {};
   1061 		const struct mmpdu_probe_request *req =
   1062 			mmpdu_body(client_frame);
   1063 		size_t req_ies_len = (void *) client_frame + client_frame_len -
   1064 			(void *) req->ies;
   1065 		ssize_t req_p2p_data_size;
   1066 
   1067 		/*
   1068 		 * Wi-Fi P2P Technical Specification v1.7 Section 3.2.2:
   1069 		 * "A P2P Group Owner shall not include a P2P IE in the Probe
   1070 		 * Response frame if the received Probe Request frame does
   1071 		 * not contain a P2P IE."
   1072 		 */
   1073 		tmp = ie_tlv_extract_p2p_payload(req->ies, req_ies_len,
   1074 							&req_p2p_data_size);
   1075 		if (!tmp)
   1076 			return 0;
   1077 
   1078 		info.capability = dev->capability;
   1079 		info.device_info = dev->device_info;
   1080 
   1081 		if (dev->conn_peer_added) {
   1082 			struct p2p_client_info_descriptor client = {};
   1083 
   1084 			memcpy(client.device_addr,
   1085 				dev->conn_peer_dev_info.device_addr, 6);
   1086 			memcpy(client.interface_addr,
   1087 				dev->conn_peer_interface_addr, 6);
   1088 			client.device_caps =
   1089 				dev->conn_peer_capability.device_caps;
   1090 			client.wsc_config_methods =
   1091 				dev->conn_peer_dev_info.wsc_config_methods;
   1092 			client.primary_device_type =
   1093 				dev->conn_peer_dev_info.primary_device_type;
   1094 			l_strlcpy(client.device_name,
   1095 					dev->conn_peer_dev_info.device_name,
   1096 					sizeof(client.device_name));
   1097 
   1098 			info.group_clients = l_queue_new();
   1099 			l_queue_push_tail(info.group_clients,
   1100 					l_memdup(&client, sizeof(client)));
   1101 		}
   1102 
   1103 		p2p_ie = p2p_build_probe_resp(&info, &p2p_ie_len);
   1104 		p2p_clear_probe_resp(&info);
   1105 		break;
   1106 	}
   1107 
   1108 	case MPDU_MANAGEMENT_SUBTYPE_BEACON:
   1109 	{
   1110 		struct p2p_beacon info = {};
   1111 
   1112 		info.capability = dev->capability;
   1113 		memcpy(info.device_addr, dev->addr, 6);
   1114 		p2p_ie = p2p_build_beacon(&info, &p2p_ie_len);
   1115 		break;
   1116 	}
   1117 
   1118 	default:
   1119 		return 0;
   1120 	}
   1121 
   1122 	memcpy(out_buf, p2p_ie, p2p_ie_len);
   1123 	return p2p_ie_len;
   1124 }
   1125 
   1126 static size_t p2p_group_get_wfd_ie_len(struct p2p_device *dev,
   1127 					enum mpdu_management_subtype type,
   1128 					const struct mmpdu_header *client_frame,
   1129 					size_t client_frame_len)
   1130 {
   1131 	switch (type) {
   1132 	case MPDU_MANAGEMENT_SUBTYPE_ASSOCIATION_RESPONSE:
   1133 	case MPDU_MANAGEMENT_SUBTYPE_REASSOCIATION_RESPONSE:
   1134 		return (dev->conn_own_wfd && !dev->conn_own_wfd->r2) ? 32 : 0;
   1135 	case MPDU_MANAGEMENT_SUBTYPE_PROBE_RESPONSE:
   1136 	case MPDU_MANAGEMENT_SUBTYPE_BEACON:
   1137 		return p2p_own_wfd ? 64 : 0;
   1138 	default:
   1139 		return 0;
   1140 	}
   1141 }
   1142 
   1143 static size_t p2p_group_write_wfd_ie(struct p2p_device *dev,
   1144 					enum mpdu_management_subtype type,
   1145 					const struct mmpdu_header *client_frame,
   1146 					size_t client_frame_len,
   1147 					uint8_t *out_buf)
   1148 {
   1149 	switch (type) {
   1150 	case MPDU_MANAGEMENT_SUBTYPE_ASSOCIATION_RESPONSE:
   1151 	case MPDU_MANAGEMENT_SUBTYPE_REASSOCIATION_RESPONSE:
   1152 		if (dev->conn_own_wfd && !dev->conn_own_wfd->r2)
   1153 			return p2p_build_wfd_ie(dev->conn_own_wfd, NULL,
   1154 						out_buf);
   1155 
   1156 		break;
   1157 	case MPDU_MANAGEMENT_SUBTYPE_PROBE_RESPONSE:
   1158 		if (p2p_own_wfd)
   1159 			return p2p_build_wfd_ie(p2p_own_wfd,
   1160 						dev->conn_own_wfd ?
   1161 						dev->conn_peer : NULL, out_buf);
   1162 
   1163 		break;
   1164 	case MPDU_MANAGEMENT_SUBTYPE_BEACON:
   1165 		if (p2p_own_wfd)
   1166 			return p2p_build_wfd_ie(p2p_own_wfd, NULL, out_buf);
   1167 
   1168 		break;
   1169 	default:
   1170 		break;
   1171 	}
   1172 
   1173 	return 0;
   1174 }
   1175 
   1176 static size_t p2p_group_get_ies_len(enum mpdu_management_subtype type,
   1177 					const struct mmpdu_header *client_frame,
   1178 					size_t client_frame_len,
   1179 					void *user_data)
   1180 {
   1181 	struct p2p_device *dev = user_data;
   1182 
   1183 	return p2p_group_get_p2p_ie_len(dev, type,
   1184 					client_frame, client_frame_len) +
   1185 		p2p_group_get_wfd_ie_len(dev, type,
   1186 						client_frame, client_frame_len);
   1187 }
   1188 
   1189 static size_t p2p_group_write_ies(enum mpdu_management_subtype type,
   1190 					const struct mmpdu_header *client_frame,
   1191 					size_t client_frame_len,
   1192 					uint8_t *out_buf, void *user_data)
   1193 {
   1194 	struct p2p_device *dev = user_data;
   1195 	size_t len;
   1196 
   1197 	len = p2p_group_write_p2p_ie(dev, type,
   1198 					client_frame, client_frame_len,
   1199 					out_buf);
   1200 	len += p2p_group_write_wfd_ie(dev, type,
   1201 					client_frame, client_frame_len,
   1202 					out_buf + len);
   1203 
   1204 	return len;
   1205 }
   1206 
   1207 static const struct ap_ops p2p_go_ops = {
   1208 	.handle_event = p2p_group_event,
   1209 	.get_extra_ies_len = p2p_group_get_ies_len,
   1210 	.write_extra_ies = p2p_group_write_ies,
   1211 };
   1212 
   1213 static void p2p_dhcp_timeout(struct l_timeout *timeout, void *user_data)
   1214 {
   1215 	struct p2p_device *dev = user_data;
   1216 
   1217 	l_debug("");
   1218 
   1219 	p2p_connect_failed(dev);
   1220 }
   1221 
   1222 static void p2p_dhcp_timeout_destroy(void *user_data)
   1223 {
   1224 	struct p2p_device *dev = user_data;
   1225 
   1226 	dev->conn_dhcp_timeout = NULL;
   1227 }
   1228 
   1229 static void p2p_group_start(struct p2p_device *dev)
   1230 {
   1231 	struct l_settings *config = l_settings_new();
   1232 	uint8_t psk[32];
   1233 	char *macs[2] = {};
   1234 	const struct wsc_primary_device_type *pdt =
   1235 		&dev->device_info.primary_device_type;
   1236 	uint64_t pdt_uint =
   1237 		((uint64_t) pdt->category << 48) |
   1238 		((uint64_t) pdt->oui[0] << 40) |
   1239 		((uint64_t) pdt->oui[1] << 32) |
   1240 		((uint64_t) pdt->oui[2] << 24) |
   1241 		((uint64_t) pdt->oui_type << 16) |
   1242 		pdt->subcategory;
   1243 
   1244 	l_settings_set_string(config, "General", "SSID", dev->go_group_id.ssid);
   1245 	l_settings_set_uint(config, "General", "Channel", dev->listen_channel);
   1246 	l_settings_set_bool(config, "General", "NoCCKRates", true);
   1247 	l_settings_set_string(config, "WSC", "DeviceName",
   1248 				dev->device_info.device_name);
   1249 	l_settings_set_uint64(config, "WSC", "PrimaryDeviceType", pdt_uint);
   1250 	/*
   1251 	 * Section 3.1.4.4: "It shall only allow association by the
   1252 	 * P2P Device that it is currently in Group Formation with."
   1253 	 */
   1254 	macs[0] = (char *) util_address_to_string(
   1255 						dev->conn_peer_interface_addr);
   1256 	l_settings_set_string_list(config, "WSC", "AuthorizedMACs", macs, ',');
   1257 
   1258 	/*
   1259 	 * Section 3.2.1: "The Credentials for a P2P Group issued to a
   1260 	 * P2P Device shall: [...]
   1261 	 *  - Use a Network Key Type of 64 Hex characters."
   1262 	 *
   1263 	 * This implies we have to send the PSK and not the passphrase to
   1264 	 * the WSC clients.  For simplicity we directly generate random
   1265 	 * PSKs and don't currently respect the requirement to maintain
   1266 	 * a passphrase.  We have no practical use for the passphrase and
   1267 	 * it's a little costlier to generate for the same cryptographic
   1268 	 * strength as the PSK.
   1269 	 */
   1270 	if (!l_getrandom(psk, 32)) {
   1271 		l_error("l_getrandom() failed");
   1272 		l_settings_free(config);
   1273 		p2p_connect_failed(dev);
   1274 		return;
   1275 	}
   1276 
   1277 	l_settings_set_bytes(config, "Security", "PreSharedKey", psk, 32);
   1278 
   1279 	/* Enable netconfig, set maximum usable DHCP lease time */
   1280 	l_settings_set_uint(config, "IPv4", "LeaseTime", 0x7fffffff);
   1281 
   1282 	l_settings_set_string(config, "Security", "PairwiseCiphers", "CCMP");
   1283 	l_settings_set_string(config, "Security", "GroupCipher", "CCMP");
   1284 
   1285 	dev->capability.group_caps |= P2P_GROUP_CAP_GO;
   1286 	dev->capability.group_caps |= P2P_GROUP_CAP_GROUP_FORMATION;
   1287 	dev->capability.group_caps |= P2P_GROUP_CAP_IP_ALLOCATION;
   1288 
   1289 	dev->group = ap_start(dev->conn_netdev, config, &p2p_go_ops, NULL, dev);
   1290 	l_settings_free(config);
   1291 
   1292 	if (!dev->group) {
   1293 		p2p_connect_failed(dev);
   1294 		return;
   1295 	}
   1296 
   1297 	/* Set timeout on client connecting and getting its IP */
   1298 	dev->conn_dhcp_timeout = l_timeout_create(p2p_dhcp_timeout_val,
   1299 						p2p_dhcp_timeout, dev,
   1300 						p2p_dhcp_timeout_destroy);
   1301 }
   1302 
   1303 static void p2p_netconfig_event_handler(enum netconfig_event event,
   1304 					void *user_data)
   1305 {
   1306 	struct p2p_device *dev = user_data;
   1307 
   1308 	switch (event) {
   1309 	case NETCONFIG_EVENT_CONNECTED:
   1310 		l_timeout_remove(dev->conn_dhcp_timeout);
   1311 
   1312 		if (!dev->conn_peer_ip)
   1313 			dev->conn_peer_ip = netconfig_get_dhcp_server_ipv4(
   1314 							dev->conn_netconfig);
   1315 
   1316 		p2p_peer_connect_done(dev);
   1317 		break;
   1318 	default:
   1319 		l_error("station: Unsupported netconfig event: %d.", event);
   1320 		p2p_connect_failed(dev);
   1321 		break;
   1322 	}
   1323 }
   1324 
   1325 static void p2p_start_client_netconfig(struct p2p_device *dev)
   1326 {
   1327 	uint32_t ifindex = netdev_get_ifindex(dev->conn_netdev);
   1328 	struct l_settings *settings;
   1329 
   1330 	if (!dev->conn_netconfig) {
   1331 		dev->conn_netconfig = netconfig_new(ifindex);
   1332 		if (!dev->conn_netconfig) {
   1333 			p2p_connect_failed(dev);
   1334 			return;
   1335 		}
   1336 	}
   1337 
   1338 	settings = dev->conn_netconfig_settings ?: p2p_dhcp_settings;
   1339 
   1340 	if (!netconfig_load_settings(dev->conn_netconfig, settings) ||
   1341 			!netconfig_configure(dev->conn_netconfig,
   1342 						p2p_netconfig_event_handler,
   1343 						dev)) {
   1344 		p2p_connect_failed(dev);
   1345 		return;
   1346 	}
   1347 
   1348 	dev->conn_dhcp_timeout = l_timeout_create(p2p_dhcp_timeout_val,
   1349 						p2p_dhcp_timeout, dev,
   1350 						p2p_dhcp_timeout_destroy);
   1351 }
   1352 
   1353 static void p2p_netdev_connect_cb(struct netdev *netdev,
   1354 					enum netdev_result result,
   1355 					void *event_data, void *user_data)
   1356 {
   1357 	struct p2p_device *dev = user_data;
   1358 	struct p2p_peer *peer = dev->conn_peer;
   1359 
   1360 	l_debug("result: %i", result);
   1361 
   1362 	if (!peer->wsc.pending_connect || dev->disconnecting) {
   1363 		/* Shouldn't happen except maybe in the ABORTED case */
   1364 		return;
   1365 	}
   1366 
   1367 	switch (result) {
   1368 	case NETDEV_RESULT_OK:
   1369 		p2p_start_client_netconfig(dev);
   1370 		break;
   1371 	case NETDEV_RESULT_AUTHENTICATION_FAILED:
   1372 	case NETDEV_RESULT_ASSOCIATION_FAILED:
   1373 	case NETDEV_RESULT_HANDSHAKE_FAILED:
   1374 	case NETDEV_RESULT_KEY_SETTING_FAILED:
   1375 	case NETDEV_RESULT_DISCONNECTED:
   1376 		/*
   1377 		 * In the AUTHENTICATION_FAILED and ASSOCIATION_FAILED
   1378 		 * cases there's nothing to disconnect.  In the
   1379 		 * HANDSHAKE_FAILED and KEY_SETTING failed cases
   1380 		 * netdev disconnects from the GO automatically and we are
   1381 		 * called already from within the disconnect callback,
   1382 		 * so we can directly free the netdev.
   1383 		 */
   1384 		p2p_connect_failed(dev);
   1385 		break;
   1386 	case NETDEV_RESULT_ABORTED:
   1387 		/*
   1388 		 * This case can only be triggered by netdev_disconnect so
   1389 		 * we'll wait for its callback before freeing the netdev.
   1390 		 * We will also have already replied to
   1391 		 * @peer->wsc.pending_connect so we have nothing to do here.
   1392 		 */
   1393 		break;
   1394 	}
   1395 }
   1396 
   1397 static void p2p_try_connect_group(struct p2p_device *dev);
   1398 
   1399 static void p2p_netdev_event(struct netdev *netdev, enum netdev_event event,
   1400 				void *event_data, void *user_data)
   1401 {
   1402 	struct p2p_device *dev = user_data;
   1403 	const uint16_t *reason_code;
   1404 
   1405 	switch (event) {
   1406 	case NETDEV_EVENT_DISCONNECT_BY_AP:
   1407 		reason_code = event_data;
   1408 
   1409 		if (*reason_code == MMPDU_REASON_CODE_PREV_AUTH_NOT_VALID &&
   1410 				dev->conn_wsc_bss &&
   1411 				dev->conn_retry_count < 5) {
   1412 			/*
   1413 			 * Sometimes a retry helps here, may be that we haven't
   1414 			 * waited long enough for the GO setup.
   1415 			 */
   1416 			l_timeout_remove(dev->conn_dhcp_timeout);
   1417 
   1418 			if (dev->conn_netconfig)
   1419 				netconfig_reset(dev->conn_netconfig);
   1420 
   1421 			p2p_try_connect_group(dev);
   1422 			break;
   1423 		}
   1424 
   1425 		/* Fall through. */
   1426 	case NETDEV_EVENT_DISCONNECT_BY_SME:
   1427 		/*
   1428 		 * We may get a DISCONNECT_BY_SME as a result of a
   1429 		 * netdev_disconnect().  In that case let the callback handle
   1430 		 * that.
   1431 		 */
   1432 		if (dev->disconnecting)
   1433 			break;
   1434 
   1435 		/* If we're not connected, .Connected is already False */
   1436 		if (!p2p_peer_operational(dev->conn_peer)) {
   1437 			p2p_connect_failed(dev);
   1438 			break;
   1439 		}
   1440 
   1441 		l_dbus_property_changed(dbus_get_bus(),
   1442 					p2p_peer_get_path(dev->conn_peer),
   1443 					IWD_P2P_PEER_INTERFACE, "Connected");
   1444 		l_dbus_property_changed(dbus_get_bus(),
   1445 					p2p_peer_get_path(dev->conn_peer),
   1446 					IWD_P2P_PEER_INTERFACE,
   1447 					"ConnectedInterface");
   1448 		l_dbus_property_changed(dbus_get_bus(),
   1449 					p2p_peer_get_path(dev->conn_peer),
   1450 					IWD_P2P_PEER_INTERFACE,
   1451 					"ConnectedIP");
   1452 		p2p_connection_reset(dev);
   1453 		break;
   1454 	default:
   1455 		break;
   1456 	};
   1457 }
   1458 
   1459 static const char *p2p_ip_to_string(uint32_t addr)
   1460 {
   1461 	struct in_addr ia = { .s_addr = addr };
   1462 
   1463 	return inet_ntoa(ia);
   1464 }
   1465 
   1466 static void p2p_handshake_event(struct handshake_state *hs,
   1467 				enum handshake_event event, void *user_data,
   1468 				...)
   1469 {
   1470 	va_list args;
   1471 
   1472 	va_start(args, user_data);
   1473 
   1474 	switch (event) {
   1475 	case HANDSHAKE_EVENT_COMPLETE:
   1476 	{
   1477 		struct p2p_device *dev = user_data;
   1478 		struct l_settings *ip_config;
   1479 
   1480 		if (!hs->support_ip_allocation)
   1481 			break;
   1482 
   1483 		ip_config = l_settings_new();
   1484 		l_settings_set_string(ip_config, "IPv4", "Address",
   1485 					p2p_ip_to_string(hs->client_ip_addr));
   1486 		l_settings_set_string(ip_config, "IPv4", "Netmask",
   1487 					p2p_ip_to_string(hs->subnet_mask));
   1488 		dev->conn_netconfig_settings = ip_config;
   1489 		dev->conn_peer_ip = l_strdup(p2p_ip_to_string(hs->go_ip_addr));
   1490 
   1491 		break;
   1492 	}
   1493 	case HANDSHAKE_EVENT_FAILED:
   1494 		netdev_handshake_failed(hs, va_arg(args, int));
   1495 		break;
   1496 	default:
   1497 		break;
   1498 	}
   1499 
   1500 	va_end(args);
   1501 }
   1502 
   1503 static void p2p_try_connect_group(struct p2p_device *dev)
   1504 {
   1505 	struct scan_bss *bss = dev->conn_wsc_bss;
   1506 	_auto_(handshake_state_unref) struct handshake_state *hs = NULL;
   1507 	struct iovec ie_iov[16];
   1508 	int ie_num = 0;
   1509 	int r;
   1510 	struct p2p_association_req info = {
   1511 		.capability = dev->capability,
   1512 		.device_info = dev->device_info,
   1513 	};
   1514 	struct ie_rsn_info bss_info = {};
   1515 	struct ie_rsn_info rsn_info = {};
   1516 	uint8_t rsne_buf[256];
   1517 	uint8_t wfd_ie[32];
   1518 	_auto_(l_free) uint8_t *req_ie =
   1519 		p2p_build_association_req(&info, &ie_iov[ie_num].iov_len);
   1520 
   1521 	ie_iov[ie_num++].iov_base = req_ie;
   1522 
   1523 	if (dev->conn_own_wfd) {
   1524 		ie_iov[ie_num].iov_base = wfd_ie;
   1525 		ie_iov[ie_num].iov_len = p2p_build_wfd_ie(dev->conn_own_wfd,
   1526 								NULL, wfd_ie);
   1527 		ie_num++;
   1528 	}
   1529 
   1530 	scan_bss_get_rsn_info(bss, &bss_info);
   1531 
   1532 	rsn_info.akm_suites = wiphy_select_akm(dev->wiphy, bss, SECURITY_PSK,
   1533 						&bss_info, false);
   1534 	if (!rsn_info.akm_suites)
   1535 		goto not_supported;
   1536 
   1537 	rsn_info.pairwise_ciphers = wiphy_select_cipher(dev->wiphy,
   1538 						bss_info.pairwise_ciphers);
   1539 	rsn_info.group_cipher = wiphy_select_cipher(dev->wiphy,
   1540 						bss_info.group_cipher);
   1541 	if (!rsn_info.pairwise_ciphers || !rsn_info.group_cipher)
   1542 		goto not_supported;
   1543 
   1544 	rsn_info.group_management_cipher = wiphy_select_cipher(dev->wiphy,
   1545 					bss_info.group_management_cipher);
   1546 	rsn_info.mfpc = rsn_info.group_management_cipher != 0;
   1547 	ie_build_rsne(&rsn_info, rsne_buf);
   1548 
   1549 	hs = netdev_handshake_state_new(dev->conn_netdev);
   1550 
   1551 	if (!handshake_state_set_authenticator_ie(hs, bss->rsne))
   1552 		goto not_supported;
   1553 
   1554 	if (!handshake_state_set_supplicant_ie(hs, rsne_buf))
   1555 		goto not_supported;
   1556 
   1557 	handshake_state_set_event_func(hs, p2p_handshake_event, dev);
   1558 	handshake_state_set_ssid(hs, bss->ssid, bss->ssid_len);
   1559 	handshake_state_set_pmk(hs, dev->conn_psk, 32);
   1560 	handshake_state_set_vendor_ies(hs, ie_iov, ie_num);
   1561 
   1562 	if (dev->conn_peer_capability.group_caps & P2P_GROUP_CAP_IP_ALLOCATION)
   1563 		hs->support_ip_allocation = true;
   1564 
   1565 	r = netdev_connect(dev->conn_netdev, bss, hs,
   1566 				p2p_netdev_event, p2p_netdev_connect_cb, dev);
   1567 	if (r < 0) {
   1568 		l_error("netdev_connect error: %s (%i)", strerror(-r), -r);
   1569 		goto error;
   1570 	}
   1571 
   1572 	l_steal_ptr(hs);
   1573 	dev->conn_retry_count++;
   1574 	return;
   1575 
   1576 error:
   1577 not_supported:
   1578 	p2p_connect_failed(dev);
   1579 }
   1580 
   1581 static void p2p_peer_provision_done(int err, struct wsc_credentials_info *creds,
   1582 					unsigned int n_creds, void *user_data)
   1583 {
   1584 	struct p2p_peer *peer = user_data;
   1585 	struct p2p_device *dev = peer->dev;
   1586 	struct scan_bss *bss = dev->conn_wsc_bss;
   1587 
   1588 	l_debug("err=%i n_creds=%u", err, n_creds);
   1589 
   1590 	dev->conn_enrollee = NULL;
   1591 
   1592 	l_timeout_remove(dev->conn_peer_config_timeout);
   1593 	l_timeout_remove(dev->conn_go_neg_req_timeout);
   1594 
   1595 	if (err < 0) {
   1596 		if (err == -ECANCELED && peer->wsc.pending_cancel) {
   1597 			dbus_pending_reply(&peer->wsc.pending_cancel,
   1598 				l_dbus_message_new_method_return(
   1599 						peer->wsc.pending_cancel));
   1600 
   1601 			p2p_connection_reset(dev);
   1602 			return;
   1603 		}
   1604 
   1605 		goto error;
   1606 	}
   1607 
   1608 	if (strlen(creds[0].ssid) != bss->ssid_len ||
   1609 			memcmp(creds[0].ssid, bss->ssid, bss->ssid_len)) {
   1610 		l_error("Unsupported: the SSID from the P2P peer's WSC "
   1611 			"credentials doesn't match the SSID from the "
   1612 			"Probe Response IEs");
   1613 		goto not_supported;
   1614 	}
   1615 
   1616 	/*
   1617 	 * Apparently some implementations send the intended client's address
   1618 	 * here (i.e. our), and some send the target BSS's (their own).
   1619 	 */
   1620 	if (memcmp(creds[0].addr, netdev_get_address(dev->conn_netdev), 6) &&
   1621 			memcmp(creds[0].addr, bss->addr, 6)) {
   1622 		char addr1[32], addr2[32];
   1623 
   1624 		l_strlcpy(addr1, util_address_to_string(creds[0].addr),
   1625 				sizeof(addr1));
   1626 		l_strlcpy(addr2, util_address_to_string(
   1627 					netdev_get_address(dev->conn_netdev)),
   1628 				sizeof(addr2));
   1629 		l_error("Error: WSC credentials are not for our client "
   1630 			"interface (%s vs. %s)", addr1, addr2);
   1631 		goto error;
   1632 	}
   1633 
   1634 	if (!bss->rsne || creds[0].security != SECURITY_PSK)
   1635 		goto not_supported;
   1636 
   1637 	if (creds[0].has_passphrase) {
   1638 		if (crypto_psk_from_passphrase(creds[0].passphrase, bss->ssid,
   1639 						bss->ssid_len,
   1640 						dev->conn_psk) < 0)
   1641 			goto error;
   1642 	} else
   1643 		memcpy(dev->conn_psk, creds[0].psk, 32);
   1644 
   1645 	dev->conn_retry_count = 0;
   1646 	p2p_try_connect_group(dev);
   1647 	return;
   1648 
   1649 error:
   1650 not_supported:
   1651 	p2p_connect_failed(dev);
   1652 }
   1653 
   1654 static void p2p_provision_connect(struct p2p_device *dev)
   1655 {
   1656 	struct iovec iov[16];
   1657 	int iov_num;
   1658 	uint8_t wfd_ie[32];
   1659 	struct p2p_association_req info = {};
   1660 
   1661 	/* Ready to start the provisioning */
   1662 	info.capability = dev->capability;
   1663 	info.device_info = dev->device_info;
   1664 
   1665 	iov[0].iov_base = p2p_build_association_req(&info, &iov[0].iov_len);
   1666 	L_WARN_ON(!iov[0].iov_base);
   1667 	iov_num = 1;
   1668 
   1669 	if (dev->conn_own_wfd) {
   1670 		iov[iov_num].iov_base = wfd_ie;
   1671 		iov[iov_num].iov_len = p2p_build_wfd_ie(dev->conn_own_wfd,
   1672 							NULL, wfd_ie);
   1673 		iov_num++;
   1674 	}
   1675 
   1676 	dev->conn_enrollee = wsc_enrollee_new(dev->conn_netdev,
   1677 						dev->conn_wsc_bss,
   1678 						dev->conn_pin, iov, iov_num,
   1679 						p2p_peer_provision_done,
   1680 						dev->conn_peer);
   1681 	l_free(iov[0].iov_base);
   1682 }
   1683 
   1684 static void p2p_device_netdev_watch_destroy(void *user_data)
   1685 {
   1686 	struct p2p_device *dev = user_data;
   1687 
   1688 	dev->conn_netdev_watch_id = 0;
   1689 }
   1690 
   1691 static void p2p_device_netdev_notify(struct netdev *netdev,
   1692 					enum netdev_watch_event event,
   1693 					void *user_data)
   1694 {
   1695 	struct p2p_device *dev = user_data;
   1696 
   1697 	if (dev->conn_netdev != netdev)
   1698 		return;
   1699 
   1700 	switch (event) {
   1701 	case NETDEV_WATCH_EVENT_UP:
   1702 	case NETDEV_WATCH_EVENT_NEW:
   1703 		/* Ignore the event if we're already connecting/connected */
   1704 		if (dev->conn_enrollee || dev->conn_retry_count ||
   1705 				dev->group || !netdev_get_is_up(netdev))
   1706 			break;
   1707 
   1708 		if (dev->is_go)
   1709 			p2p_group_start(dev);
   1710 		else
   1711 			p2p_provision_connect(dev);
   1712 
   1713 		break;
   1714 	case NETDEV_WATCH_EVENT_DEL:
   1715 		dev->conn_netdev = NULL;
   1716 		/* Fall through */
   1717 	case NETDEV_WATCH_EVENT_DOWN:
   1718 	case NETDEV_WATCH_EVENT_ADDRESS_CHANGE:
   1719 		p2p_connect_failed(dev);
   1720 		break;
   1721 	default:
   1722 		break;
   1723 	}
   1724 }
   1725 
   1726 static void p2p_device_new_interface_cb(struct l_genl_msg *msg,
   1727 					void *user_data)
   1728 {
   1729 	struct p2p_device *dev = user_data;
   1730 
   1731 	l_debug("");
   1732 
   1733 	if (l_genl_msg_get_error(msg) < 0) {
   1734 		l_error("NEW_INTERFACE failed: %s",
   1735 			strerror(-l_genl_msg_get_error(msg)));
   1736 		p2p_connect_failed(dev);
   1737 		return;
   1738 	}
   1739 
   1740 	/* Create the netdev so we don't have to parse the message ourselves */
   1741 	dev->conn_netdev = netdev_create_from_genl(msg, dev->conn_addr);
   1742 	if (!dev->conn_netdev) {
   1743 		p2p_connect_failed(dev);
   1744 		return;
   1745 	}
   1746 
   1747 	/*
   1748 	 * Register a watch for each connection rather than having one
   1749 	 * global watch.  Each connection's watch will receive events
   1750 	 * related to all other connections too, and will check that its
   1751 	 * conn_netdev != netdev and exit immediately.  This is not ideal
   1752 	 * but it's the same complexity (n^2) as that of one global watch
   1753 	 * that receives all events and iterates over p2p_device_list to
   1754 	 * find the connection.
   1755 	 */
   1756 	dev->conn_netdev_watch_id = netdev_watch_add(p2p_device_netdev_notify,
   1757 					dev, p2p_device_netdev_watch_destroy);
   1758 }
   1759 
   1760 static void p2p_device_new_interface_destroy(void *user_data)
   1761 {
   1762 	struct p2p_device *dev = user_data;
   1763 
   1764 	dev->conn_new_intf_cmd_id = 0;
   1765 }
   1766 
   1767 static void p2p_device_interface_create(struct p2p_device *dev)
   1768 {
   1769 	uint32_t iftype = dev->is_go ? NL80211_IFTYPE_P2P_GO :
   1770 		NL80211_IFTYPE_P2P_CLIENT;
   1771 	char ifname[32];
   1772 	uint32_t wiphy_id = dev->wdev_id >> 32;
   1773 	struct l_genl_msg *msg;
   1774 
   1775 	snprintf(ifname, sizeof(ifname), "wlan%i-p2p-%s%i",
   1776 			wiphy_id, dev->is_go ? "go" : "cl", dev->conn_num++);
   1777 	l_debug("creating %s", ifname);
   1778 
   1779 	msg = l_genl_msg_new(NL80211_CMD_NEW_INTERFACE);
   1780 	l_genl_msg_append_attr(msg, NL80211_ATTR_WIPHY, 4, &wiphy_id);
   1781 	l_genl_msg_append_attr(msg, NL80211_ATTR_IFTYPE, 4, &iftype);
   1782 	l_genl_msg_append_attr(msg, NL80211_ATTR_IFNAME,
   1783 				strlen(ifname) + 1, ifname);
   1784 	l_genl_msg_append_attr(msg, NL80211_ATTR_4ADDR, 1, "\0");
   1785 	l_genl_msg_append_attr(msg, NL80211_ATTR_SOCKET_OWNER, 0, "");
   1786 
   1787 	dev->conn_new_intf_cmd_id = l_genl_family_send(dev->nl80211, msg,
   1788 					p2p_device_new_interface_cb, dev,
   1789 					p2p_device_new_interface_destroy);
   1790 	if (!dev->conn_new_intf_cmd_id) {
   1791 		l_genl_msg_unref(msg);
   1792 		l_error("Error sending NEW_INTERFACE for %s", ifname);
   1793 		p2p_connect_failed(dev);
   1794 	}
   1795 }
   1796 
   1797 static void p2p_scan_destroy(void *user_data)
   1798 {
   1799 	struct p2p_device *dev = user_data;
   1800 
   1801 	dev->scan_id = 0;
   1802 }
   1803 
   1804 static void p2p_provision_scan_start(struct p2p_device *dev);
   1805 
   1806 static bool p2p_provision_scan_notify(int err, struct l_queue *bss_list,
   1807 					const struct scan_freq_set *freqs,
   1808 					void *user_data)
   1809 {
   1810 	struct p2p_device *dev = user_data;
   1811 	const struct l_queue_entry *entry;
   1812 	static const uint8_t wildcard_addr[6] =
   1813 		{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
   1814 
   1815 	l_debug("err=%i, len(bss_list)=%i", err, l_queue_length(bss_list));
   1816 
   1817 	if (err) {
   1818 		l_error("P2P provision scan failed: %s (%i)", strerror(-err),
   1819 			-err);
   1820 		p2p_connect_failed(dev);
   1821 		return false;
   1822 	}
   1823 
   1824 	for (entry = l_queue_get_entries(bss_list); entry;
   1825 			entry = entry->next) {
   1826 		struct scan_bss *bss = entry->data;
   1827 		const uint8_t *group_id;
   1828 		bool selected_reg;
   1829 		struct p2p_capability_attr *capability;
   1830 		enum wsc_device_password_id device_password_id;
   1831 		const uint8_t *amacs;
   1832 		struct wsc_probe_response wsc_probe_info;
   1833 		struct wsc_beacon wsc_beacon_info;
   1834 
   1835 		/*
   1836 		 * Check if we found our target GO, some of these checks may
   1837 		 * need to be gradually relaxed as we discover non-compliant
   1838 		 * implementations but at least print a debug statement when
   1839 		 * something doesn't match.
   1840 		 */
   1841 
   1842 		if (strncmp((const char *) bss->ssid, dev->go_group_id.ssid,
   1843 				bss->ssid_len))
   1844 			continue;
   1845 
   1846 		if (dev->go_group_id.ssid[bss->ssid_len] != '\0')
   1847 			continue;
   1848 
   1849 		if (!l_memeqzero(dev->conn_peer_interface_addr, 6) &&
   1850 				memcmp(bss->addr, dev->conn_peer_interface_addr,
   1851 					6))
   1852 			l_debug("SSID matched but BSSID didn't match the GO's "
   1853 				"intended interface addr, proceeding anyway");
   1854 
   1855 		if (!bss->wsc) {
   1856 			l_error("SSID matched but no valid WSC IE");
   1857 			continue;
   1858 		}
   1859 
   1860 		if (bss->source_frame == SCAN_BSS_PROBE_RESP) {
   1861 			if (!bss->p2p_probe_resp_info) {
   1862 				l_error("SSID matched but no valid P2P IE");
   1863 				continue;
   1864 			}
   1865 
   1866 			if (wsc_parse_probe_response(bss->wsc, bss->wsc_size,
   1867 							&wsc_probe_info) < 0) {
   1868 				l_error("SSID matched but can't parse WSC "
   1869 					"Probe Response info");
   1870 				continue;
   1871 			}
   1872 
   1873 			group_id = bss->p2p_probe_resp_info->
   1874 				device_info.device_addr;
   1875 			selected_reg = wsc_probe_info.selected_registrar;
   1876 			capability = &bss->p2p_probe_resp_info->capability;
   1877 			device_password_id = wsc_probe_info.device_password_id;
   1878 			amacs = wsc_probe_info.authorized_macs;
   1879 		} else if (bss->source_frame == SCAN_BSS_BEACON) {
   1880 			if (!bss->p2p_beacon_info) {
   1881 				l_error("SSID matched but no valid P2P IE");
   1882 				continue;
   1883 			}
   1884 
   1885 			if (wsc_parse_beacon(bss->wsc, bss->wsc_size,
   1886 						&wsc_beacon_info) < 0) {
   1887 				l_error("SSID matched but can't parse WSC "
   1888 					"Beacon info");
   1889 				continue;
   1890 			}
   1891 
   1892 			group_id = bss->p2p_beacon_info->device_addr;
   1893 			selected_reg = wsc_beacon_info.selected_registrar;
   1894 			capability = &bss->p2p_beacon_info->capability;
   1895 			device_password_id = wsc_beacon_info.device_password_id;
   1896 			amacs = wsc_beacon_info.authorized_macs;
   1897 		} else
   1898 			continue;
   1899 
   1900 		if (memcmp(group_id, dev->go_group_id.device_addr, 6)) {
   1901 			l_error("SSID matched but Group ID address didn't");
   1902 			continue;
   1903 		}
   1904 
   1905 		if (!selected_reg) {
   1906 			/*
   1907 			 * Debug level because this will sometimes happen
   1908 			 * while the target is setting up the GO mode in the
   1909 			 * course of normal operation, and gets set to true
   1910 			 * in a few seconds, we just need to keep scanning.
   1911 			 */
   1912 			l_debug("SSID matched but not a Selected Reg");
   1913 			continue;
   1914 		}
   1915 
   1916 		if (dev->conn_peer->group && (capability->group_caps &
   1917 					P2P_GROUP_CAP_GROUP_FORMATION)) {
   1918 			l_error("SSID matched but not in Group Formation");
   1919 			continue;
   1920 		}
   1921 
   1922 		if (!dev->conn_peer->group && !(capability->group_caps &
   1923 					P2P_GROUP_CAP_GROUP_FORMATION))
   1924 			/*
   1925 			 * We have to ignore this one for interoperability
   1926 			 * with some devices.
   1927 			 */
   1928 			l_debug("SSID matched but GO not in Group Formation, "
   1929 				"proceeding anyway");
   1930 
   1931 		if (capability->group_caps & P2P_GROUP_CAP_GROUP_LIMIT) {
   1932 			l_error("SSID matched but group already full");
   1933 			continue;
   1934 		}
   1935 
   1936 		if (device_password_id != dev->conn_password_id) {
   1937 			l_error("SSID matched wrong Password ID");
   1938 			continue;
   1939 		}
   1940 
   1941 		if (!l_memeqzero(amacs, 30)) {
   1942 			bool amacs_match = false;
   1943 			int i;
   1944 
   1945 			for (i = 0; i < 5; i++, amacs += 6)
   1946 				if (!memcmp(amacs, dev->addr, 6) ||
   1947 						!memcmp(amacs, wildcard_addr, 6))
   1948 					amacs_match = true;
   1949 
   1950 			if (!amacs_match) {
   1951 				l_error("SSID matched we're not in AMacs");
   1952 				continue;
   1953 			}
   1954 		}
   1955 
   1956 		l_debug("GO found in the scan results");
   1957 
   1958 		dev->conn_wsc_bss = bss;
   1959 		dev->conn_peer_capability = *capability;
   1960 		p2p_device_interface_create(dev);
   1961 		l_queue_remove(bss_list, bss);
   1962 		l_queue_destroy(bss_list,
   1963 				(l_queue_destroy_func_t) scan_bss_free);
   1964 		return true;
   1965 	}
   1966 
   1967 	/* Retry a few times if the WSC AP not found or not ready */
   1968 	dev->conn_go_scan_retry++;
   1969 
   1970 	if (dev->conn_go_scan_retry > 15) {
   1971 		p2p_connect_failed(dev);
   1972 		return false;
   1973 	}
   1974 
   1975 	p2p_provision_scan_start(dev);
   1976 	return false;
   1977 }
   1978 
   1979 static void p2p_provision_scan_start(struct p2p_device *dev)
   1980 {
   1981 	struct scan_parameters params = {};
   1982 	struct scan_freq_set *freqs = NULL;
   1983 	uint8_t buf[256];
   1984 
   1985 	params.flush = true;
   1986 	params.no_cck_rates = true;
   1987 	params.ssid = (const uint8_t *)dev->go_group_id.ssid;
   1988 	params.ssid_len = strlen(dev->go_group_id.ssid);
   1989 	params.extra_ie = p2p_build_scan_ies(dev, buf, sizeof(buf),
   1990 						&params.extra_ie_size);
   1991 	L_WARN_ON(!params.extra_ie);
   1992 
   1993 	/*
   1994 	 * Rather than create the new interface and create a new
   1995 	 * scan_context on it, use the P2P-Device interface and set
   1996 	 * params.source_mac to our future P2P-Client address.
   1997 	 */
   1998 	params.source_mac = dev->conn_addr;
   1999 
   2000 	/*
   2001 	 * Initially scan just the Operating Channel the GO reported
   2002 	 * during the negotiation.  In theory there's no guarantee that
   2003 	 * it is going to be on that channel so we should fall back
   2004 	 * to scanning all the channels listed in the Channel List
   2005 	 * attribute.  For simplicity we just do a full scan in that
   2006 	 * scenario -- for most target P2P devices we wouldn't be saving
   2007 	 * ourselves any work anyway as the Channel List is going to
   2008 	 * contain all of the 2.4 and 5G channels.
   2009 	 */
   2010 	if (dev->conn_go_scan_retry < 12) {
   2011 		freqs = scan_freq_set_new();
   2012 		scan_freq_set_add(freqs, dev->conn_go_oper_freq);
   2013 		params.freqs = freqs;
   2014 	}
   2015 
   2016 	dev->scan_id = scan_active_full(dev->wdev_id, &params, NULL,
   2017 					p2p_provision_scan_notify, dev,
   2018 					p2p_scan_destroy);
   2019 
   2020 	if (freqs)
   2021 		scan_freq_set_free(freqs);
   2022 }
   2023 
   2024 static void p2p_start_client_provision(struct p2p_device *dev)
   2025 {
   2026 	char bssid_str[18];
   2027 
   2028 	memcpy(bssid_str, util_address_to_string(dev->conn_peer_interface_addr),
   2029 		18);
   2030 	l_debug("freq=%u ssid=%s group_addr=%s bssid=%s",
   2031 		dev->conn_go_oper_freq, dev->go_group_id.ssid,
   2032 		util_address_to_string(dev->go_group_id.device_addr),
   2033 		bssid_str);
   2034 
   2035 	dev->conn_go_scan_retry = 0;
   2036 	p2p_provision_scan_start(dev);
   2037 }
   2038 
   2039 static void p2p_config_timeout_destroy(void *user_data)
   2040 {
   2041 	struct p2p_device *dev = user_data;
   2042 
   2043 	dev->conn_peer_config_timeout = NULL;
   2044 }
   2045 
   2046 static void p2p_config_timeout(struct l_timeout *timeout, void *user_data)
   2047 {
   2048 	struct p2p_device *dev = user_data;
   2049 
   2050 	l_timeout_remove(dev->conn_peer_config_timeout);
   2051 
   2052 	/* Ready to start WSC */
   2053 	p2p_start_client_provision(dev);
   2054 }
   2055 
   2056 static void p2p_go_negotiation_resp_done(int error, void *user_data)
   2057 {
   2058 	struct p2p_device *dev = user_data;
   2059 
   2060 	if (error)
   2061 		l_error("Sending the GO Negotiation Response failed: %s (%i)",
   2062 			strerror(-error), -error);
   2063 	else
   2064 		l_error("No GO Negotiation Confirmation frame received");
   2065 
   2066 	p2p_connect_failed(dev);
   2067 }
   2068 
   2069 static void p2p_go_negotiation_resp_err_done(int error, void *user_data)
   2070 {
   2071 	if (error)
   2072 		l_error("Sending the GO Negotiation Response failed: %s (%i)",
   2073 			strerror(-error), -error);
   2074 }
   2075 
   2076 /*
   2077  * Called by GO Negotiation Response and Confirmation receive handlers,
   2078  * in both cases the channel lists are required to be subsets of our
   2079  * own supported channels and the Operating Channel must appear in the
   2080  * channel list.
   2081  */
   2082 static bool p2p_device_validate_channel_list(struct p2p_device *dev,
   2083 				const struct p2p_channel_list_attr *attr,
   2084 				const struct p2p_channel_attr *oper_channel)
   2085 {
   2086 	if (l_queue_isempty(attr->channel_entries))
   2087 		return false;
   2088 
   2089 	/* TODO */
   2090 	return true;
   2091 }
   2092 
   2093 /*
   2094  * It seems that sending more than about 42 channels in a frame's Channel
   2095  * List attribute will baffle some devices enough that they will ignore
   2096  * the frame.
   2097  */
   2098 #define MAX_CHANNELS 40
   2099 
   2100 static void p2p_add_freq_func(uint32_t freq, void *user_data)
   2101 {
   2102 	struct p2p_channel_entries *channel_entry = user_data;
   2103 	uint8_t channel;
   2104 	enum band_freq band;
   2105 
   2106 	if (channel_entry->n_channels >= MAX_CHANNELS)
   2107 		return;
   2108 
   2109 	channel = band_freq_to_channel(freq, &band);
   2110 
   2111 	if (band != band_oper_class_to_band((const uint8_t *) "XX\x4",
   2112 						channel_entry->oper_class))
   2113 		return;
   2114 
   2115 	channel_entry->channels[channel_entry->n_channels++] = channel;
   2116 }
   2117 
   2118 static void p2p_device_fill_channel_list(struct p2p_device *dev,
   2119 					struct p2p_channel_list_attr *attr)
   2120 {
   2121 	struct p2p_channel_entries *channel_entry;
   2122 	unsigned int total_channels;
   2123 
   2124 	memcpy(attr->country, dev->listen_country, 3);
   2125 	attr->channel_entries = l_queue_new();
   2126 
   2127 	channel_entry = l_malloc(sizeof(struct p2p_channel_entries) +
   2128 					MAX_CHANNELS);
   2129 	channel_entry->oper_class = 81;
   2130 	channel_entry->n_channels = 0;
   2131 	scan_freq_set_foreach(wiphy_get_supported_freqs(dev->wiphy),
   2132 				p2p_add_freq_func, channel_entry);
   2133 	l_queue_push_tail(attr->channel_entries, channel_entry);
   2134 	total_channels = channel_entry->n_channels;
   2135 
   2136 	if (total_channels >= MAX_CHANNELS)
   2137 		return;
   2138 
   2139 	channel_entry = l_malloc(sizeof(struct p2p_channel_entries) +
   2140 					MAX_CHANNELS);
   2141 	channel_entry->oper_class = 115;
   2142 	channel_entry->n_channels = 0;
   2143 	scan_freq_set_foreach(wiphy_get_supported_freqs(dev->wiphy),
   2144 				p2p_add_freq_func, channel_entry);
   2145 
   2146 	if (total_channels + channel_entry->n_channels > MAX_CHANNELS)
   2147 		channel_entry->n_channels = MAX_CHANNELS - total_channels;
   2148 
   2149 	l_queue_push_tail(attr->channel_entries, channel_entry);
   2150 }
   2151 
   2152 static bool p2p_go_negotiation_confirm_cb(const struct mmpdu_header *mpdu,
   2153 					const void *body, size_t body_len,
   2154 					int rssi, struct p2p_device *dev)
   2155 {
   2156 	struct p2p_go_negotiation_confirmation info;
   2157 	int r;
   2158 
   2159 	l_debug("");
   2160 
   2161 	if (body_len < 8) {
   2162 		l_error("GO Negotiation Confirmation frame too short");
   2163 		p2p_connect_failed(dev);
   2164 		return true;
   2165 	}
   2166 
   2167 	r = p2p_parse_go_negotiation_confirmation(body + 7, body_len - 7,
   2168 							&info);
   2169 	if (r < 0) {
   2170 		l_error("GO Negotiation Confirmation parse error %s (%i)",
   2171 			strerror(-r), -r);
   2172 		p2p_connect_failed(dev);
   2173 		return true;
   2174 	}
   2175 
   2176 	if (info.dialog_token != dev->conn_go_dialog_token) {
   2177 		l_error("GO Negotiation Response dialog token doesn't match");
   2178 		p2p_connect_failed(dev);
   2179 		goto cleanup;
   2180 	}
   2181 
   2182 	if (info.status != P2P_STATUS_SUCCESS) {
   2183 		l_error("GO Negotiation Confirmation status %i", info.status);
   2184 		p2p_connect_failed(dev);
   2185 		goto cleanup;
   2186 	}
   2187 
   2188 	/* Check whether WFD IE is required, validate it if present */
   2189 	if (!p2p_device_validate_conn_wfd(dev, info.wfd, info.wfd_size)) {
   2190 		p2p_connect_failed(dev);
   2191 		goto cleanup;
   2192 	}
   2193 
   2194 	/*
   2195 	 * In both scenarios the Channel List is a subset of what we previously
   2196 	 * sent in the GO Negotiation Response and must contain the Operating
   2197 	 * Channel.
   2198 	 */
   2199 	if (!p2p_device_validate_channel_list(dev, &info.channel_list,
   2200 						&info.operating_channel)) {
   2201 		p2p_connect_failed(dev);
   2202 		goto cleanup;
   2203 	}
   2204 
   2205 	/*
   2206 	 * Not validating .capability.group_caps, it's either reserved
   2207 	 * (dev->is_go) or has to be identical to that in the GO Negotiation
   2208 	 * Request (!dev->is_go).
   2209 	 */
   2210 
   2211 	if (dev->is_go) {
   2212 		if (memcmp(info.operating_channel.country,
   2213 				dev->listen_country, 3) ||
   2214 				info.operating_channel.oper_class !=
   2215 				dev->listen_oper_class ||
   2216 				info.operating_channel.channel_num !=
   2217 				dev->listen_channel) {
   2218 			l_error("Bad operating channel in GO Negotiation "
   2219 				"Confirmation");
   2220 			p2p_connect_failed(dev);
   2221 			goto cleanup;
   2222 		}
   2223 
   2224 		/*
   2225 		 * Start setting the group up right away and we'll add the
   2226 		 * client's Configuration Timeout to the WSC start timeout's
   2227 		 * value.
   2228 		 */
   2229 		p2p_device_interface_create(dev);
   2230 	} else {
   2231 		enum band_freq band = band_oper_class_to_band(
   2232 			(const uint8_t *) info.operating_channel.country,
   2233 			info.operating_channel.oper_class);
   2234 		uint32_t frequency = band_channel_to_freq(
   2235 					info.operating_channel.channel_num,
   2236 					band);
   2237 
   2238 		if (!frequency) {
   2239 			l_error("Bad operating channel in GO Negotiation "
   2240 				"Confirmation");
   2241 			p2p_connect_failed(dev);
   2242 			goto cleanup;
   2243 		}
   2244 
   2245 		dev->conn_go_oper_freq = frequency;
   2246 		memcpy(&dev->go_group_id, &info.group_id,
   2247 			sizeof(struct p2p_group_id_attr));
   2248 
   2249 		/*
   2250 		 * Confirmation received.  For simplicity wait idly the maximum
   2251 		 * amount of time indicated by the peer in the GO Negotiation
   2252 		 * Request's Configuration Timeout attribute and start the
   2253 		 * provisioning phase.
   2254 		 */
   2255 		dev->conn_peer_config_timeout = l_timeout_create_ms(
   2256 						dev->conn_config_delay,
   2257 						p2p_config_timeout, dev,
   2258 						p2p_config_timeout_destroy);
   2259 	}
   2260 
   2261 cleanup:
   2262 	p2p_clear_go_negotiation_confirmation(&info);
   2263 	return true;
   2264 }
   2265 
   2266 static void p2p_set_group_id(struct p2p_device *dev)
   2267 {
   2268 	const char *name = dev->device_info.device_name;
   2269 	char buf[2];
   2270 
   2271 	/* SSID format following section 3.2.1 */
   2272 	p2p_get_random_string(buf, 2);
   2273 	snprintf(dev->go_group_id.ssid, sizeof(dev->go_group_id.ssid),
   2274 			"DIRECT-%c%c-%.22s", buf[0], buf[1], name);
   2275 	memcpy(dev->go_group_id.device_addr, dev->addr, 6);
   2276 }
   2277 
   2278 static void p2p_device_go_negotiation_req_cb(const struct mmpdu_header *mpdu,
   2279 						const void *body,
   2280 						size_t body_len, int rssi,
   2281 						void *user_data)
   2282 {
   2283 	struct p2p_device *dev = user_data;
   2284 	struct p2p_go_negotiation_req req_info;
   2285 	struct p2p_go_negotiation_resp resp_info = {};
   2286 	int r;
   2287 	uint8_t *resp_body;
   2288 	size_t resp_len;
   2289 	uint8_t wfd_ie[32];
   2290 	struct iovec iov[16];
   2291 	int iov_len = 0;
   2292 	struct p2p_peer *peer;
   2293 	enum p2p_attr_status_code status = P2P_STATUS_SUCCESS;
   2294 
   2295 	l_debug("");
   2296 
   2297 	/*
   2298 	 * Check the Destination Address and the BSSID. Section 2.4.3:
   2299 	 * "When communication is not within a P2P Group, e.g. during
   2300 	 * [...] GO Negotiation [...], a P2P Device shall use the
   2301 	 * P2P Device Address of the intended destination as the BSSID in
   2302 	 * Request, or Confirmation frames and its own P2P Device Address
   2303 	 * as the BSSID in Response frames."
   2304 	 *
   2305 	 * Some drivers (brcmfmac) will report the BSSID as all zeros and
   2306 	 * some Wi-Fi Display dongles will pass their own address as the
   2307 	 * BSSID in the GO Negotiation Request so allow all three possible
   2308 	 * values.
   2309 	 */
   2310 	if (memcmp(mpdu->address_1, dev->addr, 6) ||
   2311 			(memcmp(mpdu->address_3, dev->addr, 6) &&
   2312 			 memcmp(mpdu->address_3, mpdu->address_2, 6) &&
   2313 			 !l_memeqzero(mpdu->address_3, 6)))
   2314 		return;
   2315 
   2316 	peer = l_queue_find(dev->peer_list, p2p_peer_match, mpdu->address_2);
   2317 	if (!peer)
   2318 		return;
   2319 
   2320 	if (!dev->conn_peer)
   2321 		return;
   2322 
   2323 	if (body_len < 8)
   2324 		return;
   2325 
   2326 	if (!dev->conn_go_neg_req_timeout || peer != dev->conn_peer) {
   2327 		status = P2P_STATUS_FAIL_INFO_NOT_AVAIL;
   2328 		goto respond;
   2329 	}
   2330 
   2331 	if (memcmp(mpdu->address_2, dev->conn_peer->bss->addr, 6)) {
   2332 		status = P2P_STATUS_FAIL_UNABLE_TO_ACCOMMODATE_REQUEST;
   2333 		goto respond;
   2334 	}
   2335 
   2336 	r = p2p_parse_go_negotiation_req(body + 7, body_len - 7, &req_info);
   2337 	if (r < 0) {
   2338 		l_error("GO Negotiation Request parse error %s (%i)",
   2339 			strerror(-r), -r);
   2340 		p2p_connect_failed(dev);
   2341 		status = P2P_STATUS_FAIL_INVALID_PARAMS;
   2342 		goto respond;
   2343 	}
   2344 
   2345 	dev->conn_go_tie_breaker = !req_info.go_tie_breaker;
   2346 	dev->is_go = P2P_GO_INTENT * 2 + dev->conn_go_tie_breaker >
   2347 		req_info.go_intent * 2;
   2348 
   2349 	if ((req_info.capability.group_caps & P2P_GROUP_CAP_PERSISTENT_GROUP) &&
   2350 			!dev->is_go) {
   2351 		if (peer->wsc.pending_connect) {
   2352 			struct l_dbus_message *reply =
   2353 				dbus_error_not_supported(
   2354 						peer->wsc.pending_connect);
   2355 
   2356 			dbus_pending_reply(&peer->wsc.pending_connect, reply);
   2357 		}
   2358 
   2359 		p2p_connect_failed(dev);
   2360 		l_error("Persistent groups not supported");
   2361 		status = P2P_STATUS_FAIL_INCOMPATIBLE_PARAMS;
   2362 		goto p2p_free;
   2363 	}
   2364 
   2365 	if (req_info.device_password_id != dev->conn_password_id) {
   2366 		p2p_connect_failed(dev);
   2367 		l_error("Incompatible Password ID in the GO Negotiation Req");
   2368 		status = P2P_STATUS_FAIL_INCOMPATIBLE_PROVISIONING;
   2369 		goto p2p_free;
   2370 	}
   2371 
   2372 	if (!p2p_device_validate_channel_list(dev, &req_info.channel_list,
   2373 						&req_info.operating_channel)) {
   2374 		p2p_connect_failed(dev);
   2375 		status = P2P_STATUS_FAIL_INCOMPATIBLE_PARAMS;
   2376 		goto p2p_free;
   2377 	}
   2378 
   2379 	if (dev->is_go) {
   2380 		const struct l_queue_entry *entry;
   2381 		const struct p2p_channel_entries *entries;
   2382 		int i;
   2383 
   2384 		/*
   2385 		 * Section 3.1.4.2.1: "The Channel List attribute shall
   2386 		 * indicate the channels that the P2P Device can support as
   2387 		 * Operating Channel of the P2P Group if it becomes P2P Group
   2388 		 * Owner."
   2389 		 * Section 3.1.4.2.2: "The channels indicated in the Channel
   2390 		 * List shall only include channels from the Channel List
   2391 		 * attribute in the GO Negotiation Request frame. [...]
   2392 		 * The channel indicated in the Operating Channel attribute
   2393 		 * shall be one of the channels in the Channel List attribute
   2394 		 * in the GO Negotiation Response frame."
   2395 		 *
   2396 		 * Since the sender is not becoming the GO this shouldn't
   2397 		 * affect us but following 3.1.4.2.2 our operating channel
   2398 		 * should be one of those listed in the GO Negotiation
   2399 		 * Response which in turn are the subset of those in the
   2400 		 * Request.  So effectively the list in the Request limits
   2401 		 * the peer's set of supported operating channels both as the
   2402 		 * GO and the Client.  Check that our listen channel is in
   2403 		 * that set.
   2404 		 * TODO: if it's not, look for a different channel.
   2405 		 */
   2406 		for (entry = l_queue_get_entries(
   2407 					req_info.channel_list.channel_entries);
   2408 				entry; entry = entry->next) {
   2409 			entries = entry->data;
   2410 
   2411 			if (entries->oper_class == dev->listen_oper_class)
   2412 				break;
   2413 		}
   2414 
   2415 		if (!entry) {
   2416 			l_error("Our Operating Class not listed in "
   2417 				"the GO Negotiation Request");
   2418 			p2p_connect_failed(dev);
   2419 			status = P2P_STATUS_FAIL_NO_COMMON_CHANNELS;
   2420 			goto p2p_free;
   2421 		}
   2422 
   2423 		for (i = 0; i < entries->n_channels; i++)
   2424 			if (entries->channels[i] == dev->listen_channel)
   2425 				break;
   2426 
   2427 		if (i == entries->n_channels) {
   2428 			l_error("Our listen channel not listed in "
   2429 				"the GO Negotiation Request");
   2430 			p2p_connect_failed(dev);
   2431 			status = P2P_STATUS_FAIL_NO_COMMON_CHANNELS;
   2432 			goto p2p_free;
   2433 		}
   2434 	}
   2435 
   2436 	/* Check whether WFD IE is required, validate it if present */
   2437 	if (!p2p_device_validate_conn_wfd(dev, req_info.wfd,
   2438 						req_info.wfd_size)) {
   2439 		p2p_connect_failed(dev);
   2440 		status = P2P_STATUS_FAIL_INCOMPATIBLE_PARAMS;
   2441 		goto p2p_free;
   2442 	}
   2443 
   2444 	l_timeout_remove(dev->conn_go_neg_req_timeout);
   2445 	p2p_device_discovery_stop(dev);
   2446 
   2447 	dev->conn_go_dialog_token = req_info.dialog_token;
   2448 	memcpy(dev->conn_peer_interface_addr, req_info.intended_interface_addr,
   2449 		6);
   2450 
   2451 	if (dev->is_go) {
   2452 		p2p_set_group_id(dev);
   2453 
   2454 		dev->conn_config_delay =
   2455 			req_info.config_timeout.client_config_timeout * 10;
   2456 	} else {
   2457 		dev->conn_config_delay =
   2458 			req_info.config_timeout.go_config_timeout * 10;
   2459 	}
   2460 
   2461 p2p_free:
   2462 	dev->conn_go_tie_breaker = !req_info.go_tie_breaker;
   2463 	p2p_clear_go_negotiation_req(&req_info);
   2464 
   2465 respond:
   2466 	/* Build and send the GO Negotiation Response */
   2467 	resp_info.dialog_token = dev->conn_go_dialog_token;
   2468 	resp_info.status = status;
   2469 
   2470 	if (dev->is_go && dev->conn_peer) {
   2471 		struct l_queue *channel_list = l_queue_new();
   2472 		struct p2p_channel_entries *channel_entries =
   2473 			l_malloc(sizeof(struct p2p_channel_entries) + 1);
   2474 
   2475 		resp_info.capability = dev->capability;
   2476 		memcpy(resp_info.operating_channel.country,
   2477 			dev->listen_country, 3);
   2478 		resp_info.operating_channel.oper_class = dev->listen_oper_class;
   2479 		resp_info.operating_channel.channel_num = dev->listen_channel;
   2480 		memcpy(&resp_info.group_id, &dev->go_group_id,
   2481 			sizeof(struct p2p_group_id_attr));
   2482 
   2483 		channel_entries->oper_class = dev->listen_oper_class;
   2484 		channel_entries->n_channels = 1;
   2485 		channel_entries->channels[0] = dev->listen_channel;
   2486 		l_queue_push_tail(channel_list, channel_entries);
   2487 
   2488 		memcpy(resp_info.channel_list.country, dev->listen_country, 3);
   2489 		resp_info.channel_list.channel_entries = channel_list;
   2490 	} else {
   2491 		resp_info.capability.device_caps = dev->capability.device_caps;
   2492 		resp_info.capability.group_caps = 0;	/* Reserved */
   2493 		p2p_device_fill_channel_list(dev, &resp_info.channel_list);
   2494 	}
   2495 
   2496 	resp_info.go_intent = P2P_GO_INTENT;
   2497 	resp_info.go_tie_breaker = dev->conn_go_tie_breaker;
   2498 	resp_info.config_timeout.go_config_timeout = 50;	/* 500ms */
   2499 	resp_info.config_timeout.client_config_timeout = 50;	/* 500ms */
   2500 
   2501 	if (dev->conn_peer)
   2502 		memcpy(resp_info.intended_interface_addr, dev->conn_addr, 6);
   2503 
   2504 	resp_info.device_info = dev->device_info;
   2505 	resp_info.device_info.wsc_config_methods = dev->conn_config_method;
   2506 	resp_info.device_password_id = dev->conn_password_id;
   2507 
   2508 	if (dev->conn_own_wfd) {
   2509 		resp_info.wfd = wfd_ie;
   2510 		resp_info.wfd_size = p2p_build_wfd_ie(dev->conn_own_wfd,
   2511 							NULL, wfd_ie);
   2512 	}
   2513 
   2514 	resp_body = p2p_build_go_negotiation_resp(&resp_info, &resp_len);
   2515 	resp_info.wfd = NULL;
   2516 	p2p_clear_go_negotiation_resp(&resp_info);
   2517 
   2518 	if (!resp_body) {
   2519 		p2p_connect_failed(dev);
   2520 		return;
   2521 	}
   2522 
   2523 	iov[iov_len].iov_base = resp_body;
   2524 	iov[iov_len].iov_len = resp_len;
   2525 	iov_len++;
   2526 
   2527 	iov[iov_len].iov_base = NULL;
   2528 
   2529 	if (status == P2P_STATUS_SUCCESS)
   2530 		p2p_peer_frame_xchg(peer, iov, dev->addr, 0, 600, 0, true,
   2531 					FRAME_GROUP_P2P_CONNECT,
   2532 					p2p_go_negotiation_resp_done,
   2533 					&p2p_frame_go_neg_confirm,
   2534 					p2p_go_negotiation_confirm_cb, NULL);
   2535 	else
   2536 		p2p_peer_frame_xchg(peer, iov, dev->addr, 0, 0, 0, true,
   2537 					FRAME_GROUP_P2P_CONNECT,
   2538 					p2p_go_negotiation_resp_err_done, NULL);
   2539 
   2540 	l_debug("GO Negotiation Response sent with status %i", status);
   2541 	l_free(resp_body);
   2542 }
   2543 
   2544 static void p2p_go_negotiation_confirm_done(int error, void *user_data)
   2545 {
   2546 	struct p2p_device *dev = user_data;
   2547 
   2548 	if (error) {
   2549 		/* TODO: we should probably ignore the missing ACK error */
   2550 		l_error("Sending the GO Negotiation Confirm failed: %s (%i)",
   2551 			strerror(-error), -error);
   2552 		p2p_connect_failed(dev);
   2553 		return;
   2554 	}
   2555 
   2556 	/*
   2557 	 * Frame was ACKed.  On the GO start setting the group up right
   2558 	 * away and we'll add the client's Configuration Timeout to the
   2559 	 * WSC start timeout's value.  On the client wait idly the
   2560 	 * maximum amount of time indicated by the peer in the GO
   2561 	 * Negotiation Response's Configuration Timeout attribute and
   2562 	 * start the provisioning phase.
   2563 	 */
   2564 	if (dev->is_go) {
   2565 		p2p_device_interface_create(dev);
   2566 		return;
   2567 	}
   2568 
   2569 	dev->conn_peer_config_timeout = l_timeout_create_ms(
   2570 						dev->conn_config_delay,
   2571 						p2p_config_timeout, dev,
   2572 						p2p_config_timeout_destroy);
   2573 }
   2574 
   2575 static void p2p_go_neg_req_timeout_destroy(void *user_data)
   2576 {
   2577 	struct p2p_device *dev = user_data;
   2578 
   2579 	dev->conn_go_neg_req_timeout = NULL;
   2580 }
   2581 
   2582 static void p2p_go_neg_req_timeout(struct l_timeout *timeout, void *user_data)
   2583 {
   2584 	struct p2p_device *dev = user_data;
   2585 
   2586 	l_debug("");
   2587 
   2588 	p2p_connect_failed(dev);
   2589 }
   2590 
   2591 static bool p2p_go_negotiation_resp_cb(const struct mmpdu_header *mpdu,
   2592 					const void *body, size_t body_len,
   2593 					int rssi, struct p2p_device *dev)
   2594 {
   2595 	struct p2p_go_negotiation_resp resp_info;
   2596 	struct p2p_go_negotiation_confirmation confirm_info = {};
   2597 	uint8_t *confirm_body;
   2598 	size_t confirm_len;
   2599 	uint8_t wfd_ie[32];
   2600 	int r;
   2601 	struct iovec iov[16];
   2602 	int iov_len = 0;
   2603 	enum band_freq band;
   2604 	uint32_t frequency;
   2605 
   2606 	l_debug("");
   2607 
   2608 	if (!dev->conn_peer)
   2609 		return true;
   2610 
   2611 	if (body_len < 8) {
   2612 		l_error("GO Negotiation Response frame too short");
   2613 		p2p_connect_failed(dev);
   2614 		return true;
   2615 	}
   2616 
   2617 	r = p2p_parse_go_negotiation_resp(body + 7, body_len - 7, &resp_info);
   2618 	if (r < 0) {
   2619 		l_error("GO Negotiation Response parse error %s (%i)",
   2620 			strerror(-r), -r);
   2621 		p2p_connect_failed(dev);
   2622 		return true;
   2623 	}
   2624 
   2625 	if (resp_info.dialog_token != 1) {
   2626 		l_error("GO Negotiation Response dialog token doesn't match");
   2627 		p2p_connect_failed(dev);
   2628 		goto p2p_free;
   2629 	}
   2630 
   2631 	if (resp_info.status != P2P_STATUS_SUCCESS) {
   2632 		if (resp_info.status == P2P_STATUS_FAIL_INFO_NOT_AVAIL) {
   2633 			/* Give the peer 120s to restart the GO Negotiation */
   2634 			l_error("P2P_STATUS_FAIL_INFO_NOT_AVAIL: Will wait for "
   2635 				"a new GO Negotiation Request before declaring "
   2636 				"failure");
   2637 			dev->conn_go_neg_req_timeout = l_timeout_create(120,
   2638 						p2p_go_neg_req_timeout, dev,
   2639 						p2p_go_neg_req_timeout_destroy);
   2640 			p2p_device_discovery_start(dev);
   2641 			goto p2p_free;
   2642 		}
   2643 
   2644 		l_error("GO Negotiation Response status %i", resp_info.status);
   2645 		p2p_connect_failed(dev);
   2646 		goto p2p_free;
   2647 	}
   2648 
   2649 	/*
   2650 	 * 3.1.4.2: "The Tie breaker bit in a GO Negotiation Response frame
   2651 	 * shall be toggled from the corresponding GO Negotiation Request
   2652 	 * frame."
   2653 	 */
   2654 	if (resp_info.go_tie_breaker == dev->conn_go_tie_breaker) {
   2655 		l_error("GO Negotiation Response tie breaker value wrong");
   2656 		/* Proceed anyway */
   2657 		dev->conn_go_tie_breaker = !resp_info.go_tie_breaker;
   2658 	}
   2659 
   2660 	dev->is_go = P2P_GO_INTENT * 2 + dev->conn_go_tie_breaker >
   2661 		resp_info.go_intent * 2;
   2662 
   2663 	if ((resp_info.capability.group_caps & P2P_GROUP_CAP_PERSISTENT_GROUP)
   2664 			&& !dev->is_go) {
   2665 		l_error("Persistent groups not supported");
   2666 		p2p_connect_failed(dev);
   2667 		goto p2p_free;
   2668 	}
   2669 
   2670 	if (resp_info.device_password_id != dev->conn_password_id) {
   2671 		l_error("GO Negotiation Response WSC device password ID wrong");
   2672 		p2p_connect_failed(dev);
   2673 		goto p2p_free;
   2674 	}
   2675 
   2676 	if (!p2p_device_validate_channel_list(dev, &resp_info.channel_list,
   2677 						&resp_info.operating_channel)) {
   2678 		p2p_connect_failed(dev);
   2679 		goto p2p_free;
   2680 	}
   2681 
   2682 	if (dev->is_go) {
   2683 		const struct l_queue_entry *entry;
   2684 		const struct p2p_channel_entries *entries;
   2685 		int i;
   2686 
   2687 		/*
   2688 		 * Check that our listen channel is in the set supported by the
   2689 		 * Client.
   2690 		 * TODO: if it's not, look for a different channel.
   2691 		 */
   2692 		for (entry = l_queue_get_entries(
   2693 					resp_info.channel_list.channel_entries);
   2694 				entry; entry = entry->next) {
   2695 			entries = entry->data;
   2696 
   2697 			if (entries->oper_class == dev->listen_oper_class)
   2698 				break;
   2699 		}
   2700 
   2701 		if (!entry) {
   2702 			l_error("Our Operating Class not listed in "
   2703 				"the GO Negotiation Response");
   2704 			p2p_connect_failed(dev);
   2705 			goto p2p_free;
   2706 		}
   2707 
   2708 		for (i = 0; i < entries->n_channels; i++)
   2709 			if (entries->channels[i] == dev->listen_channel)
   2710 				break;
   2711 
   2712 		if (i == entries->n_channels) {
   2713 			l_error("Our listen channel not listed in "
   2714 				"the GO Negotiation Response");
   2715 			p2p_connect_failed(dev);
   2716 			goto p2p_free;
   2717 		}
   2718 	}
   2719 
   2720 	/* Check whether WFD IE is required, validate it if present */
   2721 	if (!p2p_device_validate_conn_wfd(dev, resp_info.wfd,
   2722 						resp_info.wfd_size)) {
   2723 		p2p_connect_failed(dev);
   2724 		goto p2p_free;
   2725 	}
   2726 
   2727 	memcpy(dev->conn_peer_interface_addr, resp_info.intended_interface_addr,
   2728 		6);
   2729 
   2730 	if (dev->is_go) {
   2731 		struct l_queue *channel_list = l_queue_new();
   2732 		struct p2p_channel_entries *channel_entries =
   2733 			l_malloc(sizeof(struct p2p_channel_entries) + 1);
   2734 
   2735 		p2p_set_group_id(dev);
   2736 
   2737 		dev->conn_config_delay =
   2738 			resp_info.config_timeout.client_config_timeout * 10;
   2739 
   2740 		channel_entries->oper_class = dev->listen_oper_class;
   2741 		channel_entries->n_channels = 1;
   2742 		channel_entries->channels[0] = dev->listen_channel;
   2743 		l_queue_push_tail(channel_list, channel_entries);
   2744 
   2745 		/* Build and send the GO Negotiation Confirmation */
   2746 		confirm_info.capability = dev->capability;
   2747 		memcpy(confirm_info.operating_channel.country,
   2748 			dev->listen_country, 3);
   2749 		confirm_info.operating_channel.oper_class = dev->listen_oper_class;
   2750 		confirm_info.operating_channel.channel_num = dev->listen_channel;
   2751 		memcpy(confirm_info.channel_list.country, dev->listen_country, 3);
   2752 		confirm_info.channel_list.channel_entries = channel_list;
   2753 		memcpy(&confirm_info.group_id, &dev->go_group_id,
   2754 			sizeof(struct p2p_group_id_attr));
   2755 	} else {
   2756 		band = band_oper_class_to_band(
   2757 			(const uint8_t *) resp_info.operating_channel.country,
   2758 			resp_info.operating_channel.oper_class);
   2759 		frequency = band_channel_to_freq(
   2760 					resp_info.operating_channel.channel_num,
   2761 					band);
   2762 		if (!frequency) {
   2763 			l_error("Bad operating channel in GO Negotiation Response");
   2764 			p2p_connect_failed(dev);
   2765 			goto p2p_free;
   2766 		}
   2767 
   2768 		dev->conn_config_delay =
   2769 			resp_info.config_timeout.go_config_timeout * 10;
   2770 		dev->conn_go_oper_freq = frequency;
   2771 		memcpy(&dev->go_group_id, &resp_info.group_id,
   2772 			sizeof(struct p2p_group_id_attr));
   2773 
   2774 		/* Build and send the GO Negotiation Confirmation */
   2775 		confirm_info.capability.device_caps = 0;	/* Reserved */
   2776 		confirm_info.capability.group_caps = 0;		/* Reserved */
   2777 		confirm_info.operating_channel = resp_info.operating_channel;
   2778 		confirm_info.channel_list = resp_info.channel_list;
   2779 		resp_info.channel_list.channel_entries = NULL;
   2780 	}
   2781 
   2782 	confirm_info.dialog_token = resp_info.dialog_token;
   2783 	confirm_info.status = P2P_STATUS_SUCCESS;
   2784 
   2785 	if (dev->conn_own_wfd) {
   2786 		confirm_info.wfd = wfd_ie;
   2787 		confirm_info.wfd_size = p2p_build_wfd_ie(dev->conn_own_wfd,
   2788 								NULL, wfd_ie);
   2789 	}
   2790 
   2791 	confirm_body = p2p_build_go_negotiation_confirmation(&confirm_info,
   2792 								&confirm_len);
   2793 	confirm_info.wfd = NULL;
   2794 	p2p_clear_go_negotiation_confirmation(&confirm_info);
   2795 
   2796 	if (!confirm_body) {
   2797 		p2p_connect_failed(dev);
   2798 		goto p2p_free;
   2799 	}
   2800 
   2801 	iov[iov_len].iov_base = confirm_body;
   2802 	iov[iov_len].iov_len = confirm_len;
   2803 	iov_len++;
   2804 
   2805 	iov[iov_len].iov_base = NULL;
   2806 
   2807 	p2p_peer_frame_xchg(dev->conn_peer, iov, dev->conn_peer->device_addr,
   2808 				0, 0, 0, false, FRAME_GROUP_P2P_CONNECT,
   2809 				p2p_go_negotiation_confirm_done, NULL);
   2810 	l_free(confirm_body);
   2811 
   2812 p2p_free:
   2813 	p2p_clear_go_negotiation_resp(&resp_info);
   2814 	return true;
   2815 }
   2816 
   2817 static void p2p_go_negotiation_req_done(int error, void *user_data)
   2818 {
   2819 	struct p2p_device *dev = user_data;
   2820 
   2821 	if (error)
   2822 		l_error("Sending the GO Negotiation Req failed: %s (%i)",
   2823 			strerror(-error), -error);
   2824 	else
   2825 		l_error("No GO Negotiation Response after Request ACKed");
   2826 
   2827 	p2p_connect_failed(dev);
   2828 }
   2829 
   2830 static void p2p_start_go_negotiation(struct p2p_device *dev)
   2831 {
   2832 	struct p2p_go_negotiation_req info = {};
   2833 	uint8_t *req_body;
   2834 	size_t req_len;
   2835 	uint8_t wfd_ie[32];
   2836 	struct iovec iov[16];
   2837 	int iov_len = 0;
   2838 	/*
   2839 	 * Devices should respond within 100ms but times of ~400ms are
   2840 	 * often seen instead.
   2841 	 *
   2842 	 * 3.1.4.2: "The P2P Device that sent the Group Owner Negotiation
   2843 	 * frame shall assume that Group Owner Negotiation failed and is
   2844 	 * complete if it does not receive the next frame in the exchange
   2845 	 * within 100 milliseconds of receiving an acknowledgement frame."
   2846 	 */
   2847 	unsigned int resp_timeout = 600;
   2848 
   2849 	dev->conn_go_tie_breaker = dev->next_tie_breaker++ & 1;
   2850 
   2851 	info.dialog_token = 1;
   2852 	info.capability = dev->capability;
   2853 	info.go_intent = P2P_GO_INTENT;
   2854 	info.go_tie_breaker = dev->conn_go_tie_breaker;
   2855 	info.config_timeout.go_config_timeout = 50;	/* 500ms */
   2856 	info.config_timeout.client_config_timeout = 50;	/* 500ms */
   2857 	memcpy(info.listen_channel.country, dev->listen_country, 3);
   2858 	info.listen_channel.oper_class = dev->listen_oper_class;
   2859 	info.listen_channel.channel_num = dev->listen_channel;
   2860 	memcpy(info.intended_interface_addr, dev->conn_addr, 6);
   2861 
   2862 	/*
   2863 	 * Even if P2P_GO_INTENT is 0, we have to include our supported
   2864 	 * channels because the peer can only choose their own channels
   2865 	 * from our list.
   2866 	 */
   2867 	p2p_device_fill_channel_list(dev, &info.channel_list);
   2868 	memcpy(info.operating_channel.country, dev->listen_country, 3);
   2869 	info.operating_channel.oper_class = dev->listen_oper_class;
   2870 	info.operating_channel.channel_num = dev->listen_channel;
   2871 	info.device_info = dev->device_info;
   2872 	info.device_password_id = dev->conn_password_id;
   2873 
   2874 	if (dev->conn_own_wfd) {
   2875 		info.wfd = wfd_ie;
   2876 		info.wfd_size = p2p_build_wfd_ie(dev->conn_own_wfd,
   2877 							NULL, wfd_ie);
   2878 	}
   2879 
   2880 	req_body = p2p_build_go_negotiation_req(&info, &req_len);
   2881 	info.wfd = NULL;
   2882 	p2p_clear_go_negotiation_req(&info);
   2883 
   2884 	if (!req_body) {
   2885 		p2p_connect_failed(dev);
   2886 		return;
   2887 	}
   2888 
   2889 	iov[iov_len].iov_base = req_body;
   2890 	iov[iov_len].iov_len = req_len;
   2891 	iov_len++;
   2892 
   2893 	iov[iov_len].iov_base = NULL;
   2894 
   2895 	p2p_peer_frame_xchg(dev->conn_peer, iov, dev->conn_peer->device_addr,
   2896 				100, resp_timeout, 256, false,
   2897 				FRAME_GROUP_P2P_CONNECT,
   2898 				p2p_go_negotiation_req_done,
   2899 				&p2p_frame_go_neg_resp,
   2900 				p2p_go_negotiation_resp_cb, NULL);
   2901 	l_free(req_body);
   2902 }
   2903 
   2904 static bool p2p_provision_disc_resp_cb(const struct mmpdu_header *mpdu,
   2905 					const void *body, size_t body_len,
   2906 					int rssi, struct p2p_device *dev)
   2907 {
   2908 	struct p2p_provision_discovery_resp info;
   2909 	int r;
   2910 
   2911 	l_debug("");
   2912 
   2913 	if (!dev->conn_peer)
   2914 		return true;
   2915 
   2916 	if (body_len < 8) {
   2917 		l_error("Provision Discovery Response frame too short");
   2918 		p2p_connect_failed(dev);
   2919 		return true;
   2920 	}
   2921 
   2922 	r = p2p_parse_provision_disc_resp(body + 7, body_len - 7, &info);
   2923 	if (r < 0) {
   2924 		l_error("Provision Discovery Response parse error %s (%i)",
   2925 			strerror(-r), -r);
   2926 		p2p_connect_failed(dev);
   2927 		return true;
   2928 	}
   2929 
   2930 	if (info.dialog_token != 2) {
   2931 		l_error("Provision Discovery Response dialog token doesn't "
   2932 			"match");
   2933 		p2p_connect_failed(dev);
   2934 		return true;
   2935 	}
   2936 
   2937 	if (info.wsc_config_method != dev->conn_config_method) {
   2938 		l_error("Provision Discovery Response WSC device password ID "
   2939 			"wrong");
   2940 		p2p_connect_failed(dev);
   2941 		return true;
   2942 	}
   2943 
   2944 	/* Check whether WFD IE is required, validate it if present */
   2945 	if (!p2p_device_validate_conn_wfd(dev, info.wfd, info.wfd_size)) {
   2946 		p2p_connect_failed(dev);
   2947 		return true;
   2948 	}
   2949 
   2950 	/*
   2951 	 * If we're not joining an existing group, continue with Group
   2952 	 * Formation now.
   2953 	 */
   2954 	if (!dev->conn_peer->group) {
   2955 		p2p_start_go_negotiation(dev);
   2956 		return true;
   2957 	}
   2958 
   2959 	/*
   2960 	 * Intended P2P Interface address is optional, we don't have the
   2961 	 * BSSID of the group here.
   2962 	 *
   2963 	 * We might want to make sure that Group Formation is false but the
   2964 	 * Capability attribute is also optional.
   2965 	 */
   2966 	dev->conn_go_oper_freq = dev->conn_peer->bss->frequency;
   2967 	memset(dev->conn_peer_interface_addr, 0, 6);
   2968 	memcpy(dev->go_group_id.device_addr, dev->conn_peer->device_addr, 6);
   2969 	l_strlcpy(dev->go_group_id.ssid,
   2970 			(const char *) dev->conn_peer->bss->ssid,
   2971 			dev->conn_peer->bss->ssid_len + 1);
   2972 
   2973 	/* Ready to start WSC */
   2974 	p2p_start_client_provision(dev);
   2975 	return true;
   2976 }
   2977 
   2978 static void p2p_provision_disc_req_done(int error, void *user_data)
   2979 {
   2980 	struct p2p_device *dev = user_data;
   2981 
   2982 	if (error)
   2983 		l_error("Sending the Provision Discovery Req failed: %s (%i)",
   2984 			strerror(-error), -error);
   2985 	else
   2986 		l_error("No Provision Discovery Response after Request ACKed");
   2987 
   2988 	p2p_connect_failed(dev);
   2989 }
   2990 
   2991 static void p2p_start_provision_discovery(struct p2p_device *dev)
   2992 {
   2993 	struct p2p_provision_discovery_req info = { .status = -1 };
   2994 	uint8_t *req_body;
   2995 	size_t req_len;
   2996 	uint8_t wfd_ie[32];
   2997 	struct iovec iov[16];
   2998 	int iov_len = 0;
   2999 
   3000 	/* This frame is pretty simple when P2Ps isn't supported */
   3001 	info.dialog_token = 2;
   3002 	info.capability = dev->capability;
   3003 	info.device_info = dev->device_info;
   3004 
   3005 	if (dev->conn_peer->group) {
   3006 		memcpy(info.group_id.device_addr, dev->conn_peer->bss->addr, 6);
   3007 		memcpy(info.group_id.ssid, dev->conn_peer->bss->ssid,
   3008 			dev->conn_peer->bss->ssid_len);
   3009 	}
   3010 
   3011 	info.wsc_config_method = dev->conn_config_method;
   3012 
   3013 	if (dev->conn_own_wfd) {
   3014 		info.wfd = wfd_ie;
   3015 		info.wfd_size = p2p_build_wfd_ie(dev->conn_own_wfd,
   3016 							NULL, wfd_ie);
   3017 	}
   3018 
   3019 	req_body = p2p_build_provision_disc_req(&info, &req_len);
   3020 	info.wfd = NULL;
   3021 	p2p_clear_provision_disc_req(&info);
   3022 
   3023 	if (!req_body) {
   3024 		p2p_connect_failed(dev);
   3025 		return;
   3026 	}
   3027 
   3028 	iov[iov_len].iov_base = req_body;
   3029 	iov[iov_len].iov_len = req_len;
   3030 	iov_len++;
   3031 
   3032 	iov[iov_len].iov_base = NULL;
   3033 
   3034 	/*
   3035 	 * Section 3.2.3: "The Provision Discovery Request frame shall be
   3036 	 * sent to the P2P Device Address of the P2P Group Owner"
   3037 	 */
   3038 	p2p_peer_frame_xchg(dev->conn_peer, iov, dev->conn_peer->device_addr,
   3039 				200, 600, 8, false, FRAME_GROUP_P2P_CONNECT,
   3040 				p2p_provision_disc_req_done,
   3041 				&p2p_frame_pd_resp, p2p_provision_disc_resp_cb,
   3042 				NULL);
   3043 	l_free(req_body);
   3044 }
   3045 
   3046 static bool p2p_peer_get_info(struct p2p_peer *peer,
   3047 				uint16_t *wsc_config_methods,
   3048 				struct p2p_capability_attr **capability)
   3049 {
   3050 	struct wsc_probe_request wsc_info;
   3051 
   3052 	switch (peer->bss->source_frame) {
   3053 	case SCAN_BSS_PROBE_RESP:
   3054 		if (!peer->bss->p2p_probe_resp_info)
   3055 			return false;
   3056 
   3057 		if (wsc_config_methods)
   3058 			*wsc_config_methods = peer->bss->p2p_probe_resp_info->
   3059 				device_info.wsc_config_methods;
   3060 
   3061 		*capability = &peer->bss->p2p_probe_resp_info->capability;
   3062 		return true;
   3063 	case SCAN_BSS_PROBE_REQ:
   3064 		if (!peer->bss->p2p_probe_req_info || !peer->bss->wsc)
   3065 			return false;
   3066 
   3067 		if (wsc_parse_probe_request(peer->bss->wsc, peer->bss->wsc_size,
   3068 						&wsc_info) < 0)
   3069 			return false;
   3070 
   3071 		if (wsc_config_methods)
   3072 			*wsc_config_methods = wsc_info.config_methods;
   3073 
   3074 		*capability = &peer->bss->p2p_probe_req_info->capability;
   3075 		return true;
   3076 	case SCAN_BSS_BEACON:
   3077 		if (!peer->bss->p2p_beacon_info || !peer->bss->wsc)
   3078 			return false;
   3079 
   3080 		if (wsc_parse_probe_request(peer->bss->wsc, peer->bss->wsc_size,
   3081 						&wsc_info) < 0)
   3082 			return false;
   3083 
   3084 		if (wsc_config_methods)
   3085 			*wsc_config_methods = wsc_info.config_methods;
   3086 
   3087 		*capability = &peer->bss->p2p_beacon_info->capability;
   3088 		break;
   3089 	}
   3090 
   3091 	return false;
   3092 }
   3093 
   3094 static void p2p_peer_connect(struct p2p_peer *peer, const char *pin)
   3095 {
   3096 	struct p2p_device *dev = peer->dev;
   3097 	uint16_t wsc_config_methods;
   3098 	struct p2p_capability_attr *capability;
   3099 	struct l_dbus_message *message = peer->wsc.pending_connect;
   3100 	struct l_dbus_message *reply;
   3101 
   3102 	if (dev->conn_peer) {
   3103 		reply = dbus_error_busy(message);
   3104 		goto send_error;
   3105 	}
   3106 
   3107 	/*
   3108 	 * Step 1, check if the device indicates it supports our WSC method
   3109 	 * and check other flags to make sure a connection is possible.
   3110 	 */
   3111 	if (!p2p_peer_get_info(peer, &wsc_config_methods, &capability)) {
   3112 		reply = dbus_error_failed(message);
   3113 		goto send_error;
   3114 	}
   3115 
   3116 	dev->conn_config_method = pin ? WSC_CONFIGURATION_METHOD_KEYPAD :
   3117 		WSC_CONFIGURATION_METHOD_PUSH_BUTTON;
   3118 	dev->conn_password_id = pin ?
   3119 		(strlen(pin) == 4 || wsc_pin_is_checksum_valid(pin) ?
   3120 		 WSC_DEVICE_PASSWORD_ID_DEFAULT :
   3121 		 WSC_DEVICE_PASSWORD_ID_USER_SPECIFIED) :
   3122 		WSC_DEVICE_PASSWORD_ID_PUSH_BUTTON;
   3123 
   3124 	if (!(wsc_config_methods & dev->conn_config_method)) {
   3125 		reply = dbus_error_not_supported(message);
   3126 		goto send_error;
   3127 	}
   3128 
   3129 	if (capability->device_caps & P2P_DEVICE_CAP_DEVICE_LIMIT) {
   3130 		reply = dbus_error_not_supported(message);
   3131 		goto send_error;
   3132 	}
   3133 
   3134 	if (capability->group_caps & P2P_GROUP_CAP_GROUP_LIMIT) {
   3135 		reply = dbus_error_not_supported(message);
   3136 		goto send_error;
   3137 	}
   3138 
   3139 	if (capability->group_caps & P2P_GROUP_CAP_GROUP_FORMATION) {
   3140 		reply = dbus_error_busy(message);
   3141 		goto send_error;
   3142 	}
   3143 
   3144 	/*
   3145 	 * Check WFD role compatibility.  At least one of the devices
   3146 	 * (device A) must be non-dual-role and device B must implement the
   3147 	 * role that A does not.  peer->wfd and p2p_own_wfd have both been
   3148 	 * validated and we know each device implements at least one role.
   3149 	 */
   3150 	if (p2p_own_wfd && p2p_own_wfd->available && peer->wfd) {
   3151 		if (!(
   3152 				(!peer->wfd->source && p2p_own_wfd->source) ||
   3153 				(!peer->wfd->sink && p2p_own_wfd->sink) ||
   3154 				(!p2p_own_wfd->source && peer->wfd->source) ||
   3155 				(!p2p_own_wfd->sink && peer->wfd->sink))) {
   3156 			l_error("Incompatible WFD roles");
   3157 			reply = dbus_error_not_supported(message);
   3158 			goto send_error;
   3159 		}
   3160 	}
   3161 
   3162 	p2p_device_discovery_stop(dev);
   3163 
   3164 	/* Generate the interface address for our P2P-Client connection */
   3165 	wiphy_generate_random_address(dev->wiphy, dev->conn_addr);
   3166 
   3167 	dev->conn_peer = peer; /* No ref counting so just set the pointer */
   3168 	dev->conn_pin = l_strdup(pin);
   3169 	dev->connections_left--;
   3170 	l_dbus_property_changed(dbus_get_bus(), p2p_device_get_path(dev),
   3171 				IWD_P2P_INTERFACE, "AvailableConnections");
   3172 
   3173 	if (p2p_own_wfd && p2p_own_wfd->available && peer->wfd) {
   3174 		dev->conn_own_wfd = l_memdup(p2p_own_wfd, sizeof(*p2p_own_wfd));
   3175 
   3176 		/*
   3177 		 * From now on we'll appear as SESSION_NOT_AVAILABLE to other
   3178 		 * peers but as SESSION_AVAILABLE to conn_peer.
   3179 		 */
   3180 		p2p_own_wfd->available = false;
   3181 
   3182 		/* If peer is R1, fall back to R1 as well */
   3183 		dev->conn_own_wfd->r2 = p2p_own_wfd->r2 && peer->wfd->r2;
   3184 
   3185 		/*
   3186 		 * If we're a dual-role device, we have to select our role
   3187 		 * for this connection now.
   3188 		 */
   3189 		if (p2p_own_wfd->source && p2p_own_wfd->sink) {
   3190 			dev->conn_own_wfd->source = !peer->wfd->source;
   3191 			dev->conn_own_wfd->sink = !peer->wfd->sink;
   3192 		}
   3193 	}
   3194 
   3195 	/*
   3196 	 * Step 2, if peer is already a GO then send the Provision Discovery
   3197 	 * before doing WSC.  If it's not then do Provision Discovery
   3198 	 * optionally as seems to be required by some implementations, and
   3199 	 * start GO negotiation following that.
   3200 	 * TODO: Add a AlwaysUsePD config setting.
   3201 	 */
   3202 	if (dev->conn_peer->group)
   3203 		p2p_start_provision_discovery(dev);
   3204 	else
   3205 		p2p_start_go_negotiation(dev);
   3206 
   3207 	return;
   3208 
   3209 send_error:
   3210 	dbus_pending_reply(&peer->wsc.pending_connect, reply);
   3211 }
   3212 
   3213 static void p2p_peer_disconnect_cb(struct netdev *netdev, bool result,
   3214 					void *user_data)
   3215 {
   3216 	struct p2p_peer *peer = user_data;
   3217 	struct p2p_device *dev = peer->dev;
   3218 
   3219 	if (!peer->wsc.pending_cancel || !dev->disconnecting)
   3220 		return;
   3221 
   3222 	dbus_pending_reply(&peer->wsc.pending_cancel,
   3223 				l_dbus_message_new_method_return(
   3224 						peer->wsc.pending_cancel));
   3225 
   3226 	/* Independent of the result this will just drop the whole netdev */
   3227 	p2p_connection_reset(dev);
   3228 }
   3229 
   3230 static void p2p_peer_disconnect(struct p2p_peer *peer)
   3231 {
   3232 	struct p2p_device *dev = peer->dev;
   3233 	struct l_dbus_message *message = peer->wsc.pending_cancel;
   3234 	struct l_dbus_message *reply;
   3235 
   3236 	if (dev->conn_peer != peer) {
   3237 		reply = dbus_error_not_connected(message);
   3238 		goto send_reply;
   3239 	}
   3240 
   3241 	if (dev->disconnecting) {
   3242 		reply = dbus_error_busy(message);
   3243 		goto send_reply;
   3244 	}
   3245 
   3246 	if (peer->wsc.pending_connect)
   3247 		dbus_pending_reply(&peer->wsc.pending_connect,
   3248 				dbus_error_aborted(peer->wsc.pending_connect));
   3249 
   3250 	if (p2p_peer_operational(peer)) {
   3251 		l_dbus_property_changed(dbus_get_bus(), p2p_peer_get_path(peer),
   3252 					IWD_P2P_PEER_INTERFACE, "Connected");
   3253 		l_dbus_property_changed(dbus_get_bus(), p2p_peer_get_path(peer),
   3254 					IWD_P2P_PEER_INTERFACE,
   3255 					"ConnectedInterface");
   3256 		l_dbus_property_changed(dbus_get_bus(), p2p_peer_get_path(peer),
   3257 					IWD_P2P_PEER_INTERFACE,
   3258 					"ConnectedIP");
   3259 	}
   3260 
   3261 	dev->disconnecting = true;
   3262 
   3263 	if (dev->conn_enrollee) {
   3264 		wsc_enrollee_cancel(dev->conn_enrollee, true);
   3265 		return;
   3266 	}
   3267 
   3268 	if (dev->conn_netdev && dev->conn_retry_count) {
   3269 		/* Note: in theory we need to add the P2P IEs here too */
   3270 		if (netdev_disconnect(dev->conn_netdev, p2p_peer_disconnect_cb,
   3271 					peer) == 0)
   3272 			return;
   3273 
   3274 		l_error("netdev_disconnect failed");
   3275 	}
   3276 
   3277 	p2p_connection_reset(dev);
   3278 	reply = l_dbus_message_new_method_return(message);
   3279 
   3280 send_reply:
   3281 	dbus_pending_reply(&peer->wsc.pending_cancel, reply);
   3282 }
   3283 
   3284 #define SCAN_INTERVAL_MAX	3
   3285 #define SCAN_INTERVAL_STEP	1
   3286 #define CHANS_PER_SCAN_INITIAL	2
   3287 #define CHANS_PER_SCAN		2
   3288 
   3289 static bool p2p_device_scan_start(struct p2p_device *dev);
   3290 static void p2p_device_roc_start(struct p2p_device *dev);
   3291 
   3292 static void p2p_device_roc_timeout(struct l_timeout *timeout, void *user_data)
   3293 {
   3294 	struct p2p_device *dev = user_data;
   3295 
   3296 	l_timeout_remove(dev->scan_timeout);
   3297 
   3298 	if (time(NULL) < dev->next_scan_ts) {
   3299 		/*
   3300 		 * dev->scan_timeout destroy function will have been called
   3301 		 * by now so it won't overwrite the new timeout set by
   3302 		 * p2p_device_roc_start.
   3303 		 */
   3304 		p2p_device_roc_start(dev);
   3305 		return;
   3306 	}
   3307 
   3308 	p2p_device_scan_start(dev);
   3309 }
   3310 
   3311 static void p2p_device_roc_cancel(struct p2p_device *dev)
   3312 {
   3313 	struct l_genl_msg *msg;
   3314 
   3315 	if (!dev->have_roc_cookie)
   3316 		return;
   3317 
   3318 	l_debug("");
   3319 
   3320 	msg = l_genl_msg_new_sized(NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL, 32);
   3321 	l_genl_msg_append_attr(msg, NL80211_ATTR_WDEV, 8, &dev->wdev_id);
   3322 	l_genl_msg_append_attr(msg, NL80211_ATTR_COOKIE, 8, &dev->roc_cookie);
   3323 	l_genl_family_send(dev->nl80211, msg, NULL, NULL, NULL);
   3324 
   3325 	dev->have_roc_cookie = false;
   3326 }
   3327 
   3328 static void p2p_scan_timeout_destroy(void *user_data)
   3329 {
   3330 	struct p2p_device *dev = user_data;
   3331 
   3332 	dev->scan_timeout = NULL;
   3333 
   3334 	if (dev->nl80211) {
   3335 		/*
   3336 		 * Most likely when the timer expires the ROC period
   3337 		 * has finished but send a cancel command to make sure,
   3338 		 * as well as handle situations like disabling P2P.
   3339 		 */
   3340 		p2p_device_roc_cancel(dev);
   3341 	}
   3342 }
   3343 
   3344 static void p2p_device_roc_cb(struct l_genl_msg *msg, void *user_data)
   3345 {
   3346 	struct p2p_device *dev = user_data;
   3347 	uint64_t cookie;
   3348 	int error = l_genl_msg_get_error(msg);
   3349 
   3350 	l_debug("ROC: %s (%i)", strerror(-error), -error);
   3351 
   3352 	if (error)
   3353 		return;
   3354 
   3355 	if (nl80211_parse_attrs(msg, NL80211_ATTR_COOKIE, &cookie,
   3356 				NL80211_ATTR_UNSPEC) < 0)
   3357 		return;
   3358 
   3359 	dev->roc_cookie = cookie;
   3360 	dev->have_roc_cookie = true;
   3361 
   3362 	/*
   3363 	 * Has the command taken so long that P2P has been since disabled
   3364 	 * or the timeout otherwise ran out?
   3365 	 */
   3366 	if (!dev->scan_timeout)
   3367 		p2p_device_roc_cancel(dev);
   3368 }
   3369 
   3370 static void p2p_device_roc_start(struct p2p_device *dev)
   3371 {
   3372 	struct l_genl_msg *msg;
   3373 	uint32_t listen_freq;
   3374 	uint32_t duration;
   3375 	uint32_t cmd_id;
   3376 
   3377 	l_debug("");
   3378 
   3379 	/*
   3380 	 * One second granularity is fine here because some randomess
   3381 	 * is desired and the intervals don't have strictly defined
   3382 	 * limits.
   3383 	 */
   3384 	duration = (dev->next_scan_ts - time(NULL)) * 1000;
   3385 
   3386 	if (duration < 200)
   3387 		duration = 200;
   3388 
   3389 	/*
   3390 	 * Driver max duration seems to be 5000ms or more for all drivers
   3391 	 * except mac80211_hwsim where it is only 1000ms.
   3392 	 */
   3393 	if (duration > wiphy_get_max_roc_duration(dev->wiphy))
   3394 		duration = wiphy_get_max_roc_duration(dev->wiphy);
   3395 
   3396 	/*
   3397 	 * Some drivers seem to miss fewer frames if we start new requests
   3398 	 * often.
   3399 	 */
   3400 	if (duration > 1000)
   3401 		duration = 1000;
   3402 
   3403 	/*
   3404 	 * Be on our listen channel, even if we're still in the 120s
   3405 	 * waiting period after a locally-initiated GO Negotiation and
   3406 	 * waiting for the peer's GO Negotiation Request.  It's not
   3407 	 * totally clear that this is how the spec intended this
   3408 	 * mechanism to work.  On one hand 3.1.4.1 says this:
   3409 	 * "A P2P Device may start Group Owner Negotiation by sending a
   3410 	 * GO Negotiation Request frame after receiving a Probe Request
   3411 	 * frame from the target P2P Device."
   3412 	 * and the Appendix D. scenarios also show GO Negotiation happening
   3413 	 * on the initiator's listen channel directly after the reception
   3414 	 * of the Probe Request from the target.  But:
   3415 	 *  1. in 3.1.4.1 that is a MAY and doesn't exclude starting GO
   3416 	 *     Negotiation also on the target's listen channel.
   3417 	 *  2. not all devices use the search state so we may never
   3418 	 *     receive a Probe Request and may end up waiting indefinitely.
   3419 	 *  3. the time the peer spends on each channel in the scan state
   3420 	 *     may be too short for the peer to receive the GO Negotiation
   3421 	 *     Request after the Probe Request before moving to the next
   3422 	 *     channel.
   3423 	 *  4. since we know the target is going to spend some time on
   3424 	 *     their own listen channel, using that channel should work in
   3425 	 *     every case.
   3426 	 *
   3427 	 * We also have this in 3.1.4.1:
   3428 	 * "When the P2P Devices arrive on a common channel and begin Group
   3429 	 * Owner Negotiation, they shall stay on that channel until Group
   3430 	 * Owner Negotiation completes."
   3431 	 * telling us that the whole negotiation should be happening on
   3432 	 * one channel seemingly supporting the new GO Negotiation being on
   3433 	 * the same channel as the original failed GO Negotiation.
   3434 	 * However the rest of the spec makes it clear they are not treated
   3435 	 * as a single GO Negotiation:
   3436 	 * 3.1.4.2:
   3437 	 * "Group Owner Negotiation is a three way frame exchange"
   3438 	 * 3.1.4.2.2:
   3439 	 * "Group Formation ends on transmission or reception of a GO
   3440 	 * Negotiation Response frame with the Status Code set to a value
   3441 	 * other than Success."
   3442 	 *
   3443 	 * 3.1.4.1 implies frame exchanges happen on the target device's
   3444 	 * Listen Channel, not our Listen Channel:
   3445 	 * "Prior to beginning the Group Formation Procedure the P2P Device
   3446 	 * shall arrive on a common channel with the target P2P Device.
   3447 	 * The Find Phase in In-band Device Discovery or Out-of-Band Device
   3448 	 * Discovery may be used for this purpose. In the former case, the
   3449 	 * P2P Device only needs to scan the Listen Channel of the target
   3450 	 * P2P Device, as opposed to all of the Social Channels."
   3451 	 *
   3452 	 * All in all we transmit our Negotiation Requests on the peer's
   3453 	 * listen channel since it is bound to spend more time on that
   3454 	 * channel than on any other channel and then we listen for a
   3455 	 * potential GO Negotiation restart on our listen channel.
   3456 	 */
   3457 	listen_freq = band_channel_to_freq(dev->listen_channel,
   3458 						BAND_FREQ_2_4_GHZ);
   3459 
   3460 	msg = l_genl_msg_new_sized(NL80211_CMD_REMAIN_ON_CHANNEL, 64);
   3461 	l_genl_msg_append_attr(msg, NL80211_ATTR_WDEV, 8, &dev->wdev_id);
   3462 	l_genl_msg_append_attr(msg, NL80211_ATTR_WIPHY_FREQ, 4, &listen_freq);
   3463 	l_genl_msg_append_attr(msg, NL80211_ATTR_DURATION, 4, &duration);
   3464 
   3465 	cmd_id = l_genl_family_send(dev->nl80211, msg, p2p_device_roc_cb, dev,
   3466 					NULL);
   3467 	if (!cmd_id)
   3468 		l_genl_msg_unref(msg);
   3469 
   3470 	/*
   3471 	 * Time out after @duration ms independent of whether we were able to
   3472 	 * start the ROC command.  If we receive the CMD_REMAIN_ON_CHANNEL
   3473 	 * event we'll update the timeout to give the ROC command enough time
   3474 	 * to finish.  On an error or if we time out before the ROC command
   3475 	 * even starts, we'll just retry after @duration ms so we don't even
   3476 	 * need to handle errors specifically.
   3477 	 */
   3478 	dev->scan_timeout = l_timeout_create_ms(duration,
   3479 						p2p_device_roc_timeout, dev,
   3480 						p2p_scan_timeout_destroy);
   3481 	dev->listen_duration = duration;
   3482 	dev->have_roc_cookie = false;
   3483 
   3484 	l_debug("started a ROC command on channel %i for %i ms",
   3485 		(int) dev->listen_channel, (int) duration);
   3486 }
   3487 
   3488 static void p2p_peer_update_wfd(struct p2p_peer *peer,
   3489 				struct p2p_wfd_properties *new_wfd)
   3490 {
   3491 	struct p2p_wfd_properties *orig_wfd = peer->wfd;
   3492 
   3493 	if (!orig_wfd && !new_wfd)
   3494 		return;
   3495 
   3496 	peer->wfd = new_wfd ? l_memdup(new_wfd, sizeof(*new_wfd)) : NULL;
   3497 
   3498 	if (!orig_wfd && new_wfd) {
   3499 		l_dbus_object_add_interface(dbus_get_bus(),
   3500 						p2p_peer_get_path(peer),
   3501 						IWD_P2P_WFD_INTERFACE, peer);
   3502 		return;
   3503 	} else if (orig_wfd && !new_wfd) {
   3504 		l_free(orig_wfd);
   3505 		l_dbus_object_remove_interface(dbus_get_bus(),
   3506 						p2p_peer_get_path(peer),
   3507 						IWD_P2P_WFD_INTERFACE);
   3508 		return;
   3509 	}
   3510 
   3511 	if (orig_wfd->source != new_wfd->source)
   3512 		l_dbus_property_changed(dbus_get_bus(),
   3513 					p2p_peer_get_path(peer),
   3514 					IWD_P2P_WFD_INTERFACE, "Source");
   3515 
   3516 	if (orig_wfd->sink != new_wfd->sink)
   3517 		l_dbus_property_changed(dbus_get_bus(),
   3518 					p2p_peer_get_path(peer),
   3519 					IWD_P2P_WFD_INTERFACE, "Sink");
   3520 
   3521 	if (orig_wfd->port != new_wfd->port)
   3522 		l_dbus_property_changed(dbus_get_bus(),
   3523 					p2p_peer_get_path(peer),
   3524 					IWD_P2P_WFD_INTERFACE, "Port");
   3525 
   3526 	if (orig_wfd->audio != new_wfd->audio)
   3527 		l_dbus_property_changed(dbus_get_bus(),
   3528 					p2p_peer_get_path(peer),
   3529 					IWD_P2P_WFD_INTERFACE, "HasAudio");
   3530 
   3531 	if (orig_wfd->uibc != new_wfd->uibc)
   3532 		l_dbus_property_changed(dbus_get_bus(),
   3533 					p2p_peer_get_path(peer),
   3534 					IWD_P2P_WFD_INTERFACE, "HasUIBC");
   3535 
   3536 	if (orig_wfd->cp != new_wfd->cp)
   3537 		l_dbus_property_changed(dbus_get_bus(),
   3538 					p2p_peer_get_path(peer),
   3539 					IWD_P2P_WFD_INTERFACE,
   3540 					"HasContentProtection");
   3541 
   3542 	l_free(orig_wfd);
   3543 }
   3544 
   3545 static const char *p2p_peer_wsc_get_path(struct wsc_dbus *wsc)
   3546 {
   3547 	return p2p_peer_get_path(l_container_of(wsc, struct p2p_peer, wsc));
   3548 }
   3549 
   3550 static void p2p_peer_wsc_connect(struct wsc_dbus *wsc, const char *pin)
   3551 {
   3552 	p2p_peer_connect(l_container_of(wsc, struct p2p_peer, wsc), pin);
   3553 }
   3554 
   3555 static void p2p_peer_wsc_cancel(struct wsc_dbus *wsc)
   3556 {
   3557 	p2p_peer_disconnect(l_container_of(wsc, struct p2p_peer, wsc));
   3558 }
   3559 
   3560 static void p2p_peer_wsc_remove(struct wsc_dbus *wsc)
   3561 {
   3562 	/*
   3563 	 * The WSC removal is triggered in p2p_peer_put so we call
   3564 	 * p2p_peer_free directly from there too.
   3565 	 */
   3566 }
   3567 
   3568 static bool p2p_device_peer_add(struct p2p_device *dev, struct p2p_peer *peer)
   3569 {
   3570 	struct p2p_wfd_properties wfd;
   3571 
   3572 	if (!strlen(peer->name) || !l_utf8_validate(
   3573 					peer->name, strlen(peer->name), NULL)) {
   3574 		l_debug("Device name doesn't validate for bssid %s",
   3575 			util_address_to_string(peer->bss->addr));
   3576 		return false;
   3577 	}
   3578 
   3579 	if (!l_dbus_object_add_interface(dbus_get_bus(),
   3580 						p2p_peer_get_path(peer),
   3581 						IWD_P2P_PEER_INTERFACE, peer)) {
   3582 		l_debug("Unable to add the %s interface to %s",
   3583 			IWD_P2P_PEER_INTERFACE, p2p_peer_get_path(peer));
   3584 		return false;
   3585 	}
   3586 
   3587 	if (!l_dbus_object_add_interface(dbus_get_bus(),
   3588 						p2p_peer_get_path(peer),
   3589 						L_DBUS_INTERFACE_PROPERTIES,
   3590 						NULL)) {
   3591 		l_dbus_unregister_object(dbus_get_bus(),
   3592 						p2p_peer_get_path(peer));
   3593 		l_debug("Unable to add the %s interface to %s",
   3594 			L_DBUS_INTERFACE_PROPERTIES, p2p_peer_get_path(peer));
   3595 		return false;
   3596 	}
   3597 
   3598 	peer->wsc.get_path = p2p_peer_wsc_get_path;
   3599 	peer->wsc.connect = p2p_peer_wsc_connect;
   3600 	peer->wsc.cancel = p2p_peer_wsc_cancel;
   3601 	peer->wsc.remove = p2p_peer_wsc_remove;
   3602 
   3603 	if (!wsc_dbus_add_interface(&peer->wsc)) {
   3604 		l_dbus_unregister_object(dbus_get_bus(),
   3605 						p2p_peer_get_path(peer));
   3606 		return false;
   3607 	}
   3608 
   3609 	/*
   3610 	 * We need to either only show peers that are available for a WFD
   3611 	 * session, or expose the availability information through a property,
   3612 	 * which we are not doing right now.
   3613 	 */
   3614 	if (p2p_own_wfd && p2p_extract_wfd_properties(peer->bss->wfd,
   3615 						peer->bss->wfd_size, &wfd) &&
   3616 			wfd.available)
   3617 		p2p_peer_update_wfd(peer, &wfd);
   3618 
   3619 	l_queue_push_tail(dev->peer_list, peer);
   3620 
   3621 	return true;
   3622 }
   3623 
   3624 struct p2p_peer_move_data {
   3625 	struct l_queue *new_list;
   3626 	struct p2p_peer *conn_peer;
   3627 	uint64_t now;
   3628 };
   3629 
   3630 static bool p2p_peer_move_recent(void *data, void *user_data)
   3631 {
   3632 	struct p2p_peer *peer = data;
   3633 	struct p2p_peer_move_data *move_data = user_data;
   3634 
   3635 	if (move_data->now > peer->bss->time_stamp + 30 * L_USEC_PER_SEC &&
   3636 			peer != move_data->conn_peer)
   3637 		return false;	/* Old, keep on the list */
   3638 
   3639 	/* Recently seen or currently connected, move to the new list */
   3640 	l_queue_push_tail(move_data->new_list, peer);
   3641 	return true;
   3642 }
   3643 
   3644 static bool p2p_peer_update_existing(struct scan_bss *bss,
   3645 					struct l_queue *old_list,
   3646 					struct l_queue *new_list)
   3647 {
   3648 	struct p2p_peer *peer;
   3649 	struct p2p_wfd_properties wfd;
   3650 
   3651 	peer = l_queue_remove_if(old_list, p2p_peer_match, bss->addr);
   3652 	if (!peer)
   3653 		return false;
   3654 
   3655 	/*
   3656 	 * We've seen this peer already, only update the scan_bss object
   3657 	 * and WFD state.  We can update peer->bss even if
   3658 	 * peer == peer->dev->conn_peer because its .bss is not used by
   3659 	 * .conn_netdev or .conn_enrollee.  .conn_wsc_bss is used for
   3660 	 * both connections and it doesn't come from the discovery scan
   3661 	 * results.
   3662 	 * Some property changes may need to be notified here.
   3663 	 */
   3664 
   3665 	if (bss->source_frame == SCAN_BSS_PROBE_RESP)
   3666 		peer->device_addr =
   3667 			bss->p2p_probe_resp_info->device_info.device_addr;
   3668 	else if (bss->source_frame == SCAN_BSS_PROBE_REQ && !l_memeqzero(
   3669 			bss->p2p_probe_req_info->device_info.device_addr, 6))
   3670 		peer->device_addr =
   3671 			bss->p2p_probe_req_info->device_info.device_addr;
   3672 	else
   3673 		peer->device_addr = bss->addr;
   3674 
   3675 	scan_bss_free(peer->bss);
   3676 	peer->bss = bss;
   3677 
   3678 	if (p2p_own_wfd && p2p_extract_wfd_properties(bss->wfd, bss->wfd_size,
   3679 							&wfd) &&
   3680 			wfd.available)
   3681 		p2p_peer_update_wfd(peer, &wfd);
   3682 	else if (peer->wfd)
   3683 		p2p_peer_update_wfd(peer, NULL);
   3684 
   3685 	l_queue_push_tail(new_list, peer);
   3686 	return true;
   3687 }
   3688 
   3689 static bool p2p_scan_notify(int err, struct l_queue *bss_list,
   3690 				const struct scan_freq_set *freqs,
   3691 				void *user_data)
   3692 {
   3693 	struct p2p_device *dev = user_data;
   3694 	const struct l_queue_entry *entry;
   3695 	struct l_queue *old_peer_list = dev->peer_list;
   3696 	struct p2p_peer_move_data move_data;
   3697 
   3698 	if (err) {
   3699 		l_debug("P2P scan failed: %s (%i)", strerror(-err), -err);
   3700 		goto schedule;
   3701 	}
   3702 
   3703 	dev->peer_list = l_queue_new();
   3704 
   3705 	for (entry = l_queue_get_entries(bss_list); entry;
   3706 			entry = entry->next) {
   3707 		struct scan_bss *bss = entry->data;
   3708 		struct p2p_peer *peer;
   3709 
   3710 		if (bss->source_frame != SCAN_BSS_PROBE_RESP ||
   3711 				!bss->p2p_probe_resp_info) {
   3712 			scan_bss_free(bss);
   3713 			continue;
   3714 		}
   3715 
   3716 		if (p2p_peer_update_existing(bss, old_peer_list,
   3717 						dev->peer_list))
   3718 			continue;
   3719 
   3720 		peer = l_new(struct p2p_peer, 1);
   3721 		peer->dev = dev;
   3722 		peer->bss = bss;
   3723 		peer->name = l_strdup(bss->p2p_probe_resp_info->
   3724 						device_info.device_name);
   3725 		peer->primary_device_type =
   3726 			bss->p2p_probe_resp_info->device_info.primary_device_type;
   3727 		peer->group =
   3728 			!!(bss->p2p_probe_resp_info->capability.group_caps &
   3729 			   P2P_GROUP_CAP_GO);
   3730 		/*
   3731 		 * Both P2P Devices and GOs can send Probe Responses so the
   3732 		 * frame's source address may not necessarily be the Device
   3733 		 * Address, use what's in the obligatory Device Info.
   3734 		 */
   3735 		peer->device_addr =
   3736 			bss->p2p_probe_resp_info->device_info.device_addr;
   3737 
   3738 		if (!p2p_device_peer_add(dev, peer))
   3739 			p2p_peer_free(peer);
   3740 	}
   3741 
   3742 	/*
   3743 	 * old_peer_list now only contains peers not present in the new
   3744 	 * results.  Move any peers seen in the last 30 secs to the new
   3745 	 * dev->peer_list and unref only the remaining peers.
   3746 	 */
   3747 	move_data.new_list = dev->peer_list;
   3748 	move_data.conn_peer = dev->conn_peer;
   3749 	move_data.now = l_time_now();
   3750 	l_queue_foreach_remove(old_peer_list, p2p_peer_move_recent, &move_data);
   3751 	l_queue_destroy(old_peer_list, p2p_peer_put);
   3752 	l_queue_destroy(bss_list, NULL);
   3753 
   3754 schedule:
   3755 	/*
   3756 	 * Calculate interval between now and when we want the next active
   3757 	 * scan to start.  Keep issuing Remain-on-Channel commands of
   3758 	 * maximum duration until it's time to start the new scan.
   3759 	 * The listen periods are actually like a passive scan except that
   3760 	 * instead of listening for Beacons only, we also look at Probe
   3761 	 * Requests and Probe Responses because they, too, carry P2P IEs
   3762 	 * with all the information we need about peer devices.  Beacons
   3763 	 * also do, in case of GOs, but we will already get the same
   3764 	 * information from the Probe Responses and (even if we can
   3765 	 * receive the beacons in userspace in the first place) we don't
   3766 	 * want to handle so many frames.
   3767 	 *
   3768 	 * According to 3.1.2.1.1 we shall be available in listen state
   3769 	 * during Find for at least 500ms continuously at least once in
   3770 	 * every 5s.  According to 3.1.2.1.3, the Listen State lasts for
   3771 	 * between 1 and 3 one-hundred TU Intervals.
   3772 	 *
   3773 	 * The Search State duration is implementation dependent.
   3774 	 */
   3775 	if (dev->scan_interval < SCAN_INTERVAL_MAX)
   3776 		dev->scan_interval += SCAN_INTERVAL_STEP;
   3777 
   3778 	dev->next_scan_ts = time(NULL) + dev->scan_interval;
   3779 
   3780 	p2p_device_roc_start(dev);
   3781 	return true;
   3782 }
   3783 
   3784 static bool p2p_device_scan_start(struct p2p_device *dev)
   3785 {
   3786 	struct scan_parameters params = {};
   3787 	struct scan_freq_set *freqs;
   3788 	uint8_t buf[256];
   3789 	unsigned int i;
   3790 
   3791 	wiphy_get_reg_domain_country(dev->wiphy, (char *) dev->listen_country);
   3792 	dev->listen_country[2] = 4;	/* Table E-4 */
   3793 	dev->listen_oper_class = 81;	/* 2.4 band */
   3794 
   3795 	params.extra_ie = p2p_build_scan_ies(dev, buf, sizeof(buf),
   3796 						&params.extra_ie_size);
   3797 	L_WARN_ON(!params.extra_ie);
   3798 	params.flush = true;
   3799 	/* P2P Wildcard SSID because we don't need legacy networks to reply */
   3800 	params.ssid = (const uint8_t *)"DIRECT-";
   3801 	params.ssid_len = strlen("DIRECT-");
   3802 	/*
   3803 	 * Must send probe requests at 6Mb/s, OFDM only.  The no-CCK rates
   3804 	 * flag forces the drivers to do exactly this for 2.4GHz frames.
   3805 	 *
   3806 	 * "- P2P Devices shall not use 11b rates (1, 2, 5.5, 11 Mbps) for data
   3807 	 *   and management frames except:
   3808 	 *    * Probe Request frames sent to both P2P Devices and non-P2P
   3809 	 *      Devices.
   3810 	 * - P2P Devices shall not respond to Probe Request frames that indicate
   3811 	 *   support for 11b rates only.
   3812 	 * Note 1 - This means that the P2P Group Owner transmits Beacon frames
   3813 	 * using OFDM.
   3814 	 * Note 2 - This means that the P2P Group Owner transmits Probe Response
   3815 	 * frames using OFDM, including frames sent in response to Probe
   3816 	 * Requests received at 11b rates from non 11b-only devices.
   3817 	 * Note 3 - P2P Devices shall not include 11b rates in the list of
   3818 	 * supported rates in Probe Request frame intended only for P2P Devices.
   3819 	 * 11b rates may be included in the list of supported rates in Probe
   3820 	 * Request frames intended for both P2P Devices and non-P2P Devices."
   3821 	 */
   3822 	params.no_cck_rates = true;
   3823 	freqs = scan_freq_set_new();
   3824 
   3825 	for (i = 0; i < L_ARRAY_SIZE(channels_social); i++) {
   3826 		int chan = channels_social[i];
   3827 		uint32_t freq = band_channel_to_freq(chan, BAND_FREQ_2_4_GHZ);
   3828 
   3829 		scan_freq_set_add(freqs, freq);
   3830 	}
   3831 
   3832 	/*
   3833 	 * Instead of doing a single Scan Phase at the beginning of the Device
   3834 	 * Discovery and then strictly a Find Phase loop as defined in the
   3835 	 * spec, mix both to keep watching for P2P groups on the non-social
   3836 	 * channels, slowly going through a few channels at a time in each
   3837 	 * Scan State iteration.  Scan dev->chans_per_scan channels each time,
   3838 	 * use dev->scan_chan_idx to keep track of which channels we've
   3839 	 * visited recently.
   3840 	 */
   3841 	for (i = 0; i < dev->chans_per_scan; i++) {
   3842 		int idx = dev->scan_chan_idx++;
   3843 		int chan = channels_scan_2_4_other[idx];
   3844 		uint32_t freq = band_channel_to_freq(chan, BAND_FREQ_2_4_GHZ);
   3845 
   3846 		if (dev->scan_chan_idx >=
   3847 				L_ARRAY_SIZE(channels_scan_2_4_other)) {
   3848 			dev->scan_chan_idx = 0;
   3849 			/*
   3850 			 * Do fewer channels per scan after we've initially
   3851 			 * gone through the 2.4 band.
   3852 			 */
   3853 			dev->chans_per_scan = CHANS_PER_SCAN;
   3854 		}
   3855 
   3856 		scan_freq_set_add(freqs, freq);
   3857 	}
   3858 
   3859 	params.freqs = freqs;
   3860 
   3861 	dev->scan_id = scan_active_full(dev->wdev_id, &params, NULL,
   3862 					p2p_scan_notify, dev, p2p_scan_destroy);
   3863 	scan_freq_set_free(freqs);
   3864 
   3865 	return dev->scan_id != 0;
   3866 }
   3867 
   3868 static void p2p_probe_resp_done(int error, void *user_data)
   3869 {
   3870 	if (error)
   3871 		l_error("Sending the Probe Response failed: %s (%i)",
   3872 			strerror(-error), -error);
   3873 }
   3874 
   3875 static void p2p_device_send_probe_resp(struct p2p_device *dev,
   3876 					const uint8_t *dest_addr,
   3877 					bool to_conn_peer)
   3878 {
   3879 	uint8_t resp_buf[64] __attribute__ ((aligned));
   3880 	size_t resp_len = 0;
   3881 	struct p2p_probe_resp resp_info = {};
   3882 	uint8_t *p2p_ie;
   3883 	size_t p2p_ie_size;
   3884 	struct wsc_probe_response wsc_info = {};
   3885 	uint8_t *wsc_data;
   3886 	size_t wsc_data_size;
   3887 	uint8_t *wsc_ie;
   3888 	size_t wsc_ie_size;
   3889 	uint8_t wfd_ie[32];
   3890 	struct iovec iov[16];
   3891 	int iov_len = 0;
   3892 	/* TODO: extract some of these from wiphy features */
   3893 	uint16_t capability = IE_BSS_CAP_PRIVACY | IE_BSS_CAP_SHORT_PREAMBLE;
   3894 	struct mmpdu_header *header;
   3895 	uint32_t freq;
   3896 
   3897 	/* Header */
   3898 	memset(resp_buf, 0, sizeof(resp_buf));
   3899 	header = (void *) resp_buf;
   3900 	header->fc.protocol_version = 0;
   3901 	header->fc.type = MPDU_TYPE_MANAGEMENT;
   3902 	header->fc.subtype = MPDU_MANAGEMENT_SUBTYPE_PROBE_RESPONSE;
   3903 	memcpy(header->address_1, dest_addr, 6);	/* DA */
   3904 	memcpy(header->address_2, dev->addr, 6);	/* SA */
   3905 	memcpy(header->address_3, dev->addr, 6);	/* BSSID */
   3906 
   3907 	resp_len = (const uint8_t *) mmpdu_body(header) - resp_buf;
   3908 
   3909 	resp_len += 8;			/* Timestamp */
   3910 	resp_buf[resp_len++] = 0x64;	/* Beacon Interval: 100 TUs */
   3911 	resp_buf[resp_len++] = 0x00;
   3912 	resp_buf[resp_len++] = capability >> 0;
   3913 	resp_buf[resp_len++] = capability >> 8;
   3914 	resp_buf[resp_len++] = IE_TYPE_SSID;
   3915 	resp_buf[resp_len++] = 7;
   3916 	resp_buf[resp_len++] = 'D';
   3917 	resp_buf[resp_len++] = 'I';
   3918 	resp_buf[resp_len++] = 'R';
   3919 	resp_buf[resp_len++] = 'E';
   3920 	resp_buf[resp_len++] = 'C';
   3921 	resp_buf[resp_len++] = 'T';
   3922 	resp_buf[resp_len++] = '-';
   3923 	resp_buf[resp_len++] = IE_TYPE_SUPPORTED_RATES;
   3924 	resp_buf[resp_len++] = 8;
   3925 	resp_buf[resp_len++] = 0x8c;
   3926 	resp_buf[resp_len++] = 0x12;
   3927 	resp_buf[resp_len++] = 0x18;
   3928 	resp_buf[resp_len++] = 0x24;
   3929 	resp_buf[resp_len++] = 0x30;
   3930 	resp_buf[resp_len++] = 0x48;
   3931 	resp_buf[resp_len++] = 0x60;
   3932 	resp_buf[resp_len++] = 0x6c;
   3933 
   3934 	resp_info.capability = dev->capability;
   3935 	resp_info.device_info = dev->device_info;
   3936 
   3937 	/*
   3938 	 * Note the SSID and resp_info.group_clients are not updated with
   3939 	 * our group information because we generally won't be in the
   3940 	 * Listen State on the P2P Device when running a group.  Otherwise
   3941 	 * we'd be sending two Probe Responses, one from the P2P Interface
   3942 	 * and another from the P2P Device.  According to this part in
   3943 	 * Wi-Fi P2P Technical Specification v1.7 section 3.2.2 it seems
   3944 	 * only the P2P Interface is supposed to be sending Probe
   3945 	 * Responses in that situation:
   3946 	 * "In all Probe Responses that it sends, a P2P Group Owner shall
   3947 	 * set the SSID to the SSID of the group, and shall set the SA and
   3948 	 * BSSID to its P2P Interface Address."
   3949 	 */
   3950 
   3951 	p2p_ie = p2p_build_probe_resp(&resp_info, &p2p_ie_size);
   3952 	if (!p2p_ie) {
   3953 		l_error("Can't build our Probe Response P2P IE");
   3954 		return;
   3955 	}
   3956 
   3957 	if (to_conn_peer) {
   3958 		wsc_info.device_password_id = dev->conn_password_id;
   3959 		wsc_info.config_methods = dev->conn_config_method;
   3960 		wsc_uuid_from_addr(dev->conn_addr, wsc_info.uuid_e);
   3961 	} else {
   3962 		wsc_info.config_methods = dev->device_info.wsc_config_methods;
   3963 		wsc_uuid_from_addr(dev->addr, wsc_info.uuid_e);
   3964 	}
   3965 
   3966 	wsc_info.state = WSC_STATE_NOT_CONFIGURED;
   3967 	wsc_info.response_type = WSC_RESPONSE_TYPE_ENROLLEE_INFO;
   3968 	wsc_info.serial_number[0] = '0';
   3969 	wsc_info.primary_device_type = dev->device_info.primary_device_type;
   3970 	l_strlcpy(wsc_info.device_name, dev->device_info.device_name,
   3971 			sizeof(wsc_info.device_name));
   3972 	wsc_info.rf_bands = WSC_RF_BAND_2_4_GHZ;
   3973 	wsc_info.version2 = true;
   3974 
   3975 	wsc_data = wsc_build_probe_response(&wsc_info, &wsc_data_size);
   3976 	if (!wsc_data) {
   3977 		l_free(p2p_ie);
   3978 		l_error("Can't build our Probe Response WSC payload");
   3979 		return;
   3980 	}
   3981 
   3982 	wsc_ie = ie_tlv_encapsulate_wsc_payload(wsc_data, wsc_data_size,
   3983 						&wsc_ie_size);
   3984 	l_free(wsc_data);
   3985 	if (!wsc_ie) {
   3986 		l_free(p2p_ie);
   3987 		l_error("Can't build our Probe Response WSC IE");
   3988 		return;
   3989 	}
   3990 
   3991 	iov[iov_len].iov_base = resp_buf;
   3992 	iov[iov_len].iov_len = resp_len;
   3993 	iov_len++;
   3994 
   3995 	iov[iov_len].iov_base = p2p_ie;
   3996 	iov[iov_len].iov_len = p2p_ie_size;
   3997 	iov_len++;
   3998 
   3999 	iov[iov_len].iov_base = wsc_ie;
   4000 	iov[iov_len].iov_len = wsc_ie_size;
   4001 	iov_len++;
   4002 
   4003 	if (to_conn_peer && dev->conn_own_wfd) {
   4004 		iov[iov_len].iov_base = wfd_ie;
   4005 		iov[iov_len].iov_len = p2p_build_wfd_ie(dev->conn_own_wfd,
   4006 							NULL, wfd_ie);
   4007 		iov_len++;
   4008 	} else if (p2p_own_wfd) {
   4009 		iov[iov_len].iov_base = wfd_ie;
   4010 		iov[iov_len].iov_len = p2p_build_wfd_ie(p2p_own_wfd,
   4011 							NULL, wfd_ie);
   4012 		iov_len++;
   4013 	}
   4014 
   4015 	iov[iov_len].iov_base = NULL;
   4016 
   4017 	freq = band_channel_to_freq(dev->listen_channel, BAND_FREQ_2_4_GHZ);
   4018 	frame_xchg_start(dev->wdev_id, iov, freq, 0, 0, false, 0,
   4019 				p2p_probe_resp_done, dev, NULL, NULL);
   4020 	l_debug("Probe Response tx queued");
   4021 
   4022 	l_free(p2p_ie);
   4023 	l_free(wsc_ie);
   4024 }
   4025 
   4026 static void p2p_device_probe_cb(const struct mmpdu_header *mpdu,
   4027 				const void *body, size_t body_len,
   4028 				int rssi, void *user_data)
   4029 {
   4030 	struct p2p_device *dev = user_data;
   4031 	struct p2p_peer *peer;
   4032 	struct p2p_probe_req p2p_info;
   4033 	struct wsc_probe_request wsc_info;
   4034 	int r;
   4035 	uint8_t *wsc_payload;
   4036 	ssize_t wsc_len;
   4037 	struct scan_bss *bss;
   4038 	struct p2p_channel_attr *channel;
   4039 	enum band_freq band;
   4040 	uint32_t frequency;
   4041 	bool from_conn_peer;
   4042 
   4043 	l_debug("");
   4044 
   4045 	if (!dev->scan_timeout && !dev->scan_id)
   4046 		return;
   4047 
   4048 	from_conn_peer =
   4049 		dev->conn_go_neg_req_timeout && dev->conn_peer &&
   4050 		!memcmp(mpdu->address_2, dev->conn_peer->bss->addr, 6);
   4051 
   4052 	wsc_payload = ie_tlv_extract_wsc_payload(body, body_len, &wsc_len);
   4053 	if (!wsc_payload)	/* Not a P2P Probe Req, ignore */
   4054 		return;
   4055 
   4056 	r =  wsc_parse_probe_request(wsc_payload, wsc_len, &wsc_info);
   4057 	l_free(wsc_payload);
   4058 
   4059 	if (r < 0) {
   4060 		l_error("Probe Request WSC IE parse error %s (%i)",
   4061 			strerror(-r), -r);
   4062 
   4063 		/*
   4064 		 * Ignore requests with erroneous WSC IEs except if they
   4065 		 * come from the peer we're currently connecting to as a
   4066 		 * workaround for implementations sending invalid Probe
   4067 		 * Requests.
   4068 		 */
   4069 		if (!from_conn_peer)
   4070 			return;
   4071 	}
   4072 
   4073 	r = p2p_parse_probe_req(body, body_len, &p2p_info);
   4074 	if (r < 0) {
   4075 		if (r == -ENOENT)	/* Not a P2P Probe Req, ignore */
   4076 			return;
   4077 
   4078 		l_error("Probe Request P2P IE parse error %s (%i)",
   4079 			strerror(-r), -r);
   4080 		return;
   4081 	}
   4082 
   4083 	/*
   4084 	 * TODO: use ap.c code to check if we match the SSID, BSSID, DSSS
   4085 	 * Channel etc. in the Probe Request, and to build the Response body.
   4086 	 */
   4087 	p2p_device_send_probe_resp(dev, mpdu->address_2, from_conn_peer);
   4088 
   4089 	/*
   4090 	 * The peer's listen frequency may be different from ours.
   4091 	 * The Listen Channel attribute is optional but if neither
   4092 	 * it nor the Operating Channel are set then we have no way
   4093 	 * to contact that peer.  Ignore such peers.
   4094 	 */
   4095 	if (p2p_info.listen_channel.country[0])
   4096 		channel = &p2p_info.listen_channel;
   4097 	else if (p2p_info.operating_channel.country[0])
   4098 		channel = &p2p_info.operating_channel;
   4099 	else
   4100 		goto p2p_free;
   4101 
   4102 	band = band_oper_class_to_band((const uint8_t *) channel->country,
   4103 					channel->oper_class);
   4104 	frequency = band_channel_to_freq(channel->channel_num, band);
   4105 	if (!frequency)
   4106 		goto p2p_free;
   4107 
   4108 	bss = scan_bss_new_from_probe_req(mpdu, body, body_len, frequency,
   4109 						rssi);
   4110 	if (!bss)
   4111 		goto p2p_free;
   4112 
   4113 	bss->time_stamp = l_time_now();
   4114 
   4115 	if (p2p_peer_update_existing(bss, dev->peer_list, dev->peer_list))
   4116 		goto p2p_free;
   4117 
   4118 	peer = l_new(struct p2p_peer, 1);
   4119 	peer->dev = dev;
   4120 	peer->bss = bss;
   4121 	peer->name = l_strdup(wsc_info.device_name);
   4122 	peer->primary_device_type = wsc_info.primary_device_type;
   4123 	peer->group = !!(p2p_info.capability.group_caps & P2P_GROUP_CAP_GO);
   4124 	/*
   4125 	 * The Device Info attribute is present conditionally so we can't get
   4126 	 * the Device Address from there.  In theory only P2P Devices send
   4127 	 * out Probe Requests, not P2P GOs, so we assume the source address
   4128 	 * is the Device Address.
   4129 	 */
   4130 	peer->device_addr = bss->addr;
   4131 
   4132 	if (!dev->peer_list)
   4133 		dev->peer_list = l_queue_new();
   4134 
   4135 	if (!p2p_device_peer_add(dev, peer))
   4136 		p2p_peer_free(peer);
   4137 
   4138 	/*
   4139 	 * TODO: check SSID/BSSID are wildcard values if present and
   4140 	 * reply with a Probe Response -- not useful in our current usage
   4141 	 * scenarios but required by the spec.
   4142 	 */
   4143 
   4144 p2p_free:
   4145 	p2p_clear_probe_req(&p2p_info);
   4146 }
   4147 
   4148 static void p2p_device_discovery_start(struct p2p_device *dev)
   4149 {
   4150 	if (dev->scan_timeout || dev->scan_id)
   4151 		return;
   4152 
   4153 	dev->scan_interval = 1;
   4154 	dev->chans_per_scan = CHANS_PER_SCAN_INITIAL;
   4155 	dev->scan_chan_idx = 0;
   4156 
   4157 	/*
   4158 	 * 3.1.2.1.1: "The Listen Channel shall be chosen at the beginning of
   4159 	 * the In-band Device Discovery"
   4160 	 *
   4161 	 * But keep the old channel if we're still waiting for the peer to
   4162 	 * restart the GO Negotiation because there may not be enough time
   4163 	 * for the peer to update our Listen Channel value before the user
   4164 	 * accepts the connection.  In that case the GO Negotiation Request
   4165 	 * would be sent on the old channel.
   4166 	 */
   4167 	if (!(dev->listen_channel && dev->conn_peer))
   4168 		dev->listen_channel = channels_social[l_getrandom_uint32() %
   4169 						L_ARRAY_SIZE(channels_social)];
   4170 
   4171 	frame_watch_add(dev->wdev_id, FRAME_GROUP_P2P_LISTEN, 0x0040,
   4172 			(uint8_t *) "", 0, false,
   4173 			p2p_device_probe_cb, dev, NULL);
   4174 	frame_watch_add(dev->wdev_id, FRAME_GROUP_P2P_LISTEN, 0x00d0,
   4175 			p2p_frame_go_neg_req.data, p2p_frame_go_neg_req.len,
   4176 			false, p2p_device_go_negotiation_req_cb, dev, NULL);
   4177 
   4178 	p2p_device_scan_start(dev);
   4179 }
   4180 
   4181 static void p2p_device_discovery_stop(struct p2p_device *dev)
   4182 {
   4183 	dev->scan_interval = 0;
   4184 
   4185 	if (dev->scan_id)
   4186 		scan_cancel(dev->wdev_id, dev->scan_id);
   4187 
   4188 	if (dev->scan_timeout)
   4189 		l_timeout_remove(dev->scan_timeout);
   4190 
   4191 	p2p_device_roc_cancel(dev);
   4192 	frame_watch_group_remove(dev->wdev_id, FRAME_GROUP_P2P_LISTEN);
   4193 }
   4194 
   4195 static void p2p_device_enable_cb(struct l_genl_msg *msg, void *user_data)
   4196 {
   4197 	struct p2p_device *dev = user_data;
   4198 	int error = l_genl_msg_get_error(msg);
   4199 	struct l_dbus_message *message = dev->pending_message;
   4200 
   4201 	l_debug("START/STOP_P2P_DEVICE: %s (%i)", strerror(-error), -error);
   4202 
   4203 	if (error)
   4204 		goto done;
   4205 
   4206 	dev->enabled = !dev->enabled;
   4207 
   4208 	if (dev->enabled && !l_queue_isempty(dev->discovery_users))
   4209 		p2p_device_discovery_start(dev);
   4210 
   4211 done:
   4212 	dev->pending_complete(dbus_get_bus(), message,
   4213 				error ? dbus_error_failed(message) :
   4214 				NULL);
   4215 	dev->pending_message = NULL;
   4216 	dev->pending_complete = NULL;
   4217 
   4218 	if (!error)
   4219 		l_dbus_property_changed(dbus_get_bus(),
   4220 					p2p_device_get_path(dev),
   4221 					IWD_P2P_INTERFACE, "Enabled");
   4222 }
   4223 
   4224 static void p2p_device_enable_destroy(void *user_data)
   4225 {
   4226 	struct p2p_device *dev = user_data;
   4227 
   4228 	dev->start_stop_cmd_id = 0;
   4229 }
   4230 
   4231 static bool p2p_peer_remove_disconnected(void *peer, void *conn_peer)
   4232 {
   4233 	if (peer == conn_peer)
   4234 		return false;
   4235 
   4236 	p2p_peer_put(peer);
   4237 	return true;
   4238 }
   4239 
   4240 static void p2p_device_start_stop(struct p2p_device *dev,
   4241 				l_dbus_property_complete_cb_t complete,
   4242 				struct l_dbus_message *message)
   4243 {
   4244 	struct l_genl_msg *cmd;
   4245 
   4246 	if (dev->enabled)
   4247 		p2p_device_discovery_stop(dev);
   4248 
   4249 	if (!dev->enabled)
   4250 		cmd = l_genl_msg_new_sized(NL80211_CMD_START_P2P_DEVICE, 16);
   4251 	else
   4252 		cmd = l_genl_msg_new_sized(NL80211_CMD_STOP_P2P_DEVICE, 16);
   4253 
   4254 	l_genl_msg_append_attr(cmd, NL80211_ATTR_WDEV, 8, &dev->wdev_id);
   4255 
   4256 	dev->start_stop_cmd_id = l_genl_family_send(dev->nl80211, cmd,
   4257 						p2p_device_enable_cb, dev,
   4258 						p2p_device_enable_destroy);
   4259 	if (!dev->start_stop_cmd_id) {
   4260 		l_genl_msg_unref(cmd);
   4261 		complete(dbus_get_bus(), message, dbus_error_failed(message));
   4262 		return;
   4263 	}
   4264 
   4265 	dev->pending_message = message;
   4266 	dev->pending_complete = complete;
   4267 
   4268 	if (dev->enabled) {
   4269 		/*
   4270 		 * Stopping the P2P device, drop all peers as we can't start
   4271 		 * new connections from now on.  Check if we have a connection
   4272 		 * being set up without a .conn_netdev and without
   4273 		 * .conn_wsc_bss -- this will mean the connection is still in
   4274 		 * the PD or GO Negotiation phase or inside the scan.  Those
   4275 		 * phases happen on the device interface so the connection
   4276 		 * gets immediately aborted.
   4277 		 */
   4278 		if (dev->conn_peer && !dev->conn_netdev && !dev->conn_wsc_bss)
   4279 			p2p_connect_failed(dev);
   4280 
   4281 		if (!dev->conn_peer) {
   4282 			l_queue_destroy(dev->peer_list, p2p_peer_put);
   4283 			dev->peer_list = NULL;
   4284 		} else
   4285 			/*
   4286 			 * If the connection already depends on its own
   4287 			 * netdev only, we can let it continue until the user
   4288 			 * decides to disconnect.
   4289 			 */
   4290 			l_queue_foreach_remove(dev->peer_list,
   4291 						p2p_peer_remove_disconnected,
   4292 						dev->conn_peer);
   4293 	}
   4294 }
   4295 
   4296 static void p2p_mlme_notify(struct l_genl_msg *msg, void *user_data)
   4297 {
   4298 	struct p2p_device *dev = user_data;
   4299 	uint64_t wdev_id;
   4300 	uint64_t cookie;
   4301 
   4302 	if (nl80211_parse_attrs(msg, NL80211_ATTR_WDEV, &wdev_id,
   4303 				NL80211_ATTR_COOKIE, &cookie,
   4304 				NL80211_ATTR_UNSPEC) < 0 ||
   4305 			wdev_id != dev->wdev_id)
   4306 		return;
   4307 
   4308 	switch (l_genl_msg_get_command(msg)) {
   4309 	case NL80211_CMD_REMAIN_ON_CHANNEL:
   4310 		if (!dev->have_roc_cookie || cookie != dev->roc_cookie)
   4311 			break;
   4312 
   4313 		if (!dev->scan_timeout)
   4314 			break;
   4315 
   4316 		/*
   4317 		 * The Listen phase is actually starting here, update the
   4318 		 * timeout so we know more or less when it ends.
   4319 		 */
   4320 		l_debug("ROC started");
   4321 		l_timeout_modify_ms(dev->scan_timeout, dev->listen_duration);
   4322 		break;
   4323 	case NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL:
   4324 		/* TODO */
   4325 		break;
   4326 	}
   4327 }
   4328 
   4329 #define P2P_SUPPORTED_METHODS	(			\
   4330 	WSC_CONFIGURATION_METHOD_LABEL |		\
   4331 	WSC_CONFIGURATION_METHOD_KEYPAD |		\
   4332 	WSC_CONFIGURATION_METHOD_VIRTUAL_PUSH_BUTTON |	\
   4333 	WSC_CONFIGURATION_METHOD_PHYSICAL_PUSH_BUTTON |	\
   4334 	WSC_CONFIGURATION_METHOD_P2P |			\
   4335 	WSC_CONFIGURATION_METHOD_VIRTUAL_DISPLAY_PIN |	\
   4336 	WSC_CONFIGURATION_METHOD_PHYSICAL_DISPLAY_PIN)
   4337 
   4338 struct p2p_device *p2p_device_update_from_genl(struct l_genl_msg *msg,
   4339 						bool create)
   4340 {
   4341 	const uint8_t *ifaddr;
   4342 	uint32_t iftype;
   4343 	uint64_t wdev_id;
   4344 	uint32_t wiphy_id;
   4345 	struct wiphy *wiphy;
   4346 	struct p2p_device *dev;
   4347 	char hostname[HOST_NAME_MAX + 1];
   4348 	char *str;
   4349 	unsigned int uint_val;
   4350 
   4351 	if (nl80211_parse_attrs(msg, NL80211_ATTR_WDEV, &wdev_id,
   4352 				NL80211_ATTR_WIPHY, &wiphy_id,
   4353 				NL80211_ATTR_IFTYPE, &iftype,
   4354 				NL80211_ATTR_MAC, &ifaddr,
   4355 				NL80211_ATTR_UNSPEC) < 0 ||
   4356 			L_WARN_ON(!(wiphy = wiphy_find(wiphy_id))) ||
   4357 			L_WARN_ON(iftype != NL80211_IFTYPE_P2P_DEVICE)) {
   4358 		l_warn("Unable to parse interface information");
   4359 		return NULL;
   4360 	}
   4361 
   4362 	if (create) {
   4363 		if (p2p_device_find(wdev_id)) {
   4364 			l_debug("Duplicate p2p device %" PRIx64, wdev_id);
   4365 			return NULL;
   4366 		}
   4367 	} else {
   4368 		dev = p2p_device_find(wdev_id);
   4369 		if (!dev)
   4370 			return NULL;
   4371 
   4372 		memcpy(dev->addr, ifaddr, ETH_ALEN);
   4373 		return NULL;
   4374 	}
   4375 
   4376 	dev = l_new(struct p2p_device, 1);
   4377 	dev->wdev_id = wdev_id;
   4378 	memcpy(dev->addr, ifaddr, ETH_ALEN);
   4379 	dev->nl80211 = l_genl_family_new(iwd_get_genl(), NL80211_GENL_NAME);
   4380 	dev->wiphy = wiphy;
   4381 	gethostname(hostname, sizeof(hostname));
   4382 	dev->connections_left = 1;
   4383 
   4384 	/*
   4385 	 * Section 3.1.4.2: "The Tie breaker bit in a first GO Negotiation
   4386 	 * Request frame (for instance after power up) shall be set to 0 or 1
   4387 	 * randomly, such that both values occur equally on average."
   4388 	 */
   4389 	dev->next_tie_breaker = l_getrandom_uint32();
   4390 
   4391 	/* TODO: allow masking capability bits through a setting? */
   4392 	dev->capability.device_caps = P2P_DEVICE_CAP_CONCURRENT_OP;
   4393 	dev->capability.group_caps = 0;
   4394 
   4395 	memcpy(dev->device_info.device_addr, dev->addr, 6);
   4396 
   4397 	dev->device_info.wsc_config_methods =
   4398 		WSC_CONFIGURATION_METHOD_P2P |
   4399 		WSC_CONFIGURATION_METHOD_PUSH_BUTTON;
   4400 	dev->device_info.primary_device_type.category = 1;	/* Computer */
   4401 	memcpy(dev->device_info.primary_device_type.oui, microsoft_oui, 3);
   4402 	dev->device_info.primary_device_type.oui_type = 0x04;
   4403 	dev->device_info.primary_device_type.subcategory = 1;	/* PC */
   4404 	l_strlcpy(dev->device_info.device_name, hostname,
   4405 			sizeof(dev->device_info.device_name));
   4406 
   4407 	if (l_settings_get_uint(iwd_get_config(), "P2P",
   4408 				"ConfigurationMethods", &uint_val)) {
   4409 		if (!(uint_val & P2P_SUPPORTED_METHODS))
   4410 			l_error("[P2P].ConfigurationMethods must contain "
   4411 				"at least one supported method");
   4412 		else if (uint_val & ~0xffff)
   4413 			l_error("[P2P].ConfigurationMethods should be a "
   4414 				"16-bit integer");
   4415 		else
   4416 			dev->device_info.wsc_config_methods =
   4417 				uint_val & P2P_SUPPORTED_METHODS;
   4418 	}
   4419 
   4420 	str = l_settings_get_string(iwd_get_config(), "P2P", "DeviceType");
   4421 
   4422 	if (str && !wsc_device_type_from_setting_str(str,
   4423 					&dev->device_info.primary_device_type))
   4424 		l_error("[P2P].DeviceType must be a subcategory string "
   4425 			"or a 64-bit integer encoding the full Primary"
   4426 			" Device Type attribute: "
   4427 			"<Category>|<OUI>|<OUI Type>|<Subcategory>");
   4428 
   4429 	l_free(str);
   4430 
   4431 	l_queue_push_tail(p2p_device_list, dev);
   4432 
   4433 	l_debug("Created P2P device %" PRIx64, dev->wdev_id);
   4434 
   4435 	scan_wdev_add(dev->wdev_id);
   4436 
   4437 	if (!l_genl_family_register(dev->nl80211, NL80211_MULTICAST_GROUP_MLME,
   4438 					p2p_mlme_notify, dev, NULL))
   4439 		l_error("Registering for MLME notifications failed");
   4440 
   4441 #ifdef HAVE_DBUS
   4442 	if (!l_dbus_object_add_interface(dbus_get_bus(),
   4443 						p2p_device_get_path(dev),
   4444 						IWD_P2P_INTERFACE, dev))
   4445 		l_info("Unable to add the %s interface to %s",
   4446 			IWD_P2P_INTERFACE, p2p_device_get_path(dev));
   4447 #endif
   4448 
   4449 	return dev;
   4450 }
   4451 
   4452 static void p2p_device_free(void *user_data)
   4453 {
   4454 	struct p2p_device *dev = user_data;
   4455 
   4456 #ifdef HAVE_DBUS
   4457 	if (dev->pending_message) {
   4458 		struct l_dbus_message *reply =
   4459 			dbus_error_aborted(dev->pending_message);
   4460 
   4461 		dev->pending_complete(dbus_get_bus(),
   4462 					dev->pending_message, reply);
   4463 		dev->pending_message = NULL;
   4464 		dev->pending_complete = NULL;
   4465 	}
   4466 #endif
   4467 
   4468 	p2p_device_discovery_stop(dev);
   4469 	p2p_connection_reset(dev);
   4470 #ifdef HAVE_DBUS
   4471 	l_dbus_unregister_object(dbus_get_bus(), p2p_device_get_path(dev));
   4472 #endif
   4473 	l_queue_destroy(dev->peer_list, p2p_peer_put);
   4474 	l_queue_destroy(dev->discovery_users, p2p_discovery_user_free);
   4475 	l_genl_family_free(dev->nl80211); /* Cancels dev->start_stop_cmd_id */
   4476 	scan_wdev_remove(dev->wdev_id);
   4477 	l_free(dev);
   4478 }
   4479 
   4480 bool p2p_device_destroy(struct p2p_device *dev)
   4481 {
   4482 	if (!l_queue_remove(p2p_device_list, dev))
   4483 		return false;
   4484 
   4485 	p2p_device_free(dev);
   4486 	return true;
   4487 }
   4488 
   4489 static bool p2p_device_get_enabled(struct l_dbus *dbus,
   4490 					struct l_dbus_message *message,
   4491 					struct l_dbus_message_builder *builder,
   4492 					void *user_data)
   4493 {
   4494 	struct p2p_device *dev = user_data;
   4495 	bool enabled = dev->enabled;
   4496 
   4497 	l_dbus_message_builder_append_basic(builder, 'b', &enabled);
   4498 
   4499 	return true;
   4500 }
   4501 
   4502 static struct l_dbus_message *p2p_device_set_enabled(struct l_dbus *dbus,
   4503 					struct l_dbus_message *message,
   4504 					struct l_dbus_message_iter *new_value,
   4505 					l_dbus_property_complete_cb_t complete,
   4506 					void *user_data)
   4507 {
   4508 	struct p2p_device *dev = user_data;
   4509 	bool new_enabled;
   4510 
   4511 	if (!l_dbus_message_iter_get_variant(new_value, "b", &new_enabled))
   4512 		return dbus_error_invalid_args(message);
   4513 
   4514 	if (dev->start_stop_cmd_id || dev->pending_message)
   4515 		return dbus_error_busy(message);
   4516 
   4517 	if (dev->enabled == new_enabled) {
   4518 		complete(dbus, message, NULL);
   4519 		return NULL;
   4520 	}
   4521 
   4522 	p2p_device_start_stop(dev, complete, message);
   4523 	return NULL;
   4524 }
   4525 
   4526 static bool p2p_device_get_name(struct l_dbus *dbus,
   4527 				struct l_dbus_message *message,
   4528 				struct l_dbus_message_builder *builder,
   4529 				void *user_data)
   4530 {
   4531 	struct p2p_device *dev = user_data;
   4532 
   4533 	l_dbus_message_builder_append_basic(builder, 's',
   4534 						dev->device_info.device_name);
   4535 	return true;
   4536 }
   4537 
   4538 static struct l_dbus_message *p2p_device_set_name(struct l_dbus *dbus,
   4539 					struct l_dbus_message *message,
   4540 					struct l_dbus_message_iter *new_value,
   4541 					l_dbus_property_complete_cb_t complete,
   4542 					void *user_data)
   4543 {
   4544 	struct p2p_device *dev = user_data;
   4545 	const char *new_name;
   4546 	bool changed = false;
   4547 
   4548 	if (!l_dbus_message_iter_get_variant(new_value, "s", &new_name))
   4549 		return dbus_error_invalid_args(message);
   4550 
   4551 	if (!strcmp(new_name, dev->device_info.device_name))
   4552 		goto done;
   4553 
   4554 	if (strlen(new_name) > sizeof(dev->device_info.device_name) - 1)
   4555 		return dbus_error_invalid_args(message);
   4556 
   4557 	changed = true;
   4558 	l_strlcpy(dev->device_info.device_name, new_name,
   4559 			sizeof(dev->device_info.device_name));
   4560 
   4561 done:
   4562 	complete(dbus, message, NULL);
   4563 
   4564 	if (changed)
   4565 		l_dbus_property_changed(dbus, p2p_device_get_path(dev),
   4566 					IWD_P2P_INTERFACE, "Name");
   4567 
   4568 	return NULL;
   4569 }
   4570 
   4571 static bool p2p_device_get_avail_conns(struct l_dbus *dbus,
   4572 					struct l_dbus_message *message,
   4573 					struct l_dbus_message_builder *builder,
   4574 					void *user_data)
   4575 {
   4576 	struct p2p_device *dev = user_data;
   4577 	uint16_t avail_conns = dev->connections_left;
   4578 
   4579 	l_dbus_message_builder_append_basic(builder, 'q', &avail_conns);
   4580 	return true;
   4581 }
   4582 
   4583 static struct l_dbus_message *p2p_device_get_peers(struct l_dbus *dbus,
   4584 						struct l_dbus_message *message,
   4585 						void *user_data)
   4586 {
   4587 	struct p2p_device *dev = user_data;
   4588 	struct l_dbus_message *reply;
   4589 	struct l_dbus_message_builder *builder;
   4590 	const struct l_queue_entry *entry;
   4591 
   4592 	if (!l_dbus_message_get_arguments(message, ""))
   4593 		return dbus_error_invalid_args(message);
   4594 
   4595 	reply = l_dbus_message_new_method_return(message);
   4596 	builder = l_dbus_message_builder_new(reply);
   4597 
   4598 	l_dbus_message_builder_enter_array(builder, "(on)");
   4599 
   4600 	for (entry = l_queue_get_entries(dev->peer_list); entry;
   4601 			entry = entry->next) {
   4602 		const struct p2p_peer *peer = entry->data;
   4603 		int16_t signal_strength = peer->bss->signal_strength;
   4604 
   4605 		l_dbus_message_builder_enter_struct(builder, "on");
   4606 		l_dbus_message_builder_append_basic(builder, 'o',
   4607 						p2p_peer_get_path(peer));
   4608 		l_dbus_message_builder_append_basic(builder, 'n',
   4609 							&signal_strength);
   4610 		l_dbus_message_builder_leave_struct(builder);
   4611 	}
   4612 
   4613 	l_dbus_message_builder_leave_array(builder);
   4614 
   4615 	l_dbus_message_builder_finalize(builder);
   4616 	l_dbus_message_builder_destroy(builder);
   4617 
   4618 	return reply;
   4619 }
   4620 
   4621 static void p2p_device_discovery_disconnect(struct l_dbus *dbus, void *user_data)
   4622 {
   4623 	struct p2p_discovery_user *user = user_data;
   4624 	struct p2p_device *dev = user->dev;
   4625 
   4626 	l_debug("P2P Device Discovery user %s disconnected", user->client);
   4627 
   4628 	l_queue_remove(dev->discovery_users, user);
   4629 	p2p_discovery_user_free(user);
   4630 
   4631 	if (l_queue_isempty(dev->discovery_users))
   4632 		p2p_device_discovery_stop(dev);
   4633 }
   4634 
   4635 static void p2p_device_discovery_destroy(void *user_data)
   4636 {
   4637 	struct p2p_discovery_user *user = user_data;
   4638 
   4639 	user->disconnect_watch = 0;
   4640 }
   4641 
   4642 static struct l_dbus_message *p2p_device_request_discovery(struct l_dbus *dbus,
   4643 						struct l_dbus_message *message,
   4644 						void *user_data)
   4645 {
   4646 	struct p2p_device *dev = user_data;
   4647 	struct p2p_discovery_user *user;
   4648 	bool first_user = l_queue_isempty(dev->discovery_users);
   4649 
   4650 	if (!l_dbus_message_get_arguments(message, ""))
   4651 		return dbus_error_invalid_args(message);
   4652 
   4653 	if (l_queue_find(dev->discovery_users, p2p_discovery_user_match,
   4654 				l_dbus_message_get_sender(message)))
   4655 		return dbus_error_already_exists(message);
   4656 
   4657 	if (!dev->discovery_users)
   4658 		dev->discovery_users = l_queue_new();
   4659 
   4660 	user = l_new(struct p2p_discovery_user, 1);
   4661 	user->client = l_strdup(l_dbus_message_get_sender(message));
   4662 	user->dev = dev;
   4663 	user->disconnect_watch = l_dbus_add_disconnect_watch(dbus,
   4664 						user->client,
   4665 						p2p_device_discovery_disconnect,
   4666 						user,
   4667 						p2p_device_discovery_destroy);
   4668 	l_queue_push_tail(dev->discovery_users, user);
   4669 
   4670 	if (first_user && !dev->conn_peer && dev->enabled)
   4671 		p2p_device_discovery_start(dev);
   4672 
   4673 	return l_dbus_message_new_method_return(message);
   4674 }
   4675 
   4676 static struct l_dbus_message *p2p_device_release_discovery(struct l_dbus *dbus,
   4677 						struct l_dbus_message *message,
   4678 						void *user_data)
   4679 {
   4680 	struct p2p_device *dev = user_data;
   4681 	struct p2p_discovery_user *user;
   4682 
   4683 	if (!l_dbus_message_get_arguments(message, ""))
   4684 		return dbus_error_invalid_args(message);
   4685 
   4686 	user = l_queue_remove_if(dev->discovery_users,
   4687 				p2p_discovery_user_match,
   4688 				l_dbus_message_get_sender(message));
   4689 	if (!user)
   4690 		return dbus_error_not_found(message);
   4691 
   4692 	p2p_discovery_user_free(user);
   4693 
   4694 	/*
   4695 	 * If dev->conn_peer is non-NULL, we may be scanning as a way to
   4696 	 * listen for a GO Negotiation Request from the target peer.  In
   4697 	 * that case we don't stop the device discovery when the list
   4698 	 * becomes empty.
   4699 	 */
   4700 	if (l_queue_isempty(dev->discovery_users) && !dev->conn_peer)
   4701 		p2p_device_discovery_stop(dev);
   4702 
   4703 	return l_dbus_message_new_method_return(message);
   4704 }
   4705 
   4706 static void p2p_interface_setup(struct l_dbus_interface *interface)
   4707 {
   4708 	l_dbus_interface_property(interface, "Enabled", 0, "b",
   4709 					p2p_device_get_enabled,
   4710 					p2p_device_set_enabled);
   4711 	l_dbus_interface_property(interface, "Name", 0, "s",
   4712 					p2p_device_get_name,
   4713 					p2p_device_set_name);
   4714 	l_dbus_interface_property(interface, "AvailableConnections", 0, "q",
   4715 					p2p_device_get_avail_conns, NULL);
   4716 	l_dbus_interface_method(interface, "GetPeers", 0,
   4717 				p2p_device_get_peers, "a(on)", "", "peers");
   4718 	l_dbus_interface_method(interface, "RequestDiscovery", 0,
   4719 				p2p_device_request_discovery, "", "");
   4720 	l_dbus_interface_method(interface, "ReleaseDiscovery", 0,
   4721 				p2p_device_release_discovery, "", "");
   4722 }
   4723 
   4724 static bool p2p_peer_get_name(struct l_dbus *dbus,
   4725 				struct l_dbus_message *message,
   4726 				struct l_dbus_message_builder *builder,
   4727 				void *user_data)
   4728 {
   4729 	struct p2p_peer *peer = user_data;
   4730 
   4731 	l_dbus_message_builder_append_basic(builder, 's', peer->name);
   4732 	return true;
   4733 }
   4734 
   4735 static bool p2p_peer_get_addr(struct l_dbus *dbus,
   4736 				struct l_dbus_message *message,
   4737 				struct l_dbus_message_builder *builder,
   4738 				void *user_data)
   4739 {
   4740 	struct p2p_peer *peer = user_data;
   4741 	const char *addr = util_address_to_string(peer->device_addr);
   4742 
   4743 	l_dbus_message_builder_append_basic(builder, 's', addr);
   4744 	return true;
   4745 }
   4746 
   4747 static bool p2p_peer_get_device(struct l_dbus *dbus,
   4748 				struct l_dbus_message *message,
   4749 				struct l_dbus_message_builder *builder,
   4750 				void *user_data)
   4751 {
   4752 	struct p2p_peer *peer = user_data;
   4753 
   4754 	l_dbus_message_builder_append_basic(builder, 'o',
   4755 						p2p_device_get_path(peer->dev));
   4756 	return true;
   4757 }
   4758 
   4759 static bool p2p_peer_get_category(struct l_dbus *dbus,
   4760 					struct l_dbus_message *message,
   4761 					struct l_dbus_message_builder *builder,
   4762 					void *user_data)
   4763 {
   4764 	struct p2p_peer *peer = user_data;
   4765 	const char *category;
   4766 
   4767 	if (!wsc_device_type_to_dbus_str(&peer->primary_device_type,
   4768 						&category, NULL) ||
   4769 			!category)
   4770 		category = "unknown-device";
   4771 
   4772 	l_dbus_message_builder_append_basic(builder, 's', category);
   4773 	return true;
   4774 }
   4775 
   4776 static bool p2p_peer_get_subcategory(struct l_dbus *dbus,
   4777 					struct l_dbus_message *message,
   4778 					struct l_dbus_message_builder *builder,
   4779 					void *user_data)
   4780 {
   4781 	struct p2p_peer *peer = user_data;
   4782 	const char *subcategory;
   4783 
   4784 	/*
   4785 	 * Should we generate subcategory strings with the numerical
   4786 	 * values for the subcategories we don't know, such as
   4787 	 * "Vendor-specific 00:11:22:33 44" ?
   4788 	 */
   4789 
   4790 	if (!wsc_device_type_to_dbus_str(&peer->primary_device_type,
   4791 						NULL, &subcategory) ||
   4792 			!subcategory)
   4793 		return false;
   4794 
   4795 	l_dbus_message_builder_append_basic(builder, 's', subcategory);
   4796 	return true;
   4797 }
   4798 
   4799 static bool p2p_peer_get_connected(struct l_dbus *dbus,
   4800 					struct l_dbus_message *message,
   4801 					struct l_dbus_message_builder *builder,
   4802 					void *user_data)
   4803 {
   4804 	struct p2p_peer *peer = user_data;
   4805 	bool connected = p2p_peer_operational(peer) &&
   4806 		peer->dev->conn_peer == peer;
   4807 
   4808 	l_dbus_message_builder_append_basic(builder, 'b', &connected);
   4809 	return true;
   4810 }
   4811 
   4812 static bool p2p_peer_get_connected_if(struct l_dbus *dbus,
   4813 					struct l_dbus_message *message,
   4814 					struct l_dbus_message_builder *builder,
   4815 					void *user_data)
   4816 {
   4817 	struct p2p_peer *peer = user_data;
   4818 	const char *ifname = netdev_get_name(peer->dev->conn_netdev);
   4819 
   4820 	if (!p2p_peer_operational(peer))
   4821 		return false;
   4822 
   4823 	l_dbus_message_builder_append_basic(builder, 's', ifname);
   4824 	return true;
   4825 }
   4826 
   4827 static bool p2p_peer_get_connected_ip(struct l_dbus *dbus,
   4828 					struct l_dbus_message *message,
   4829 					struct l_dbus_message_builder *builder,
   4830 					void *user_data)
   4831 {
   4832 	struct p2p_peer *peer = user_data;
   4833 
   4834 	if (!p2p_peer_operational(peer))
   4835 		return false;
   4836 
   4837 	l_dbus_message_builder_append_basic(builder, 's', peer->dev->conn_peer_ip);
   4838 	return true;
   4839 }
   4840 
   4841 static struct l_dbus_message *p2p_peer_dbus_disconnect(struct l_dbus *dbus,
   4842 						struct l_dbus_message *message,
   4843 						void *user_data)
   4844 {
   4845 	struct p2p_peer *peer = user_data;
   4846 
   4847 	if (!l_dbus_message_get_arguments(message, ""))
   4848 		return dbus_error_invalid_args(message);
   4849 
   4850 	/*
   4851 	 * Save the message for both WSC.Cancel and Peer.Disconnect the
   4852 	 * same way.
   4853 	 */
   4854 	peer->wsc.pending_cancel = l_dbus_message_ref(message);
   4855 
   4856 	p2p_peer_disconnect(peer);
   4857 	return NULL;
   4858 }
   4859 
   4860 static void p2p_peer_interface_setup(struct l_dbus_interface *interface)
   4861 {
   4862 	l_dbus_interface_property(interface, "Name", 0, "s",
   4863 					p2p_peer_get_name, NULL);
   4864 	l_dbus_interface_property(interface, "Address", 0, "s",
   4865 					p2p_peer_get_addr, NULL);
   4866 	l_dbus_interface_property(interface, "Device", 0, "o",
   4867 					p2p_peer_get_device, NULL);
   4868 	l_dbus_interface_property(interface, "DeviceCategory", 0, "s",
   4869 					p2p_peer_get_category, NULL);
   4870 	l_dbus_interface_property(interface, "DeviceSubcategory", 0, "s",
   4871 					p2p_peer_get_subcategory, NULL);
   4872 	l_dbus_interface_property(interface, "Connected", 0, "b",
   4873 					p2p_peer_get_connected, NULL);
   4874 	l_dbus_interface_property(interface, "ConnectedInterface", 0, "s",
   4875 					p2p_peer_get_connected_if, NULL);
   4876 	l_dbus_interface_property(interface, "ConnectedIP", 0, "s",
   4877 					p2p_peer_get_connected_ip, NULL);
   4878 	l_dbus_interface_method(interface, "Disconnect", 0,
   4879 				p2p_peer_dbus_disconnect, "", "");
   4880 }
   4881 
   4882 static bool p2p_peer_get_wfd_source(struct l_dbus *dbus,
   4883 					struct l_dbus_message *message,
   4884 					struct l_dbus_message_builder *builder,
   4885 					void *user_data)
   4886 {
   4887 	struct p2p_peer *peer = user_data;
   4888 
   4889 	l_dbus_message_builder_append_basic(builder, 'b', &peer->wfd->source);
   4890 	return true;
   4891 }
   4892 
   4893 static bool p2p_peer_get_wfd_sink(struct l_dbus *dbus,
   4894 					struct l_dbus_message *message,
   4895 					struct l_dbus_message_builder *builder,
   4896 					void *user_data)
   4897 {
   4898 	struct p2p_peer *peer = user_data;
   4899 
   4900 	l_dbus_message_builder_append_basic(builder, 'b', &peer->wfd->sink);
   4901 	return true;
   4902 }
   4903 
   4904 static bool p2p_peer_get_wfd_port(struct l_dbus *dbus,
   4905 					struct l_dbus_message *message,
   4906 					struct l_dbus_message_builder *builder,
   4907 					void *user_data)
   4908 {
   4909 	struct p2p_peer *peer = user_data;
   4910 
   4911 	if (!peer->wfd->source)
   4912 		return false;
   4913 
   4914 	l_dbus_message_builder_append_basic(builder, 'q', &peer->wfd->port);
   4915 	return true;
   4916 }
   4917 
   4918 static bool p2p_peer_get_wfd_has_audio(struct l_dbus *dbus,
   4919 					struct l_dbus_message *message,
   4920 					struct l_dbus_message_builder *builder,
   4921 					void *user_data)
   4922 {
   4923 	struct p2p_peer *peer = user_data;
   4924 
   4925 	if (!peer->wfd->sink)
   4926 		return false;
   4927 
   4928 	l_dbus_message_builder_append_basic(builder, 'b', &peer->wfd->audio);
   4929 	return true;
   4930 }
   4931 
   4932 static bool p2p_peer_get_wfd_has_uibc(struct l_dbus *dbus,
   4933 					struct l_dbus_message *message,
   4934 					struct l_dbus_message_builder *builder,
   4935 					void *user_data)
   4936 {
   4937 	struct p2p_peer *peer = user_data;
   4938 
   4939 	l_dbus_message_builder_append_basic(builder, 'b', &peer->wfd->uibc);
   4940 	return true;
   4941 }
   4942 
   4943 static bool p2p_peer_get_wfd_has_cp(struct l_dbus *dbus,
   4944 					struct l_dbus_message *message,
   4945 					struct l_dbus_message_builder *builder,
   4946 					void *user_data)
   4947 {
   4948 	struct p2p_peer *peer = user_data;
   4949 
   4950 	l_dbus_message_builder_append_basic(builder, 'b', &peer->wfd->cp);
   4951 	return true;
   4952 }
   4953 
   4954 static void p2p_wfd_interface_setup(struct l_dbus_interface *interface)
   4955 {
   4956 	l_dbus_interface_property(interface, "Source", 0, "b",
   4957 					p2p_peer_get_wfd_source, NULL);
   4958 	l_dbus_interface_property(interface, "Sink", 0, "b",
   4959 					p2p_peer_get_wfd_sink, NULL);
   4960 	l_dbus_interface_property(interface, "Port", 0, "q",
   4961 					p2p_peer_get_wfd_port, NULL);
   4962 	l_dbus_interface_property(interface, "HasAudio", 0, "b",
   4963 					p2p_peer_get_wfd_has_audio, NULL);
   4964 	l_dbus_interface_property(interface, "HasUIBC", 0, "b",
   4965 					p2p_peer_get_wfd_has_uibc, NULL);
   4966 	l_dbus_interface_property(interface, "HasContentProtection", 0, "b",
   4967 					p2p_peer_get_wfd_has_cp, NULL);
   4968 }
   4969 
   4970 static void p2p_own_wfd_free(void)
   4971 {
   4972 	const struct l_queue_entry *entry;
   4973 
   4974 	l_free(p2p_own_wfd);
   4975 	p2p_own_wfd = NULL;
   4976 
   4977 	for (entry = l_queue_get_entries(p2p_device_list); entry;
   4978 			entry = entry->next) {
   4979 		struct p2p_device *dev = entry->data;
   4980 
   4981 		if (dev->conn_own_wfd)
   4982 			p2p_connect_failed(dev);
   4983 	}
   4984 }
   4985 
   4986 static void p2p_wfd_disconnect_watch_cb(struct l_dbus *dbus, void *user_data)
   4987 {
   4988 	l_debug("P2P WFD service disconnected");
   4989 
   4990 	if (L_WARN_ON(unlikely(!p2p_own_wfd)))
   4991 		return;
   4992 
   4993 	p2p_own_wfd_free();
   4994 }
   4995 
   4996 static void p2p_wfd_disconnect_watch_destroy(void *user_data)
   4997 {
   4998 	p2p_wfd_disconnect_watch = 0;
   4999 }
   5000 
   5001 static struct l_dbus_message *p2p_wfd_register(struct l_dbus *dbus,
   5002 						struct l_dbus_message *message,
   5003 						void *user_data)
   5004 {
   5005 	const char *prop_name;
   5006 	struct l_dbus_message_iter prop_iter;
   5007 	struct l_dbus_message_iter prop_variant;
   5008 	struct p2p_wfd_properties props = {};
   5009 	bool have_source = false;
   5010 	bool have_sink = false;
   5011 	bool have_port = false;
   5012 	bool have_has_audio = false;
   5013 	bool have_has_uibc = false;
   5014 	bool have_has_cp = false;
   5015 
   5016 	if (!l_dbus_message_get_arguments(message, "a{sv}", &prop_iter))
   5017 		return dbus_error_invalid_args(message);
   5018 
   5019 	while (l_dbus_message_iter_next_entry(&prop_iter, &prop_name,
   5020 						&prop_variant)) {
   5021 		if (!strcmp(prop_name, "Source")) {
   5022 			if (have_source)
   5023 				return dbus_error_invalid_args(message);
   5024 
   5025 			if (!l_dbus_message_iter_get_variant(&prop_variant, "b",
   5026 								&props.source))
   5027 				return dbus_error_invalid_args(message);
   5028 
   5029 			have_source = true;
   5030 		} else if (!strcmp(prop_name, "Sink")) {
   5031 			if (have_sink)
   5032 				return dbus_error_invalid_args(message);
   5033 
   5034 			if (!l_dbus_message_iter_get_variant(&prop_variant, "b",
   5035 								&props.sink))
   5036 				return dbus_error_invalid_args(message);
   5037 
   5038 			have_sink = true;
   5039 		} else if (!strcmp(prop_name, "Port")) {
   5040 			if (have_port)
   5041 				return dbus_error_invalid_args(message);
   5042 
   5043 			if (!l_dbus_message_iter_get_variant(&prop_variant, "q",
   5044 								&props.port))
   5045 				return dbus_error_invalid_args(message);
   5046 
   5047 			have_port = true;
   5048 		} else if (!strcmp(prop_name, "HasAudio")) {
   5049 			if (have_has_audio)
   5050 				return dbus_error_invalid_args(message);
   5051 
   5052 			if (!l_dbus_message_iter_get_variant(&prop_variant, "b",
   5053 								&props.audio))
   5054 				return dbus_error_invalid_args(message);
   5055 
   5056 			have_has_audio = true;
   5057 		} else if (!strcmp(prop_name, "HasUIBC")) {
   5058 			if (have_has_uibc)
   5059 				return dbus_error_invalid_args(message);
   5060 
   5061 			if (!l_dbus_message_iter_get_variant(&prop_variant, "b",
   5062 								&props.uibc))
   5063 				return dbus_error_invalid_args(message);
   5064 
   5065 			have_has_uibc = true;
   5066 		} else if (!strcmp(prop_name, "HasContentProtection")) {
   5067 			if (have_has_cp)
   5068 				return dbus_error_invalid_args(message);
   5069 
   5070 			if (!l_dbus_message_iter_get_variant(&prop_variant, "b",
   5071 								&props.cp))
   5072 				return dbus_error_invalid_args(message);
   5073 
   5074 			have_has_cp = true;
   5075 		} else
   5076 			return dbus_error_invalid_args(message);
   5077 	}
   5078 
   5079 	if ((!have_source || !props.source) && (!have_sink || !props.sink))
   5080 		return dbus_error_invalid_args(message);
   5081 
   5082 	if (!have_source)
   5083 		props.source = !props.sink;
   5084 	else if (!have_sink)
   5085 		props.sink = !props.source;
   5086 
   5087 	if (have_port && (!props.source || props.port == 0))
   5088 		return dbus_error_invalid_args(message);
   5089 
   5090 	if (props.source && !have_port)
   5091 		props.port = 7236;
   5092 
   5093 	if (have_has_audio && !props.sink)
   5094 		return dbus_error_invalid_args(message);
   5095 	else if (!have_has_audio && props.sink)
   5096 		props.audio = true;
   5097 
   5098 	/*
   5099 	 * Should this be calculated based on Wi-Fi connection capacity?
   5100 	 * Wi-Fi Display Technical Specification v2.1.0 only mentions this
   5101 	 * in the context of the video format selection on the source (D.1.1):
   5102 	 * "A WFD Source should determine averaged encoded video data rate
   5103 	 * not to exceed the value indicated in the WFD Device Maximum
   5104 	 * throughput field at WFD Device Information subelement transmitted
   5105 	 * by the targeted WFD Sink [...]"
   5106 	 */
   5107 	props.throughput = 10;
   5108 
   5109 	if (p2p_own_wfd)
   5110 		return dbus_error_already_exists(message);
   5111 
   5112 	/* Available for WFD Session by default */
   5113 	props.available = true;
   5114 
   5115 	p2p_wfd_disconnect_watch = l_dbus_add_disconnect_watch(dbus,
   5116 					l_dbus_message_get_sender(message),
   5117 					p2p_wfd_disconnect_watch_cb, NULL,
   5118 					p2p_wfd_disconnect_watch_destroy);
   5119 	p2p_own_wfd = l_memdup(&props, sizeof(props));
   5120 	return l_dbus_message_new_method_return(message);
   5121 }
   5122 
   5123 static struct l_dbus_message *p2p_wfd_unregister(struct l_dbus *dbus,
   5124 						struct l_dbus_message *message,
   5125 						void *user_data)
   5126 {
   5127 	if (!l_dbus_message_get_arguments(message, ""))
   5128 		return dbus_error_invalid_args(message);
   5129 
   5130 	if (!p2p_own_wfd)
   5131 		return dbus_error_not_found(message);
   5132 
   5133 	/* TODO: possibly check sender */
   5134 	l_dbus_remove_watch(dbus, p2p_wfd_disconnect_watch);
   5135 	p2p_own_wfd_free();
   5136 	return l_dbus_message_new_method_return(message);
   5137 }
   5138 
   5139 static void p2p_service_manager_interface_setup(
   5140 					struct l_dbus_interface *interface)
   5141 {
   5142 	l_dbus_interface_method(interface, "RegisterDisplayService", 0,
   5143 				p2p_wfd_register, "", "a{sv}", "properties");
   5144 	l_dbus_interface_method(interface, "UnregisterDisplayService", 0,
   5145 				p2p_wfd_unregister, "", "");
   5146 }
   5147 
   5148 static void p2p_service_manager_destroy_cb(void *user_data)
   5149 {
   5150 	if (p2p_own_wfd) {
   5151 		l_dbus_remove_watch(dbus_get_bus(), p2p_wfd_disconnect_watch);
   5152 		p2p_own_wfd_free();
   5153 	}
   5154 }
   5155 
   5156 static int p2p_init(void)
   5157 {
   5158 #ifdef HAVE_DBUS
   5159 	struct l_dbus *dbus = dbus_get_bus();
   5160 
   5161 	if (!l_dbus_register_interface(dbus, IWD_P2P_INTERFACE,
   5162 					p2p_interface_setup,
   5163 					NULL, false))
   5164 		l_error("Unable to register the %s interface",
   5165 			IWD_P2P_INTERFACE);
   5166 
   5167 	if (!l_dbus_register_interface(dbus, IWD_P2P_PEER_INTERFACE,
   5168 					p2p_peer_interface_setup,
   5169 					NULL, false))
   5170 		l_error("Unable to register the %s interface",
   5171 			IWD_P2P_PEER_INTERFACE);
   5172 #endif
   5173 
   5174 	p2p_dhcp_settings = l_settings_new();
   5175 	p2p_device_list = l_queue_new();
   5176 
   5177 #ifdef HAVE_DBUS
   5178 	if (!l_dbus_register_interface(dbus, IWD_P2P_WFD_INTERFACE,
   5179 					p2p_wfd_interface_setup,
   5180 					NULL, false))
   5181 		l_error("Unable to register the %s interface",
   5182 			IWD_P2P_WFD_INTERFACE);
   5183 
   5184 	if (!l_dbus_register_interface(dbus, IWD_P2P_SERVICE_MANAGER_INTERFACE,
   5185 					p2p_service_manager_interface_setup,
   5186 					p2p_service_manager_destroy_cb, false))
   5187 		l_error("Unable to register the %s interface",
   5188 			IWD_P2P_SERVICE_MANAGER_INTERFACE);
   5189 	else if (!l_dbus_object_add_interface(dbus,
   5190 					IWD_P2P_SERVICE_MANAGER_PATH,
   5191 					IWD_P2P_SERVICE_MANAGER_INTERFACE,
   5192 					NULL))
   5193 		l_error("Unable to register the P2P Service Manager object");
   5194 #endif
   5195 
   5196 	if (!l_settings_get_uint(iwd_get_config(), "P2P", "DHCPTimeout",
   5197 					&p2p_dhcp_timeout_val))
   5198 		p2p_dhcp_timeout_val = 20;	/* 20s default */
   5199 
   5200 	return 0;
   5201 }
   5202 
   5203 static void p2p_exit(void)
   5204 {
   5205 #ifdef HAVE_DBUS
   5206 	struct l_dbus *dbus = dbus_get_bus();
   5207 
   5208 	l_dbus_unregister_interface(dbus, IWD_P2P_INTERFACE);
   5209 	l_dbus_unregister_interface(dbus, IWD_P2P_PEER_INTERFACE);
   5210 	l_dbus_unregister_interface(dbus, IWD_P2P_WFD_INTERFACE);
   5211 	l_dbus_unregister_interface(dbus, IWD_P2P_SERVICE_MANAGER_INTERFACE);
   5212 #endif
   5213 	l_queue_destroy(p2p_device_list, p2p_device_free);
   5214 	p2p_device_list = NULL;
   5215 	l_settings_free(p2p_dhcp_settings);
   5216 	p2p_dhcp_settings = NULL;
   5217 }
   5218 
   5219 IWD_MODULE(p2p, p2p_init, p2p_exit)
   5220 IWD_MODULE_DEPENDS(p2p, wiphy)
   5221 IWD_MODULE_DEPENDS(p2p, scan)
   5222 IWD_MODULE_DEPENDS(p2p, netconfig)