Home | History | Annotate | Download | only in p2p
      1 /*
      2  * Wi-Fi Direct - P2P module
      3  * Copyright (c) 2009-2010, Atheros Communications
      4  *
      5  * This software may be distributed under the terms of the BSD license.
      6  * See README for more details.
      7  */
      8 
      9 #include "includes.h"
     10 
     11 #include "common.h"
     12 #include "eloop.h"
     13 #include "common/ieee802_11_defs.h"
     14 #include "common/ieee802_11_common.h"
     15 #include "common/wpa_ctrl.h"
     16 #include "crypto/sha256.h"
     17 #include "crypto/crypto.h"
     18 #include "wps/wps_i.h"
     19 #include "p2p_i.h"
     20 #include "p2p.h"
     21 
     22 
     23 static void p2p_state_timeout(void *eloop_ctx, void *timeout_ctx);
     24 static void p2p_device_free(struct p2p_data *p2p, struct p2p_device *dev);
     25 static void p2p_process_presence_req(struct p2p_data *p2p, const u8 *da,
     26 				     const u8 *sa, const u8 *data, size_t len,
     27 				     int rx_freq);
     28 static void p2p_process_presence_resp(struct p2p_data *p2p, const u8 *da,
     29 				      const u8 *sa, const u8 *data,
     30 				      size_t len);
     31 static void p2p_ext_listen_timeout(void *eloop_ctx, void *timeout_ctx);
     32 static void p2p_scan_timeout(void *eloop_ctx, void *timeout_ctx);
     33 
     34 
     35 /*
     36  * p2p_scan recovery timeout
     37  *
     38  * Many drivers are using 30 second timeout on scan results. Allow a bit larger
     39  * timeout for this to avoid hitting P2P timeout unnecessarily.
     40  */
     41 #define P2P_SCAN_TIMEOUT 35
     42 
     43 /**
     44  * P2P_PEER_EXPIRATION_AGE - Number of seconds after which inactive peer
     45  * entries will be removed
     46  */
     47 #ifndef P2P_PEER_EXPIRATION_AGE
     48 #define P2P_PEER_EXPIRATION_AGE 60
     49 #endif /* P2P_PEER_EXPIRATION_AGE */
     50 
     51 #define P2P_PEER_EXPIRATION_INTERVAL (P2P_PEER_EXPIRATION_AGE / 2)
     52 
     53 static void p2p_expire_peers(struct p2p_data *p2p)
     54 {
     55 	struct p2p_device *dev, *n;
     56 	struct os_reltime now;
     57 	size_t i;
     58 
     59 	os_get_reltime(&now);
     60 	dl_list_for_each_safe(dev, n, &p2p->devices, struct p2p_device, list) {
     61 		if (dev->last_seen.sec + P2P_PEER_EXPIRATION_AGE >= now.sec)
     62 			continue;
     63 
     64 		if (dev == p2p->go_neg_peer) {
     65 			/*
     66 			 * GO Negotiation is in progress with the peer, so
     67 			 * don't expire the peer entry until GO Negotiation
     68 			 * fails or times out.
     69 			 */
     70 			continue;
     71 		}
     72 
     73 		if (p2p->cfg->go_connected &&
     74 		    p2p->cfg->go_connected(p2p->cfg->cb_ctx,
     75 					   dev->info.p2p_device_addr)) {
     76 			/*
     77 			 * We are connected as a client to a group in which the
     78 			 * peer is the GO, so do not expire the peer entry.
     79 			 */
     80 			os_get_reltime(&dev->last_seen);
     81 			continue;
     82 		}
     83 
     84 		for (i = 0; i < p2p->num_groups; i++) {
     85 			if (p2p_group_is_client_connected(
     86 				    p2p->groups[i], dev->info.p2p_device_addr))
     87 				break;
     88 		}
     89 		if (i < p2p->num_groups) {
     90 			/*
     91 			 * The peer is connected as a client in a group where
     92 			 * we are the GO, so do not expire the peer entry.
     93 			 */
     94 			os_get_reltime(&dev->last_seen);
     95 			continue;
     96 		}
     97 
     98 		p2p_dbg(p2p, "Expiring old peer entry " MACSTR,
     99 			MAC2STR(dev->info.p2p_device_addr));
    100 		dl_list_del(&dev->list);
    101 		p2p_device_free(p2p, dev);
    102 	}
    103 }
    104 
    105 
    106 static void p2p_expiration_timeout(void *eloop_ctx, void *timeout_ctx)
    107 {
    108 	struct p2p_data *p2p = eloop_ctx;
    109 	p2p_expire_peers(p2p);
    110 	eloop_register_timeout(P2P_PEER_EXPIRATION_INTERVAL, 0,
    111 			       p2p_expiration_timeout, p2p, NULL);
    112 }
    113 
    114 
    115 static const char * p2p_state_txt(int state)
    116 {
    117 	switch (state) {
    118 	case P2P_IDLE:
    119 		return "IDLE";
    120 	case P2P_SEARCH:
    121 		return "SEARCH";
    122 	case P2P_CONNECT:
    123 		return "CONNECT";
    124 	case P2P_CONNECT_LISTEN:
    125 		return "CONNECT_LISTEN";
    126 	case P2P_GO_NEG:
    127 		return "GO_NEG";
    128 	case P2P_LISTEN_ONLY:
    129 		return "LISTEN_ONLY";
    130 	case P2P_WAIT_PEER_CONNECT:
    131 		return "WAIT_PEER_CONNECT";
    132 	case P2P_WAIT_PEER_IDLE:
    133 		return "WAIT_PEER_IDLE";
    134 	case P2P_SD_DURING_FIND:
    135 		return "SD_DURING_FIND";
    136 	case P2P_PROVISIONING:
    137 		return "PROVISIONING";
    138 	case P2P_PD_DURING_FIND:
    139 		return "PD_DURING_FIND";
    140 	case P2P_INVITE:
    141 		return "INVITE";
    142 	case P2P_INVITE_LISTEN:
    143 		return "INVITE_LISTEN";
    144 	default:
    145 		return "?";
    146 	}
    147 }
    148 
    149 
    150 const char * p2p_get_state_txt(struct p2p_data *p2p)
    151 {
    152 	return p2p_state_txt(p2p->state);
    153 }
    154 
    155 
    156 struct p2ps_advertisement * p2p_get_p2ps_adv_list(struct p2p_data *p2p)
    157 {
    158 	return p2p ? p2p->p2ps_adv_list : NULL;
    159 }
    160 
    161 
    162 void p2p_set_intended_addr(struct p2p_data *p2p, const u8 *intended_addr)
    163 {
    164 	if (p2p && intended_addr)
    165 		os_memcpy(p2p->intended_addr, intended_addr, ETH_ALEN);
    166 }
    167 
    168 
    169 u16 p2p_get_provisioning_info(struct p2p_data *p2p, const u8 *addr)
    170 {
    171 	struct p2p_device *dev = NULL;
    172 
    173 	if (!addr || !p2p)
    174 		return 0;
    175 
    176 	dev = p2p_get_device(p2p, addr);
    177 	if (dev)
    178 		return dev->wps_prov_info;
    179 	else
    180 		return 0;
    181 }
    182 
    183 
    184 void p2p_clear_provisioning_info(struct p2p_data *p2p, const u8 *addr)
    185 {
    186 	struct p2p_device *dev = NULL;
    187 
    188 	if (!addr || !p2p)
    189 		return;
    190 
    191 	dev = p2p_get_device(p2p, addr);
    192 	if (dev)
    193 		dev->wps_prov_info = 0;
    194 }
    195 
    196 
    197 void p2p_set_state(struct p2p_data *p2p, int new_state)
    198 {
    199 	p2p_dbg(p2p, "State %s -> %s",
    200 		p2p_state_txt(p2p->state), p2p_state_txt(new_state));
    201 	p2p->state = new_state;
    202 
    203 	if (new_state == P2P_IDLE && p2p->pending_channel) {
    204 		p2p_dbg(p2p, "Apply change in listen channel");
    205 		p2p->cfg->reg_class = p2p->pending_reg_class;
    206 		p2p->cfg->channel = p2p->pending_channel;
    207 		p2p->pending_reg_class = 0;
    208 		p2p->pending_channel = 0;
    209 	}
    210 }
    211 
    212 
    213 void p2p_set_timeout(struct p2p_data *p2p, unsigned int sec, unsigned int usec)
    214 {
    215 	p2p_dbg(p2p, "Set timeout (state=%s): %u.%06u sec",
    216 		p2p_state_txt(p2p->state), sec, usec);
    217 	eloop_cancel_timeout(p2p_state_timeout, p2p, NULL);
    218 	eloop_register_timeout(sec, usec, p2p_state_timeout, p2p, NULL);
    219 }
    220 
    221 
    222 void p2p_clear_timeout(struct p2p_data *p2p)
    223 {
    224 	p2p_dbg(p2p, "Clear timeout (state=%s)", p2p_state_txt(p2p->state));
    225 	eloop_cancel_timeout(p2p_state_timeout, p2p, NULL);
    226 }
    227 
    228 
    229 void p2p_go_neg_failed(struct p2p_data *p2p, int status)
    230 {
    231 	struct p2p_go_neg_results res;
    232 	struct p2p_device *peer = p2p->go_neg_peer;
    233 
    234 	if (!peer)
    235 		return;
    236 
    237 	eloop_cancel_timeout(p2p_go_neg_wait_timeout, p2p, NULL);
    238 	if (p2p->state != P2P_SEARCH) {
    239 		/*
    240 		 * Clear timeouts related to GO Negotiation if no new p2p_find
    241 		 * has been started.
    242 		 */
    243 		p2p_clear_timeout(p2p);
    244 		p2p_set_state(p2p, P2P_IDLE);
    245 	}
    246 
    247 	peer->flags &= ~P2P_DEV_PEER_WAITING_RESPONSE;
    248 	peer->wps_method = WPS_NOT_READY;
    249 	peer->oob_pw_id = 0;
    250 	wpabuf_free(peer->go_neg_conf);
    251 	peer->go_neg_conf = NULL;
    252 	p2p->go_neg_peer = NULL;
    253 
    254 	os_memset(&res, 0, sizeof(res));
    255 	res.status = status;
    256 	os_memcpy(res.peer_device_addr, peer->info.p2p_device_addr, ETH_ALEN);
    257 	os_memcpy(res.peer_interface_addr, peer->intended_addr, ETH_ALEN);
    258 	p2p->cfg->go_neg_completed(p2p->cfg->cb_ctx, &res);
    259 }
    260 
    261 
    262 static void p2p_listen_in_find(struct p2p_data *p2p, int dev_disc)
    263 {
    264 	unsigned int r, tu;
    265 	int freq;
    266 	struct wpabuf *ies;
    267 
    268 	p2p_dbg(p2p, "Starting short listen state (state=%s)",
    269 		p2p_state_txt(p2p->state));
    270 
    271 	if (p2p->pending_listen_freq) {
    272 		/* We have a pending p2p_listen request */
    273 		p2p_dbg(p2p, "p2p_listen command pending already");
    274 		return;
    275 	}
    276 
    277 	freq = p2p_channel_to_freq(p2p->cfg->reg_class, p2p->cfg->channel);
    278 	if (freq < 0) {
    279 		p2p_dbg(p2p, "Unknown regulatory class/channel");
    280 		return;
    281 	}
    282 
    283 	if (os_get_random((u8 *) &r, sizeof(r)) < 0)
    284 		r = 0;
    285 	tu = (r % ((p2p->max_disc_int - p2p->min_disc_int) + 1) +
    286 	      p2p->min_disc_int) * 100;
    287 	if (p2p->max_disc_tu >= 0 && tu > (unsigned int) p2p->max_disc_tu)
    288 		tu = p2p->max_disc_tu;
    289 	if (!dev_disc && tu < 100)
    290 		tu = 100; /* Need to wait in non-device discovery use cases */
    291 	if (p2p->cfg->max_listen && 1024 * tu / 1000 > p2p->cfg->max_listen)
    292 		tu = p2p->cfg->max_listen * 1000 / 1024;
    293 
    294 	if (tu == 0) {
    295 		p2p_dbg(p2p, "Skip listen state since duration was 0 TU");
    296 		p2p_set_timeout(p2p, 0, 0);
    297 		return;
    298 	}
    299 
    300 	ies = p2p_build_probe_resp_ies(p2p, NULL, 0);
    301 	if (ies == NULL)
    302 		return;
    303 
    304 	p2p->pending_listen_freq = freq;
    305 	p2p->pending_listen_sec = 0;
    306 	p2p->pending_listen_usec = 1024 * tu;
    307 
    308 	if (p2p->cfg->start_listen(p2p->cfg->cb_ctx, freq, 1024 * tu / 1000,
    309 		    ies) < 0) {
    310 		p2p_dbg(p2p, "Failed to start listen mode");
    311 		p2p->pending_listen_freq = 0;
    312 	}
    313 	wpabuf_free(ies);
    314 }
    315 
    316 
    317 int p2p_listen(struct p2p_data *p2p, unsigned int timeout)
    318 {
    319 	int freq;
    320 	struct wpabuf *ies;
    321 
    322 	p2p_dbg(p2p, "Going to listen(only) state");
    323 
    324 	if (p2p->pending_listen_freq) {
    325 		/* We have a pending p2p_listen request */
    326 		p2p_dbg(p2p, "p2p_listen command pending already");
    327 		return -1;
    328 	}
    329 
    330 	freq = p2p_channel_to_freq(p2p->cfg->reg_class, p2p->cfg->channel);
    331 	if (freq < 0) {
    332 		p2p_dbg(p2p, "Unknown regulatory class/channel");
    333 		return -1;
    334 	}
    335 
    336 	p2p->pending_listen_sec = timeout / 1000;
    337 	p2p->pending_listen_usec = (timeout % 1000) * 1000;
    338 
    339 	if (p2p->p2p_scan_running) {
    340 		if (p2p->start_after_scan == P2P_AFTER_SCAN_CONNECT) {
    341 			p2p_dbg(p2p, "p2p_scan running - connect is already pending - skip listen");
    342 			return 0;
    343 		}
    344 		p2p_dbg(p2p, "p2p_scan running - delay start of listen state");
    345 		p2p->start_after_scan = P2P_AFTER_SCAN_LISTEN;
    346 		return 0;
    347 	}
    348 
    349 	ies = p2p_build_probe_resp_ies(p2p, NULL, 0);
    350 	if (ies == NULL)
    351 		return -1;
    352 
    353 	p2p->pending_listen_freq = freq;
    354 
    355 	if (p2p->cfg->start_listen(p2p->cfg->cb_ctx, freq, timeout, ies) < 0) {
    356 		p2p_dbg(p2p, "Failed to start listen mode");
    357 		p2p->pending_listen_freq = 0;
    358 		wpabuf_free(ies);
    359 		return -1;
    360 	}
    361 	wpabuf_free(ies);
    362 
    363 	p2p_set_state(p2p, P2P_LISTEN_ONLY);
    364 
    365 	return 0;
    366 }
    367 
    368 
    369 static void p2p_device_clear_reported(struct p2p_data *p2p)
    370 {
    371 	struct p2p_device *dev;
    372 	dl_list_for_each(dev, &p2p->devices, struct p2p_device, list) {
    373 		dev->flags &= ~P2P_DEV_REPORTED;
    374 		dev->sd_reqs = 0;
    375 	}
    376 }
    377 
    378 
    379 /**
    380  * p2p_get_device - Fetch a peer entry
    381  * @p2p: P2P module context from p2p_init()
    382  * @addr: P2P Device Address of the peer
    383  * Returns: Pointer to the device entry or %NULL if not found
    384  */
    385 struct p2p_device * p2p_get_device(struct p2p_data *p2p, const u8 *addr)
    386 {
    387 	struct p2p_device *dev;
    388 	dl_list_for_each(dev, &p2p->devices, struct p2p_device, list) {
    389 		if (os_memcmp(dev->info.p2p_device_addr, addr, ETH_ALEN) == 0)
    390 			return dev;
    391 	}
    392 	return NULL;
    393 }
    394 
    395 
    396 /**
    397  * p2p_get_device_interface - Fetch a peer entry based on P2P Interface Address
    398  * @p2p: P2P module context from p2p_init()
    399  * @addr: P2P Interface Address of the peer
    400  * Returns: Pointer to the device entry or %NULL if not found
    401  */
    402 struct p2p_device * p2p_get_device_interface(struct p2p_data *p2p,
    403 					     const u8 *addr)
    404 {
    405 	struct p2p_device *dev;
    406 	dl_list_for_each(dev, &p2p->devices, struct p2p_device, list) {
    407 		if (os_memcmp(dev->interface_addr, addr, ETH_ALEN) == 0)
    408 			return dev;
    409 	}
    410 	return NULL;
    411 }
    412 
    413 
    414 /**
    415  * p2p_create_device - Create a peer entry
    416  * @p2p: P2P module context from p2p_init()
    417  * @addr: P2P Device Address of the peer
    418  * Returns: Pointer to the device entry or %NULL on failure
    419  *
    420  * If there is already an entry for the peer, it will be returned instead of
    421  * creating a new one.
    422  */
    423 static struct p2p_device * p2p_create_device(struct p2p_data *p2p,
    424 					     const u8 *addr)
    425 {
    426 	struct p2p_device *dev, *oldest = NULL;
    427 	size_t count = 0;
    428 
    429 	dev = p2p_get_device(p2p, addr);
    430 	if (dev)
    431 		return dev;
    432 
    433 	dl_list_for_each(dev, &p2p->devices, struct p2p_device, list) {
    434 		count++;
    435 		if (oldest == NULL ||
    436 		    os_reltime_before(&dev->last_seen, &oldest->last_seen))
    437 			oldest = dev;
    438 	}
    439 	if (count + 1 > p2p->cfg->max_peers && oldest) {
    440 		p2p_dbg(p2p, "Remove oldest peer entry to make room for a new peer");
    441 		dl_list_del(&oldest->list);
    442 		p2p_device_free(p2p, oldest);
    443 	}
    444 
    445 	dev = os_zalloc(sizeof(*dev));
    446 	if (dev == NULL)
    447 		return NULL;
    448 	dl_list_add(&p2p->devices, &dev->list);
    449 	os_memcpy(dev->info.p2p_device_addr, addr, ETH_ALEN);
    450 
    451 	return dev;
    452 }
    453 
    454 
    455 static void p2p_copy_client_info(struct p2p_device *dev,
    456 				 struct p2p_client_info *cli)
    457 {
    458 	os_memcpy(dev->info.device_name, cli->dev_name, cli->dev_name_len);
    459 	dev->info.device_name[cli->dev_name_len] = '\0';
    460 	dev->info.dev_capab = cli->dev_capab;
    461 	dev->info.config_methods = cli->config_methods;
    462 	os_memcpy(dev->info.pri_dev_type, cli->pri_dev_type, 8);
    463 	dev->info.wps_sec_dev_type_list_len = 8 * cli->num_sec_dev_types;
    464 	os_memcpy(dev->info.wps_sec_dev_type_list, cli->sec_dev_types,
    465 		  dev->info.wps_sec_dev_type_list_len);
    466 }
    467 
    468 
    469 static int p2p_add_group_clients(struct p2p_data *p2p, const u8 *go_dev_addr,
    470 				 const u8 *go_interface_addr, int freq,
    471 				 const u8 *gi, size_t gi_len,
    472 				 struct os_reltime *rx_time)
    473 {
    474 	struct p2p_group_info info;
    475 	size_t c;
    476 	struct p2p_device *dev;
    477 
    478 	if (gi == NULL)
    479 		return 0;
    480 
    481 	if (p2p_group_info_parse(gi, gi_len, &info) < 0)
    482 		return -1;
    483 
    484 	/*
    485 	 * Clear old data for this group; if the devices are still in the
    486 	 * group, the information will be restored in the loop following this.
    487 	 */
    488 	dl_list_for_each(dev, &p2p->devices, struct p2p_device, list) {
    489 		if (os_memcmp(dev->member_in_go_iface, go_interface_addr,
    490 			      ETH_ALEN) == 0) {
    491 			os_memset(dev->member_in_go_iface, 0, ETH_ALEN);
    492 			os_memset(dev->member_in_go_dev, 0, ETH_ALEN);
    493 		}
    494 	}
    495 
    496 	for (c = 0; c < info.num_clients; c++) {
    497 		struct p2p_client_info *cli = &info.client[c];
    498 		if (os_memcmp(cli->p2p_device_addr, p2p->cfg->dev_addr,
    499 			      ETH_ALEN) == 0)
    500 			continue; /* ignore our own entry */
    501 		dev = p2p_get_device(p2p, cli->p2p_device_addr);
    502 		if (dev) {
    503 			if (dev->flags & (P2P_DEV_GROUP_CLIENT_ONLY |
    504 					  P2P_DEV_PROBE_REQ_ONLY)) {
    505 				/*
    506 				 * Update information since we have not
    507 				 * received this directly from the client.
    508 				 */
    509 				p2p_copy_client_info(dev, cli);
    510 			} else {
    511 				/*
    512 				 * Need to update P2P Client Discoverability
    513 				 * flag since it is valid only in P2P Group
    514 				 * Info attribute.
    515 				 */
    516 				dev->info.dev_capab &=
    517 					~P2P_DEV_CAPAB_CLIENT_DISCOVERABILITY;
    518 				dev->info.dev_capab |=
    519 					cli->dev_capab &
    520 					P2P_DEV_CAPAB_CLIENT_DISCOVERABILITY;
    521 			}
    522 			if (dev->flags & P2P_DEV_PROBE_REQ_ONLY) {
    523 				dev->flags &= ~P2P_DEV_PROBE_REQ_ONLY;
    524 			}
    525 		} else {
    526 			dev = p2p_create_device(p2p, cli->p2p_device_addr);
    527 			if (dev == NULL)
    528 				continue;
    529 			dev->flags |= P2P_DEV_GROUP_CLIENT_ONLY;
    530 			p2p_copy_client_info(dev, cli);
    531 			dev->oper_freq = freq;
    532 			p2p->cfg->dev_found(p2p->cfg->cb_ctx,
    533 					    dev->info.p2p_device_addr,
    534 					    &dev->info, 1);
    535 			dev->flags |= P2P_DEV_REPORTED | P2P_DEV_REPORTED_ONCE;
    536 		}
    537 
    538 		os_memcpy(dev->interface_addr, cli->p2p_interface_addr,
    539 			  ETH_ALEN);
    540 		os_memcpy(&dev->last_seen, rx_time, sizeof(struct os_reltime));
    541 		os_memcpy(dev->member_in_go_dev, go_dev_addr, ETH_ALEN);
    542 		os_memcpy(dev->member_in_go_iface, go_interface_addr,
    543 			  ETH_ALEN);
    544 		dev->flags |= P2P_DEV_LAST_SEEN_AS_GROUP_CLIENT;
    545 	}
    546 
    547 	return 0;
    548 }
    549 
    550 
    551 static void p2p_copy_wps_info(struct p2p_data *p2p, struct p2p_device *dev,
    552 			      int probe_req, const struct p2p_message *msg)
    553 {
    554 	os_memcpy(dev->info.device_name, msg->device_name,
    555 		  sizeof(dev->info.device_name));
    556 
    557 	if (msg->manufacturer &&
    558 	    msg->manufacturer_len < sizeof(dev->info.manufacturer)) {
    559 		os_memset(dev->info.manufacturer, 0,
    560 			  sizeof(dev->info.manufacturer));
    561 		os_memcpy(dev->info.manufacturer, msg->manufacturer,
    562 			  msg->manufacturer_len);
    563 	}
    564 
    565 	if (msg->model_name &&
    566 	    msg->model_name_len < sizeof(dev->info.model_name)) {
    567 		os_memset(dev->info.model_name, 0,
    568 			  sizeof(dev->info.model_name));
    569 		os_memcpy(dev->info.model_name, msg->model_name,
    570 			  msg->model_name_len);
    571 	}
    572 
    573 	if (msg->model_number &&
    574 	    msg->model_number_len < sizeof(dev->info.model_number)) {
    575 		os_memset(dev->info.model_number, 0,
    576 			  sizeof(dev->info.model_number));
    577 		os_memcpy(dev->info.model_number, msg->model_number,
    578 			  msg->model_number_len);
    579 	}
    580 
    581 	if (msg->serial_number &&
    582 	    msg->serial_number_len < sizeof(dev->info.serial_number)) {
    583 		os_memset(dev->info.serial_number, 0,
    584 			  sizeof(dev->info.serial_number));
    585 		os_memcpy(dev->info.serial_number, msg->serial_number,
    586 			  msg->serial_number_len);
    587 	}
    588 
    589 	if (msg->pri_dev_type)
    590 		os_memcpy(dev->info.pri_dev_type, msg->pri_dev_type,
    591 			  sizeof(dev->info.pri_dev_type));
    592 	else if (msg->wps_pri_dev_type)
    593 		os_memcpy(dev->info.pri_dev_type, msg->wps_pri_dev_type,
    594 			  sizeof(dev->info.pri_dev_type));
    595 
    596 	if (msg->wps_sec_dev_type_list) {
    597 		os_memcpy(dev->info.wps_sec_dev_type_list,
    598 			  msg->wps_sec_dev_type_list,
    599 			  msg->wps_sec_dev_type_list_len);
    600 		dev->info.wps_sec_dev_type_list_len =
    601 			msg->wps_sec_dev_type_list_len;
    602 	}
    603 
    604 	if (msg->capability) {
    605 		/*
    606 		 * P2P Client Discoverability bit is reserved in all frames
    607 		 * that use this function, so do not change its value here.
    608 		 */
    609 		dev->info.dev_capab &= P2P_DEV_CAPAB_CLIENT_DISCOVERABILITY;
    610 		dev->info.dev_capab |= msg->capability[0] &
    611 			~P2P_DEV_CAPAB_CLIENT_DISCOVERABILITY;
    612 		dev->info.group_capab = msg->capability[1];
    613 	}
    614 
    615 	if (msg->ext_listen_timing) {
    616 		dev->ext_listen_period = WPA_GET_LE16(msg->ext_listen_timing);
    617 		dev->ext_listen_interval =
    618 			WPA_GET_LE16(msg->ext_listen_timing + 2);
    619 	}
    620 
    621 	if (!probe_req) {
    622 		u16 new_config_methods;
    623 		new_config_methods = msg->config_methods ?
    624 			msg->config_methods : msg->wps_config_methods;
    625 		if (new_config_methods &&
    626 		    dev->info.config_methods != new_config_methods) {
    627 			p2p_dbg(p2p, "Update peer " MACSTR
    628 				" config_methods 0x%x -> 0x%x",
    629 				MAC2STR(dev->info.p2p_device_addr),
    630 				dev->info.config_methods,
    631 				new_config_methods);
    632 			dev->info.config_methods = new_config_methods;
    633 		}
    634 	}
    635 }
    636 
    637 
    638 static void p2p_update_peer_vendor_elems(struct p2p_device *dev, const u8 *ies,
    639 					 size_t ies_len)
    640 {
    641 	const u8 *pos, *end;
    642 	u8 id, len;
    643 
    644 	wpabuf_free(dev->info.vendor_elems);
    645 	dev->info.vendor_elems = NULL;
    646 
    647 	end = ies + ies_len;
    648 
    649 	for (pos = ies; pos + 1 < end; pos += len) {
    650 		id = *pos++;
    651 		len = *pos++;
    652 
    653 		if (pos + len > end)
    654 			break;
    655 
    656 		if (id != WLAN_EID_VENDOR_SPECIFIC || len < 3)
    657 			continue;
    658 
    659 		if (len >= 4) {
    660 			u32 type = WPA_GET_BE32(pos);
    661 
    662 			if (type == WPA_IE_VENDOR_TYPE ||
    663 			    type == WMM_IE_VENDOR_TYPE ||
    664 			    type == WPS_IE_VENDOR_TYPE ||
    665 			    type == P2P_IE_VENDOR_TYPE ||
    666 			    type == WFD_IE_VENDOR_TYPE)
    667 				continue;
    668 		}
    669 
    670 		/* Unknown vendor element - make raw IE data available */
    671 		if (wpabuf_resize(&dev->info.vendor_elems, 2 + len) < 0)
    672 			break;
    673 		wpabuf_put_data(dev->info.vendor_elems, pos - 2, 2 + len);
    674 	}
    675 }
    676 
    677 
    678 static int p2p_compare_wfd_info(struct p2p_device *dev,
    679 			      const struct p2p_message *msg)
    680 {
    681 	if (dev->info.wfd_subelems && msg->wfd_subelems) {
    682 		if (dev->info.wfd_subelems->used != msg->wfd_subelems->used)
    683 			return 1;
    684 
    685 		return os_memcmp(dev->info.wfd_subelems->buf,
    686 				 msg->wfd_subelems->buf,
    687 				 dev->info.wfd_subelems->used);
    688 	}
    689 	if (dev->info.wfd_subelems || msg->wfd_subelems)
    690 		return 1;
    691 
    692 	return 0;
    693 }
    694 
    695 
    696 /**
    697  * p2p_add_device - Add peer entries based on scan results or P2P frames
    698  * @p2p: P2P module context from p2p_init()
    699  * @addr: Source address of Beacon or Probe Response frame (may be either
    700  *	P2P Device Address or P2P Interface Address)
    701  * @level: Signal level (signal strength of the received frame from the peer)
    702  * @freq: Frequency on which the Beacon or Probe Response frame was received
    703  * @rx_time: Time when the result was received
    704  * @ies: IEs from the Beacon or Probe Response frame
    705  * @ies_len: Length of ies buffer in octets
    706  * @scan_res: Whether this was based on scan results
    707  * Returns: 0 on success, -1 on failure
    708  *
    709  * If the scan result is for a GO, the clients in the group will also be added
    710  * to the peer table. This function can also be used with some other frames
    711  * like Provision Discovery Request that contains P2P Capability and P2P Device
    712  * Info attributes.
    713  */
    714 int p2p_add_device(struct p2p_data *p2p, const u8 *addr, int freq,
    715 		   struct os_reltime *rx_time, int level, const u8 *ies,
    716 		   size_t ies_len, int scan_res)
    717 {
    718 	struct p2p_device *dev;
    719 	struct p2p_message msg;
    720 	const u8 *p2p_dev_addr;
    721 	int wfd_changed;
    722 	int i;
    723 	struct os_reltime time_now;
    724 
    725 	os_memset(&msg, 0, sizeof(msg));
    726 	if (p2p_parse_ies(ies, ies_len, &msg)) {
    727 		p2p_dbg(p2p, "Failed to parse P2P IE for a device entry");
    728 		p2p_parse_free(&msg);
    729 		return -1;
    730 	}
    731 
    732 	if (msg.p2p_device_addr)
    733 		p2p_dev_addr = msg.p2p_device_addr;
    734 	else if (msg.device_id)
    735 		p2p_dev_addr = msg.device_id;
    736 	else {
    737 		p2p_dbg(p2p, "Ignore scan data without P2P Device Info or P2P Device Id");
    738 		p2p_parse_free(&msg);
    739 		return -1;
    740 	}
    741 
    742 	if (!is_zero_ether_addr(p2p->peer_filter) &&
    743 	    os_memcmp(p2p_dev_addr, p2p->peer_filter, ETH_ALEN) != 0) {
    744 		p2p_dbg(p2p, "Do not add peer filter for " MACSTR
    745 			" due to peer filter", MAC2STR(p2p_dev_addr));
    746 		p2p_parse_free(&msg);
    747 		return 0;
    748 	}
    749 
    750 	dev = p2p_create_device(p2p, p2p_dev_addr);
    751 	if (dev == NULL) {
    752 		p2p_parse_free(&msg);
    753 		return -1;
    754 	}
    755 
    756 	if (rx_time == NULL) {
    757 		os_get_reltime(&time_now);
    758 		rx_time = &time_now;
    759 	}
    760 
    761 	/*
    762 	 * Update the device entry only if the new peer
    763 	 * entry is newer than the one previously stored, or if
    764 	 * the device was previously seen as a P2P Client in a group
    765 	 * and the new entry isn't older than a threshold.
    766 	 */
    767 	if (dev->last_seen.sec > 0 &&
    768 	    os_reltime_before(rx_time, &dev->last_seen) &&
    769 	    (!(dev->flags & P2P_DEV_LAST_SEEN_AS_GROUP_CLIENT) ||
    770 	     os_reltime_expired(&dev->last_seen, rx_time,
    771 				P2P_DEV_GROUP_CLIENT_RESP_THRESHOLD))) {
    772 		p2p_dbg(p2p,
    773 			"Do not update peer entry based on old frame (rx_time=%u.%06u last_seen=%u.%06u flags=0x%x)",
    774 			(unsigned int) rx_time->sec,
    775 			(unsigned int) rx_time->usec,
    776 			(unsigned int) dev->last_seen.sec,
    777 			(unsigned int) dev->last_seen.usec,
    778 			dev->flags);
    779 		p2p_parse_free(&msg);
    780 		return -1;
    781 	}
    782 
    783 	os_memcpy(&dev->last_seen, rx_time, sizeof(struct os_reltime));
    784 
    785 	dev->flags &= ~(P2P_DEV_PROBE_REQ_ONLY | P2P_DEV_GROUP_CLIENT_ONLY |
    786 			P2P_DEV_LAST_SEEN_AS_GROUP_CLIENT);
    787 
    788 	if (os_memcmp(addr, p2p_dev_addr, ETH_ALEN) != 0)
    789 		os_memcpy(dev->interface_addr, addr, ETH_ALEN);
    790 	if (msg.ssid &&
    791 	    msg.ssid[1] <= sizeof(dev->oper_ssid) &&
    792 	    (msg.ssid[1] != P2P_WILDCARD_SSID_LEN ||
    793 	     os_memcmp(msg.ssid + 2, P2P_WILDCARD_SSID, P2P_WILDCARD_SSID_LEN)
    794 	     != 0)) {
    795 		os_memcpy(dev->oper_ssid, msg.ssid + 2, msg.ssid[1]);
    796 		dev->oper_ssid_len = msg.ssid[1];
    797 	}
    798 
    799 	if (msg.adv_service_instance && msg.adv_service_instance_len) {
    800 		wpabuf_free(dev->info.p2ps_instance);
    801 		dev->info.p2ps_instance = wpabuf_alloc_copy(
    802 			msg.adv_service_instance, msg.adv_service_instance_len);
    803 	}
    804 
    805 	if (freq >= 2412 && freq <= 2484 && msg.ds_params &&
    806 	    *msg.ds_params >= 1 && *msg.ds_params <= 14) {
    807 		int ds_freq;
    808 		if (*msg.ds_params == 14)
    809 			ds_freq = 2484;
    810 		else
    811 			ds_freq = 2407 + *msg.ds_params * 5;
    812 		if (freq != ds_freq) {
    813 			p2p_dbg(p2p, "Update Listen frequency based on DS Parameter Set IE: %d -> %d MHz",
    814 				freq, ds_freq);
    815 			freq = ds_freq;
    816 		}
    817 	}
    818 
    819 	if (dev->listen_freq && dev->listen_freq != freq && scan_res) {
    820 		p2p_dbg(p2p, "Update Listen frequency based on scan results ("
    821 			MACSTR " %d -> %d MHz (DS param %d)",
    822 			MAC2STR(dev->info.p2p_device_addr), dev->listen_freq,
    823 			freq, msg.ds_params ? *msg.ds_params : -1);
    824 	}
    825 	if (scan_res) {
    826 		dev->listen_freq = freq;
    827 		if (msg.group_info)
    828 			dev->oper_freq = freq;
    829 	}
    830 	dev->info.level = level;
    831 
    832 	p2p_copy_wps_info(p2p, dev, 0, &msg);
    833 
    834 	for (i = 0; i < P2P_MAX_WPS_VENDOR_EXT; i++) {
    835 		wpabuf_free(dev->info.wps_vendor_ext[i]);
    836 		dev->info.wps_vendor_ext[i] = NULL;
    837 	}
    838 
    839 	for (i = 0; i < P2P_MAX_WPS_VENDOR_EXT; i++) {
    840 		if (msg.wps_vendor_ext[i] == NULL)
    841 			break;
    842 		dev->info.wps_vendor_ext[i] = wpabuf_alloc_copy(
    843 			msg.wps_vendor_ext[i], msg.wps_vendor_ext_len[i]);
    844 		if (dev->info.wps_vendor_ext[i] == NULL)
    845 			break;
    846 	}
    847 
    848 	wfd_changed = p2p_compare_wfd_info(dev, &msg);
    849 
    850 	if (msg.wfd_subelems) {
    851 		wpabuf_free(dev->info.wfd_subelems);
    852 		dev->info.wfd_subelems = wpabuf_dup(msg.wfd_subelems);
    853 	}
    854 
    855 	if (scan_res) {
    856 		p2p_add_group_clients(p2p, p2p_dev_addr, addr, freq,
    857 				      msg.group_info, msg.group_info_len,
    858 				      rx_time);
    859 	}
    860 
    861 	p2p_parse_free(&msg);
    862 
    863 	p2p_update_peer_vendor_elems(dev, ies, ies_len);
    864 
    865 	if (dev->flags & P2P_DEV_REPORTED && !wfd_changed &&
    866 	    (!msg.adv_service_instance ||
    867 	     (dev->flags & P2P_DEV_P2PS_REPORTED)))
    868 		return 0;
    869 
    870 	p2p_dbg(p2p, "Peer found with Listen frequency %d MHz (rx_time=%u.%06u)",
    871 		freq, (unsigned int) rx_time->sec,
    872 		(unsigned int) rx_time->usec);
    873 	if (dev->flags & P2P_DEV_USER_REJECTED) {
    874 		p2p_dbg(p2p, "Do not report rejected device");
    875 		return 0;
    876 	}
    877 
    878 	if (dev->info.config_methods == 0 &&
    879 	    (freq == 2412 || freq == 2437 || freq == 2462)) {
    880 		/*
    881 		 * If we have only seen a Beacon frame from a GO, we do not yet
    882 		 * know what WPS config methods it supports. Since some
    883 		 * applications use config_methods value from P2P-DEVICE-FOUND
    884 		 * events, postpone reporting this peer until we've fully
    885 		 * discovered its capabilities.
    886 		 *
    887 		 * At least for now, do this only if the peer was detected on
    888 		 * one of the social channels since that peer can be easily be
    889 		 * found again and there are no limitations of having to use
    890 		 * passive scan on this channels, so this can be done through
    891 		 * Probe Response frame that includes the config_methods
    892 		 * information.
    893 		 */
    894 		p2p_dbg(p2p, "Do not report peer " MACSTR
    895 			" with unknown config methods", MAC2STR(addr));
    896 		return 0;
    897 	}
    898 
    899 	p2p->cfg->dev_found(p2p->cfg->cb_ctx, addr, &dev->info,
    900 			    !(dev->flags & P2P_DEV_REPORTED_ONCE));
    901 	dev->flags |= P2P_DEV_REPORTED | P2P_DEV_REPORTED_ONCE;
    902 
    903 	if (msg.adv_service_instance)
    904 		dev->flags |= P2P_DEV_P2PS_REPORTED;
    905 
    906 	return 0;
    907 }
    908 
    909 
    910 static void p2p_device_free(struct p2p_data *p2p, struct p2p_device *dev)
    911 {
    912 	int i;
    913 
    914 	if (p2p->go_neg_peer == dev) {
    915 		/*
    916 		 * If GO Negotiation is in progress, report that it has failed.
    917 		 */
    918 		p2p_go_neg_failed(p2p, -1);
    919 	}
    920 	if (p2p->invite_peer == dev)
    921 		p2p->invite_peer = NULL;
    922 	if (p2p->sd_peer == dev)
    923 		p2p->sd_peer = NULL;
    924 	if (p2p->pending_client_disc_go == dev)
    925 		p2p->pending_client_disc_go = NULL;
    926 
    927 	/* dev_lost() device, but only if it was previously dev_found() */
    928 	if (dev->flags & P2P_DEV_REPORTED_ONCE)
    929 		p2p->cfg->dev_lost(p2p->cfg->cb_ctx,
    930 				   dev->info.p2p_device_addr);
    931 
    932 	for (i = 0; i < P2P_MAX_WPS_VENDOR_EXT; i++) {
    933 		wpabuf_free(dev->info.wps_vendor_ext[i]);
    934 		dev->info.wps_vendor_ext[i] = NULL;
    935 	}
    936 
    937 	wpabuf_free(dev->info.wfd_subelems);
    938 	wpabuf_free(dev->info.vendor_elems);
    939 	wpabuf_free(dev->go_neg_conf);
    940 	wpabuf_free(dev->info.p2ps_instance);
    941 
    942 	os_free(dev);
    943 }
    944 
    945 
    946 static int p2p_get_next_prog_freq(struct p2p_data *p2p)
    947 {
    948 	struct p2p_channels *c;
    949 	struct p2p_reg_class *cla;
    950 	size_t cl, ch;
    951 	int found = 0;
    952 	u8 reg_class;
    953 	u8 channel;
    954 	int freq;
    955 
    956 	c = &p2p->cfg->channels;
    957 	for (cl = 0; cl < c->reg_classes; cl++) {
    958 		cla = &c->reg_class[cl];
    959 		if (cla->reg_class != p2p->last_prog_scan_class)
    960 			continue;
    961 		for (ch = 0; ch < cla->channels; ch++) {
    962 			if (cla->channel[ch] == p2p->last_prog_scan_chan) {
    963 				found = 1;
    964 				break;
    965 			}
    966 		}
    967 		if (found)
    968 			break;
    969 	}
    970 
    971 	if (!found) {
    972 		/* Start from beginning */
    973 		reg_class = c->reg_class[0].reg_class;
    974 		channel = c->reg_class[0].channel[0];
    975 	} else {
    976 		/* Pick the next channel */
    977 		ch++;
    978 		if (ch == cla->channels) {
    979 			cl++;
    980 			if (cl == c->reg_classes)
    981 				cl = 0;
    982 			ch = 0;
    983 		}
    984 		reg_class = c->reg_class[cl].reg_class;
    985 		channel = c->reg_class[cl].channel[ch];
    986 	}
    987 
    988 	freq = p2p_channel_to_freq(reg_class, channel);
    989 	p2p_dbg(p2p, "Next progressive search channel: reg_class %u channel %u -> %d MHz",
    990 		reg_class, channel, freq);
    991 	p2p->last_prog_scan_class = reg_class;
    992 	p2p->last_prog_scan_chan = channel;
    993 
    994 	if (freq == 2412 || freq == 2437 || freq == 2462)
    995 		return 0; /* No need to add social channels */
    996 	return freq;
    997 }
    998 
    999 
   1000 static void p2p_search(struct p2p_data *p2p)
   1001 {
   1002 	int freq = 0;
   1003 	enum p2p_scan_type type;
   1004 	u16 pw_id = DEV_PW_DEFAULT;
   1005 	int res;
   1006 
   1007 	if (p2p->drv_in_listen) {
   1008 		p2p_dbg(p2p, "Driver is still in Listen state - wait for it to end before continuing");
   1009 		return;
   1010 	}
   1011 	p2p->cfg->stop_listen(p2p->cfg->cb_ctx);
   1012 
   1013 	if (p2p->find_type == P2P_FIND_PROGRESSIVE &&
   1014 	    (freq = p2p_get_next_prog_freq(p2p)) > 0) {
   1015 		type = P2P_SCAN_SOCIAL_PLUS_ONE;
   1016 		p2p_dbg(p2p, "Starting search (+ freq %u)", freq);
   1017 	} else {
   1018 		type = P2P_SCAN_SOCIAL;
   1019 		p2p_dbg(p2p, "Starting search");
   1020 	}
   1021 
   1022 	res = p2p->cfg->p2p_scan(p2p->cfg->cb_ctx, type, freq,
   1023 				 p2p->num_req_dev_types, p2p->req_dev_types,
   1024 				 p2p->find_dev_id, pw_id);
   1025 	if (res < 0) {
   1026 		p2p_dbg(p2p, "Scan request schedule failed");
   1027 		p2p_continue_find(p2p);
   1028 	}
   1029 }
   1030 
   1031 
   1032 static void p2p_find_timeout(void *eloop_ctx, void *timeout_ctx)
   1033 {
   1034 	struct p2p_data *p2p = eloop_ctx;
   1035 	p2p_dbg(p2p, "Find timeout -> stop");
   1036 	p2p_stop_find(p2p);
   1037 }
   1038 
   1039 
   1040 void p2p_notify_scan_trigger_status(struct p2p_data *p2p, int status)
   1041 {
   1042 	if (status != 0) {
   1043 		p2p_dbg(p2p, "Scan request failed");
   1044 		/* Do continue find even for the first p2p_find_scan */
   1045 		p2p_continue_find(p2p);
   1046 	} else {
   1047 		p2p_dbg(p2p, "Running p2p_scan");
   1048 		p2p->p2p_scan_running = 1;
   1049 		eloop_cancel_timeout(p2p_scan_timeout, p2p, NULL);
   1050 		eloop_register_timeout(P2P_SCAN_TIMEOUT, 0, p2p_scan_timeout,
   1051 				       p2p, NULL);
   1052 	}
   1053 }
   1054 
   1055 
   1056 static int p2p_run_after_scan(struct p2p_data *p2p)
   1057 {
   1058 	struct p2p_device *dev;
   1059 	enum p2p_after_scan op;
   1060 
   1061 	if (p2p->after_scan_tx) {
   1062 		p2p->after_scan_tx_in_progress = 1;
   1063 		p2p_dbg(p2p, "Send pending Action frame at p2p_scan completion");
   1064 		p2p->cfg->send_action(p2p->cfg->cb_ctx,
   1065 				      p2p->after_scan_tx->freq,
   1066 				      p2p->after_scan_tx->dst,
   1067 				      p2p->after_scan_tx->src,
   1068 				      p2p->after_scan_tx->bssid,
   1069 				      (u8 *) (p2p->after_scan_tx + 1),
   1070 				      p2p->after_scan_tx->len,
   1071 				      p2p->after_scan_tx->wait_time);
   1072 		os_free(p2p->after_scan_tx);
   1073 		p2p->after_scan_tx = NULL;
   1074 		return 1;
   1075 	}
   1076 
   1077 	op = p2p->start_after_scan;
   1078 	p2p->start_after_scan = P2P_AFTER_SCAN_NOTHING;
   1079 	switch (op) {
   1080 	case P2P_AFTER_SCAN_NOTHING:
   1081 		break;
   1082 	case P2P_AFTER_SCAN_LISTEN:
   1083 		p2p_dbg(p2p, "Start previously requested Listen state");
   1084 		p2p_listen(p2p, p2p->pending_listen_sec * 1000 +
   1085 			   p2p->pending_listen_usec / 1000);
   1086 		return 1;
   1087 	case P2P_AFTER_SCAN_CONNECT:
   1088 		p2p_dbg(p2p, "Start previously requested connect with " MACSTR,
   1089 			MAC2STR(p2p->after_scan_peer));
   1090 		dev = p2p_get_device(p2p, p2p->after_scan_peer);
   1091 		if (dev == NULL) {
   1092 			p2p_dbg(p2p, "Peer not known anymore");
   1093 			break;
   1094 		}
   1095 		p2p_connect_send(p2p, dev);
   1096 		return 1;
   1097 	}
   1098 
   1099 	return 0;
   1100 }
   1101 
   1102 
   1103 static void p2p_scan_timeout(void *eloop_ctx, void *timeout_ctx)
   1104 {
   1105 	struct p2p_data *p2p = eloop_ctx;
   1106 	int running;
   1107 	p2p_dbg(p2p, "p2p_scan timeout (running=%d)", p2p->p2p_scan_running);
   1108 	running = p2p->p2p_scan_running;
   1109 	/* Make sure we recover from missed scan results callback */
   1110 	p2p->p2p_scan_running = 0;
   1111 
   1112 	if (running)
   1113 		p2p_run_after_scan(p2p);
   1114 }
   1115 
   1116 
   1117 static void p2p_free_req_dev_types(struct p2p_data *p2p)
   1118 {
   1119 	p2p->num_req_dev_types = 0;
   1120 	os_free(p2p->req_dev_types);
   1121 	p2p->req_dev_types = NULL;
   1122 }
   1123 
   1124 
   1125 static int p2ps_gen_hash(struct p2p_data *p2p, const char *str, u8 *hash)
   1126 {
   1127 	u8 buf[SHA256_MAC_LEN];
   1128 	char str_buf[256];
   1129 	const u8 *adv_array;
   1130 	size_t i, adv_len;
   1131 
   1132 	if (!str || !hash)
   1133 		return 0;
   1134 
   1135 	if (!str[0]) {
   1136 		os_memcpy(hash, p2p->wild_card_hash, P2PS_HASH_LEN);
   1137 		return 1;
   1138 	}
   1139 
   1140 	adv_array = (u8 *) str_buf;
   1141 	adv_len = os_strlen(str);
   1142 	if (adv_len >= sizeof(str_buf))
   1143 		return 0;
   1144 
   1145 	for (i = 0; str[i] && i < adv_len; i++) {
   1146 		if (str[i] >= 'A' && str[i] <= 'Z')
   1147 			str_buf[i] = str[i] - 'A' + 'a';
   1148 		else
   1149 			str_buf[i] = str[i];
   1150 	}
   1151 
   1152 	if (sha256_vector(1, &adv_array, &adv_len, buf))
   1153 		return 0;
   1154 
   1155 	os_memcpy(hash, buf, P2PS_HASH_LEN);
   1156 	return 1;
   1157 }
   1158 
   1159 
   1160 int p2p_find(struct p2p_data *p2p, unsigned int timeout,
   1161 	     enum p2p_discovery_type type,
   1162 	     unsigned int num_req_dev_types, const u8 *req_dev_types,
   1163 	     const u8 *dev_id, unsigned int search_delay,
   1164 	     u8 seek_count, const char **seek, int freq)
   1165 {
   1166 	int res;
   1167 
   1168 	p2p_dbg(p2p, "Starting find (type=%d)", type);
   1169 	os_get_reltime(&p2p->find_start);
   1170 	if (p2p->p2p_scan_running) {
   1171 		p2p_dbg(p2p, "p2p_scan is already running");
   1172 	}
   1173 
   1174 	p2p_free_req_dev_types(p2p);
   1175 	if (req_dev_types && num_req_dev_types) {
   1176 		p2p->req_dev_types = os_malloc(num_req_dev_types *
   1177 					       WPS_DEV_TYPE_LEN);
   1178 		if (p2p->req_dev_types == NULL)
   1179 			return -1;
   1180 		os_memcpy(p2p->req_dev_types, req_dev_types,
   1181 			  num_req_dev_types * WPS_DEV_TYPE_LEN);
   1182 		p2p->num_req_dev_types = num_req_dev_types;
   1183 	}
   1184 
   1185 	if (dev_id) {
   1186 		os_memcpy(p2p->find_dev_id_buf, dev_id, ETH_ALEN);
   1187 		p2p->find_dev_id = p2p->find_dev_id_buf;
   1188 	} else
   1189 		p2p->find_dev_id = NULL;
   1190 
   1191 	if (seek_count == 0 || !seek) {
   1192 		/* Not an ASP search */
   1193 		p2p->p2ps_seek = 0;
   1194 	} else if (seek_count == 1 && seek && (!seek[0] || !seek[0][0])) {
   1195 		/*
   1196 		 * An empty seek string means no hash values, but still an ASP
   1197 		 * search.
   1198 		 */
   1199 		p2p_dbg(p2p, "ASP search");
   1200 		p2p->p2ps_seek_count = 0;
   1201 		p2p->p2ps_seek = 1;
   1202 	} else if (seek && seek_count <= P2P_MAX_QUERY_HASH) {
   1203 		u8 buf[P2PS_HASH_LEN];
   1204 		int i, count = 0;
   1205 
   1206 		for (i = 0; i < seek_count; i++) {
   1207 			if (!p2ps_gen_hash(p2p, seek[i], buf))
   1208 				continue;
   1209 
   1210 			p2p_dbg(p2p, "Seek service %s hash " MACSTR,
   1211 				seek[i], MAC2STR(buf));
   1212 			os_memcpy(&p2p->p2ps_seek_hash[count * P2PS_HASH_LEN],
   1213 				  buf, P2PS_HASH_LEN);
   1214 			count++;
   1215 		}
   1216 
   1217 		p2p->p2ps_seek_count = count;
   1218 		p2p->p2ps_seek = 1;
   1219 	} else {
   1220 		p2p->p2ps_seek_count = 0;
   1221 		p2p->p2ps_seek = 1;
   1222 	}
   1223 
   1224 	/* Special case to perform wildcard search */
   1225 	if (p2p->p2ps_seek_count == 0 && p2p->p2ps_seek) {
   1226 		p2p->p2ps_seek_count = 1;
   1227 		os_memcpy(&p2p->p2ps_seek_hash, p2p->wild_card_hash,
   1228 			  P2PS_HASH_LEN);
   1229 	}
   1230 
   1231 	p2p->start_after_scan = P2P_AFTER_SCAN_NOTHING;
   1232 	p2p_clear_timeout(p2p);
   1233 	p2p->cfg->stop_listen(p2p->cfg->cb_ctx);
   1234 	p2p->find_type = type;
   1235 	p2p_device_clear_reported(p2p);
   1236 	p2p_set_state(p2p, P2P_SEARCH);
   1237 	p2p->search_delay = search_delay;
   1238 	p2p->in_search_delay = 0;
   1239 	eloop_cancel_timeout(p2p_find_timeout, p2p, NULL);
   1240 	p2p->last_p2p_find_timeout = timeout;
   1241 	if (timeout)
   1242 		eloop_register_timeout(timeout, 0, p2p_find_timeout,
   1243 				       p2p, NULL);
   1244 	switch (type) {
   1245 	case P2P_FIND_START_WITH_FULL:
   1246 		if (freq > 0) {
   1247 			/*
   1248 			 * Start with the specified channel and then move to
   1249 			 * social channels only scans.
   1250 			 */
   1251 			res = p2p->cfg->p2p_scan(p2p->cfg->cb_ctx,
   1252 						 P2P_SCAN_SPECIFIC, freq,
   1253 						 p2p->num_req_dev_types,
   1254 						 p2p->req_dev_types, dev_id,
   1255 						 DEV_PW_DEFAULT);
   1256 			break;
   1257 		}
   1258 		/* fall through */
   1259 	case P2P_FIND_PROGRESSIVE:
   1260 		res = p2p->cfg->p2p_scan(p2p->cfg->cb_ctx, P2P_SCAN_FULL, 0,
   1261 					 p2p->num_req_dev_types,
   1262 					 p2p->req_dev_types, dev_id,
   1263 					 DEV_PW_DEFAULT);
   1264 		break;
   1265 	case P2P_FIND_ONLY_SOCIAL:
   1266 		res = p2p->cfg->p2p_scan(p2p->cfg->cb_ctx, P2P_SCAN_SOCIAL, 0,
   1267 					 p2p->num_req_dev_types,
   1268 					 p2p->req_dev_types, dev_id,
   1269 					 DEV_PW_DEFAULT);
   1270 		break;
   1271 	default:
   1272 		return -1;
   1273 	}
   1274 
   1275 	if (res != 0 && p2p->p2p_scan_running) {
   1276 		p2p_dbg(p2p, "Failed to start p2p_scan - another p2p_scan was already running");
   1277 		/* wait for the previous p2p_scan to complete */
   1278 		res = 0; /* do not report failure */
   1279 	} else if (res != 0) {
   1280 		p2p_dbg(p2p, "Failed to start p2p_scan");
   1281 		p2p_set_state(p2p, P2P_IDLE);
   1282 		eloop_cancel_timeout(p2p_find_timeout, p2p, NULL);
   1283 	}
   1284 
   1285 	return res;
   1286 }
   1287 
   1288 
   1289 void p2p_stop_find_for_freq(struct p2p_data *p2p, int freq)
   1290 {
   1291 	p2p_dbg(p2p, "Stopping find");
   1292 	eloop_cancel_timeout(p2p_find_timeout, p2p, NULL);
   1293 	p2p_clear_timeout(p2p);
   1294 	if (p2p->state == P2P_SEARCH || p2p->state == P2P_SD_DURING_FIND)
   1295 		p2p->cfg->find_stopped(p2p->cfg->cb_ctx);
   1296 
   1297 	p2p->p2ps_seek_count = 0;
   1298 
   1299 	p2p_set_state(p2p, P2P_IDLE);
   1300 	p2p_free_req_dev_types(p2p);
   1301 	p2p->start_after_scan = P2P_AFTER_SCAN_NOTHING;
   1302 	if (p2p->go_neg_peer)
   1303 		p2p->go_neg_peer->flags &= ~P2P_DEV_PEER_WAITING_RESPONSE;
   1304 	p2p->go_neg_peer = NULL;
   1305 	p2p->sd_peer = NULL;
   1306 	p2p->invite_peer = NULL;
   1307 	p2p_stop_listen_for_freq(p2p, freq);
   1308 	p2p->send_action_in_progress = 0;
   1309 }
   1310 
   1311 
   1312 void p2p_stop_listen_for_freq(struct p2p_data *p2p, int freq)
   1313 {
   1314 	if (freq > 0 && p2p->drv_in_listen == freq && p2p->in_listen) {
   1315 		p2p_dbg(p2p, "Skip stop_listen since we are on correct channel for response");
   1316 		return;
   1317 	}
   1318 	if (p2p->in_listen) {
   1319 		p2p->in_listen = 0;
   1320 		p2p_clear_timeout(p2p);
   1321 	}
   1322 	if (p2p->drv_in_listen) {
   1323 		/*
   1324 		 * The driver may not deliver callback to p2p_listen_end()
   1325 		 * when the operation gets canceled, so clear the internal
   1326 		 * variable that is tracking driver state.
   1327 		 */
   1328 		p2p_dbg(p2p, "Clear drv_in_listen (%d)", p2p->drv_in_listen);
   1329 		p2p->drv_in_listen = 0;
   1330 	}
   1331 	p2p->cfg->stop_listen(p2p->cfg->cb_ctx);
   1332 }
   1333 
   1334 
   1335 void p2p_stop_listen(struct p2p_data *p2p)
   1336 {
   1337 	if (p2p->state != P2P_LISTEN_ONLY) {
   1338 		p2p_dbg(p2p, "Skip stop_listen since not in listen_only state.");
   1339 		return;
   1340 	}
   1341 
   1342 	p2p_stop_listen_for_freq(p2p, 0);
   1343 	p2p_set_state(p2p, P2P_IDLE);
   1344 }
   1345 
   1346 
   1347 void p2p_stop_find(struct p2p_data *p2p)
   1348 {
   1349 	p2p->pending_listen_freq = 0;
   1350 	p2p_stop_find_for_freq(p2p, 0);
   1351 }
   1352 
   1353 
   1354 static int p2p_prepare_channel_pref(struct p2p_data *p2p,
   1355 				    unsigned int force_freq,
   1356 				    unsigned int pref_freq, int go)
   1357 {
   1358 	u8 op_class, op_channel;
   1359 	unsigned int freq = force_freq ? force_freq : pref_freq;
   1360 
   1361 	p2p_dbg(p2p, "Prepare channel pref - force_freq=%u pref_freq=%u go=%d",
   1362 		force_freq, pref_freq, go);
   1363 	if (p2p_freq_to_channel(freq, &op_class, &op_channel) < 0) {
   1364 		p2p_dbg(p2p, "Unsupported frequency %u MHz", freq);
   1365 		return -1;
   1366 	}
   1367 
   1368 	if (!p2p_channels_includes(&p2p->cfg->channels, op_class, op_channel) &&
   1369 	    (go || !p2p_channels_includes(&p2p->cfg->cli_channels, op_class,
   1370 					  op_channel))) {
   1371 		p2p_dbg(p2p, "Frequency %u MHz (oper_class %u channel %u) not allowed for P2P",
   1372 			freq, op_class, op_channel);
   1373 		return -1;
   1374 	}
   1375 
   1376 	p2p->op_reg_class = op_class;
   1377 	p2p->op_channel = op_channel;
   1378 
   1379 	if (force_freq) {
   1380 		p2p->channels.reg_classes = 1;
   1381 		p2p->channels.reg_class[0].channels = 1;
   1382 		p2p->channels.reg_class[0].reg_class = p2p->op_reg_class;
   1383 		p2p->channels.reg_class[0].channel[0] = p2p->op_channel;
   1384 	} else {
   1385 		os_memcpy(&p2p->channels, &p2p->cfg->channels,
   1386 			  sizeof(struct p2p_channels));
   1387 	}
   1388 
   1389 	return 0;
   1390 }
   1391 
   1392 
   1393 static void p2p_prepare_channel_best(struct p2p_data *p2p)
   1394 {
   1395 	u8 op_class, op_channel;
   1396 	const int op_classes_5ghz[] = { 124, 125, 115, 0 };
   1397 	const int op_classes_ht40[] = { 126, 127, 116, 117, 0 };
   1398 	const int op_classes_vht[] = { 128, 0 };
   1399 
   1400 	p2p_dbg(p2p, "Prepare channel best");
   1401 
   1402 	if (!p2p->cfg->cfg_op_channel && p2p->best_freq_overall > 0 &&
   1403 	    p2p_supported_freq(p2p, p2p->best_freq_overall) &&
   1404 	    p2p_freq_to_channel(p2p->best_freq_overall, &op_class, &op_channel)
   1405 	    == 0) {
   1406 		p2p_dbg(p2p, "Select best overall channel as operating channel preference");
   1407 		p2p->op_reg_class = op_class;
   1408 		p2p->op_channel = op_channel;
   1409 	} else if (!p2p->cfg->cfg_op_channel && p2p->best_freq_5 > 0 &&
   1410 		   p2p_supported_freq(p2p, p2p->best_freq_5) &&
   1411 		   p2p_freq_to_channel(p2p->best_freq_5, &op_class, &op_channel)
   1412 		   == 0) {
   1413 		p2p_dbg(p2p, "Select best 5 GHz channel as operating channel preference");
   1414 		p2p->op_reg_class = op_class;
   1415 		p2p->op_channel = op_channel;
   1416 	} else if (!p2p->cfg->cfg_op_channel && p2p->best_freq_24 > 0 &&
   1417 		   p2p_supported_freq(p2p, p2p->best_freq_24) &&
   1418 		   p2p_freq_to_channel(p2p->best_freq_24, &op_class,
   1419 				       &op_channel) == 0) {
   1420 		p2p_dbg(p2p, "Select best 2.4 GHz channel as operating channel preference");
   1421 		p2p->op_reg_class = op_class;
   1422 		p2p->op_channel = op_channel;
   1423 	} else if (p2p->cfg->num_pref_chan > 0 &&
   1424 		   p2p_channels_includes(&p2p->cfg->channels,
   1425 					 p2p->cfg->pref_chan[0].op_class,
   1426 					 p2p->cfg->pref_chan[0].chan)) {
   1427 		p2p_dbg(p2p, "Select first pref_chan entry as operating channel preference");
   1428 		p2p->op_reg_class = p2p->cfg->pref_chan[0].op_class;
   1429 		p2p->op_channel = p2p->cfg->pref_chan[0].chan;
   1430 	} else if (p2p_channel_select(&p2p->cfg->channels, op_classes_vht,
   1431 				      &p2p->op_reg_class, &p2p->op_channel) ==
   1432 		   0) {
   1433 		p2p_dbg(p2p, "Select possible VHT channel (op_class %u channel %u) as operating channel preference",
   1434 			p2p->op_reg_class, p2p->op_channel);
   1435 	} else if (p2p_channel_select(&p2p->cfg->channels, op_classes_ht40,
   1436 				      &p2p->op_reg_class, &p2p->op_channel) ==
   1437 		   0) {
   1438 		p2p_dbg(p2p, "Select possible HT40 channel (op_class %u channel %u) as operating channel preference",
   1439 			p2p->op_reg_class, p2p->op_channel);
   1440 	} else if (p2p_channel_select(&p2p->cfg->channels, op_classes_5ghz,
   1441 				      &p2p->op_reg_class, &p2p->op_channel) ==
   1442 		   0) {
   1443 		p2p_dbg(p2p, "Select possible 5 GHz channel (op_class %u channel %u) as operating channel preference",
   1444 			p2p->op_reg_class, p2p->op_channel);
   1445 	} else if (p2p_channels_includes(&p2p->cfg->channels,
   1446 					 p2p->cfg->op_reg_class,
   1447 					 p2p->cfg->op_channel)) {
   1448 		p2p_dbg(p2p, "Select pre-configured channel as operating channel preference");
   1449 		p2p->op_reg_class = p2p->cfg->op_reg_class;
   1450 		p2p->op_channel = p2p->cfg->op_channel;
   1451 	} else if (p2p_channel_random_social(&p2p->cfg->channels,
   1452 					     &p2p->op_reg_class,
   1453 					     &p2p->op_channel) == 0) {
   1454 		p2p_dbg(p2p, "Select random available social channel (op_class %u channel %u) as operating channel preference",
   1455 			p2p->op_reg_class, p2p->op_channel);
   1456 	} else {
   1457 		/* Select any random available channel from the first available
   1458 		 * operating class */
   1459 		p2p_channel_select(&p2p->cfg->channels, NULL,
   1460 				   &p2p->op_reg_class,
   1461 				   &p2p->op_channel);
   1462 		p2p_dbg(p2p, "Select random available channel %d from operating class %d as operating channel preference",
   1463 			p2p->op_channel, p2p->op_reg_class);
   1464 	}
   1465 
   1466 	os_memcpy(&p2p->channels, &p2p->cfg->channels,
   1467 		  sizeof(struct p2p_channels));
   1468 }
   1469 
   1470 
   1471 /**
   1472  * p2p_prepare_channel - Select operating channel for GO Negotiation
   1473  * @p2p: P2P module context from p2p_init()
   1474  * @dev: Selected peer device
   1475  * @force_freq: Forced frequency in MHz or 0 if not forced
   1476  * @pref_freq: Preferred frequency in MHz or 0 if no preference
   1477  * @go: Whether the local end will be forced to be GO
   1478  * Returns: 0 on success, -1 on failure (channel not supported for P2P)
   1479  *
   1480  * This function is used to do initial operating channel selection for GO
   1481  * Negotiation prior to having received peer information. The selected channel
   1482  * may be further optimized in p2p_reselect_channel() once the peer information
   1483  * is available.
   1484  */
   1485 int p2p_prepare_channel(struct p2p_data *p2p, struct p2p_device *dev,
   1486 			unsigned int force_freq, unsigned int pref_freq, int go)
   1487 {
   1488 	p2p_dbg(p2p, "Prepare channel - force_freq=%u pref_freq=%u go=%d",
   1489 		force_freq, pref_freq, go);
   1490 	if (force_freq || pref_freq) {
   1491 		if (p2p_prepare_channel_pref(p2p, force_freq, pref_freq, go) <
   1492 		    0)
   1493 			return -1;
   1494 	} else {
   1495 		p2p_prepare_channel_best(p2p);
   1496 	}
   1497 	p2p_channels_dump(p2p, "prepared channels", &p2p->channels);
   1498 	if (go)
   1499 		p2p_channels_remove_freqs(&p2p->channels, &p2p->no_go_freq);
   1500 	else if (!force_freq)
   1501 		p2p_channels_union_inplace(&p2p->channels,
   1502 					   &p2p->cfg->cli_channels);
   1503 	p2p_channels_dump(p2p, "after go/cli filter/add", &p2p->channels);
   1504 
   1505 	p2p_dbg(p2p, "Own preference for operation channel: Operating Class %u Channel %u%s",
   1506 		p2p->op_reg_class, p2p->op_channel,
   1507 		force_freq ? " (forced)" : "");
   1508 
   1509 	if (force_freq)
   1510 		dev->flags |= P2P_DEV_FORCE_FREQ;
   1511 	else
   1512 		dev->flags &= ~P2P_DEV_FORCE_FREQ;
   1513 
   1514 	return 0;
   1515 }
   1516 
   1517 
   1518 static void p2p_set_dev_persistent(struct p2p_device *dev,
   1519 				   int persistent_group)
   1520 {
   1521 	switch (persistent_group) {
   1522 	case 0:
   1523 		dev->flags &= ~(P2P_DEV_PREFER_PERSISTENT_GROUP |
   1524 				P2P_DEV_PREFER_PERSISTENT_RECONN);
   1525 		break;
   1526 	case 1:
   1527 		dev->flags |= P2P_DEV_PREFER_PERSISTENT_GROUP;
   1528 		dev->flags &= ~P2P_DEV_PREFER_PERSISTENT_RECONN;
   1529 		break;
   1530 	case 2:
   1531 		dev->flags |= P2P_DEV_PREFER_PERSISTENT_GROUP |
   1532 			P2P_DEV_PREFER_PERSISTENT_RECONN;
   1533 		break;
   1534 	}
   1535 }
   1536 
   1537 
   1538 int p2p_connect(struct p2p_data *p2p, const u8 *peer_addr,
   1539 		enum p2p_wps_method wps_method,
   1540 		int go_intent, const u8 *own_interface_addr,
   1541 		unsigned int force_freq, int persistent_group,
   1542 		const u8 *force_ssid, size_t force_ssid_len,
   1543 		int pd_before_go_neg, unsigned int pref_freq, u16 oob_pw_id)
   1544 {
   1545 	struct p2p_device *dev;
   1546 
   1547 	p2p_dbg(p2p, "Request to start group negotiation - peer=" MACSTR
   1548 		"  GO Intent=%d  Intended Interface Address=" MACSTR
   1549 		" wps_method=%d persistent_group=%d pd_before_go_neg=%d "
   1550 		"oob_pw_id=%u",
   1551 		MAC2STR(peer_addr), go_intent, MAC2STR(own_interface_addr),
   1552 		wps_method, persistent_group, pd_before_go_neg, oob_pw_id);
   1553 
   1554 	dev = p2p_get_device(p2p, peer_addr);
   1555 	if (dev == NULL || (dev->flags & P2P_DEV_PROBE_REQ_ONLY)) {
   1556 		p2p_dbg(p2p, "Cannot connect to unknown P2P Device " MACSTR,
   1557 			MAC2STR(peer_addr));
   1558 		return -1;
   1559 	}
   1560 
   1561 	if (p2p_prepare_channel(p2p, dev, force_freq, pref_freq,
   1562 				go_intent == 15) < 0)
   1563 		return -1;
   1564 
   1565 	if (dev->flags & P2P_DEV_GROUP_CLIENT_ONLY) {
   1566 		if (!(dev->info.dev_capab &
   1567 		      P2P_DEV_CAPAB_CLIENT_DISCOVERABILITY)) {
   1568 			p2p_dbg(p2p, "Cannot connect to P2P Device " MACSTR
   1569 				" that is in a group and is not discoverable",
   1570 				MAC2STR(peer_addr));
   1571 			return -1;
   1572 		}
   1573 		if (dev->oper_freq <= 0) {
   1574 			p2p_dbg(p2p, "Cannot connect to P2P Device " MACSTR
   1575 				" with incomplete information",
   1576 				MAC2STR(peer_addr));
   1577 			return -1;
   1578 		}
   1579 
   1580 		/*
   1581 		 * First, try to connect directly. If the peer does not
   1582 		 * acknowledge frames, assume it is sleeping and use device
   1583 		 * discoverability via the GO at that point.
   1584 		 */
   1585 	}
   1586 
   1587 	p2p->ssid_set = 0;
   1588 	if (force_ssid) {
   1589 		wpa_hexdump_ascii(MSG_DEBUG, "P2P: Forced SSID",
   1590 				  force_ssid, force_ssid_len);
   1591 		os_memcpy(p2p->ssid, force_ssid, force_ssid_len);
   1592 		p2p->ssid_len = force_ssid_len;
   1593 		p2p->ssid_set = 1;
   1594 	}
   1595 
   1596 	dev->flags &= ~P2P_DEV_NOT_YET_READY;
   1597 	dev->flags &= ~P2P_DEV_USER_REJECTED;
   1598 	dev->flags &= ~P2P_DEV_WAIT_GO_NEG_RESPONSE;
   1599 	dev->flags &= ~P2P_DEV_WAIT_GO_NEG_CONFIRM;
   1600 	if (pd_before_go_neg)
   1601 		dev->flags |= P2P_DEV_PD_BEFORE_GO_NEG;
   1602 	else {
   1603 		dev->flags &= ~P2P_DEV_PD_BEFORE_GO_NEG;
   1604 		/*
   1605 		 * Assign dialog token and tie breaker here to use the same
   1606 		 * values in each retry within the same GO Negotiation exchange.
   1607 		 */
   1608 		dev->dialog_token++;
   1609 		if (dev->dialog_token == 0)
   1610 			dev->dialog_token = 1;
   1611 		dev->tie_breaker = p2p->next_tie_breaker;
   1612 		p2p->next_tie_breaker = !p2p->next_tie_breaker;
   1613 	}
   1614 	dev->connect_reqs = 0;
   1615 	dev->go_neg_req_sent = 0;
   1616 	dev->go_state = UNKNOWN_GO;
   1617 	p2p_set_dev_persistent(dev, persistent_group);
   1618 	p2p->go_intent = go_intent;
   1619 	os_memcpy(p2p->intended_addr, own_interface_addr, ETH_ALEN);
   1620 
   1621 	if (p2p->state != P2P_IDLE)
   1622 		p2p_stop_find(p2p);
   1623 
   1624 	if (p2p->after_scan_tx) {
   1625 		/*
   1626 		 * We need to drop the pending frame to avoid issues with the
   1627 		 * new GO Negotiation, e.g., when the pending frame was from a
   1628 		 * previous attempt at starting a GO Negotiation.
   1629 		 */
   1630 		p2p_dbg(p2p, "Dropped previous pending Action frame TX that was waiting for p2p_scan completion");
   1631 		os_free(p2p->after_scan_tx);
   1632 		p2p->after_scan_tx = NULL;
   1633 	}
   1634 
   1635 	dev->wps_method = wps_method;
   1636 	dev->oob_pw_id = oob_pw_id;
   1637 	dev->status = P2P_SC_SUCCESS;
   1638 
   1639 	if (p2p->p2p_scan_running) {
   1640 		p2p_dbg(p2p, "p2p_scan running - delay connect send");
   1641 		p2p->start_after_scan = P2P_AFTER_SCAN_CONNECT;
   1642 		os_memcpy(p2p->after_scan_peer, peer_addr, ETH_ALEN);
   1643 		return 0;
   1644 	}
   1645 	p2p->start_after_scan = P2P_AFTER_SCAN_NOTHING;
   1646 
   1647 	return p2p_connect_send(p2p, dev);
   1648 }
   1649 
   1650 
   1651 int p2p_authorize(struct p2p_data *p2p, const u8 *peer_addr,
   1652 		  enum p2p_wps_method wps_method,
   1653 		  int go_intent, const u8 *own_interface_addr,
   1654 		  unsigned int force_freq, int persistent_group,
   1655 		  const u8 *force_ssid, size_t force_ssid_len,
   1656 		  unsigned int pref_freq, u16 oob_pw_id)
   1657 {
   1658 	struct p2p_device *dev;
   1659 
   1660 	p2p_dbg(p2p, "Request to authorize group negotiation - peer=" MACSTR
   1661 		"  GO Intent=%d  Intended Interface Address=" MACSTR
   1662 		" wps_method=%d  persistent_group=%d oob_pw_id=%u",
   1663 		MAC2STR(peer_addr), go_intent, MAC2STR(own_interface_addr),
   1664 		wps_method, persistent_group, oob_pw_id);
   1665 
   1666 	dev = p2p_get_device(p2p, peer_addr);
   1667 	if (dev == NULL) {
   1668 		p2p_dbg(p2p, "Cannot authorize unknown P2P Device " MACSTR,
   1669 			MAC2STR(peer_addr));
   1670 		return -1;
   1671 	}
   1672 
   1673 	if (p2p_prepare_channel(p2p, dev, force_freq, pref_freq, go_intent ==
   1674 				15) < 0)
   1675 		return -1;
   1676 
   1677 	p2p->ssid_set = 0;
   1678 	if (force_ssid) {
   1679 		wpa_hexdump_ascii(MSG_DEBUG, "P2P: Forced SSID",
   1680 				  force_ssid, force_ssid_len);
   1681 		os_memcpy(p2p->ssid, force_ssid, force_ssid_len);
   1682 		p2p->ssid_len = force_ssid_len;
   1683 		p2p->ssid_set = 1;
   1684 	}
   1685 
   1686 	dev->flags &= ~P2P_DEV_NOT_YET_READY;
   1687 	dev->flags &= ~P2P_DEV_USER_REJECTED;
   1688 	dev->go_neg_req_sent = 0;
   1689 	dev->go_state = UNKNOWN_GO;
   1690 	p2p_set_dev_persistent(dev, persistent_group);
   1691 	p2p->go_intent = go_intent;
   1692 	os_memcpy(p2p->intended_addr, own_interface_addr, ETH_ALEN);
   1693 
   1694 	dev->wps_method = wps_method;
   1695 	dev->oob_pw_id = oob_pw_id;
   1696 	dev->status = P2P_SC_SUCCESS;
   1697 
   1698 	return 0;
   1699 }
   1700 
   1701 
   1702 void p2p_add_dev_info(struct p2p_data *p2p, const u8 *addr,
   1703 		      struct p2p_device *dev, struct p2p_message *msg)
   1704 {
   1705 	os_get_reltime(&dev->last_seen);
   1706 
   1707 	p2p_copy_wps_info(p2p, dev, 0, msg);
   1708 
   1709 	if (msg->listen_channel) {
   1710 		int freq;
   1711 		freq = p2p_channel_to_freq(msg->listen_channel[3],
   1712 					   msg->listen_channel[4]);
   1713 		if (freq < 0) {
   1714 			p2p_dbg(p2p, "Unknown peer Listen channel: "
   1715 				"country=%c%c(0x%02x) reg_class=%u channel=%u",
   1716 				msg->listen_channel[0],
   1717 				msg->listen_channel[1],
   1718 				msg->listen_channel[2],
   1719 				msg->listen_channel[3],
   1720 				msg->listen_channel[4]);
   1721 		} else {
   1722 			p2p_dbg(p2p, "Update peer " MACSTR
   1723 				" Listen channel: %u -> %u MHz",
   1724 				MAC2STR(dev->info.p2p_device_addr),
   1725 				dev->listen_freq, freq);
   1726 			dev->listen_freq = freq;
   1727 		}
   1728 	}
   1729 
   1730 	if (msg->wfd_subelems) {
   1731 		wpabuf_free(dev->info.wfd_subelems);
   1732 		dev->info.wfd_subelems = wpabuf_dup(msg->wfd_subelems);
   1733 	}
   1734 
   1735 	if (dev->flags & P2P_DEV_PROBE_REQ_ONLY) {
   1736 		dev->flags &= ~P2P_DEV_PROBE_REQ_ONLY;
   1737 		p2p_dbg(p2p, "Completed device entry based on data from GO Negotiation Request");
   1738 	} else {
   1739 		p2p_dbg(p2p, "Created device entry based on GO Neg Req: "
   1740 			MACSTR " dev_capab=0x%x group_capab=0x%x name='%s' "
   1741 			"listen_freq=%d",
   1742 			MAC2STR(dev->info.p2p_device_addr),
   1743 			dev->info.dev_capab, dev->info.group_capab,
   1744 			dev->info.device_name, dev->listen_freq);
   1745 	}
   1746 
   1747 	dev->flags &= ~P2P_DEV_GROUP_CLIENT_ONLY;
   1748 
   1749 	if (dev->flags & P2P_DEV_USER_REJECTED) {
   1750 		p2p_dbg(p2p, "Do not report rejected device");
   1751 		return;
   1752 	}
   1753 
   1754 	p2p->cfg->dev_found(p2p->cfg->cb_ctx, addr, &dev->info,
   1755 			    !(dev->flags & P2P_DEV_REPORTED_ONCE));
   1756 	dev->flags |= P2P_DEV_REPORTED | P2P_DEV_REPORTED_ONCE;
   1757 }
   1758 
   1759 
   1760 void p2p_build_ssid(struct p2p_data *p2p, u8 *ssid, size_t *ssid_len)
   1761 {
   1762 	os_memcpy(ssid, P2P_WILDCARD_SSID, P2P_WILDCARD_SSID_LEN);
   1763 	p2p_random((char *) &ssid[P2P_WILDCARD_SSID_LEN], 2);
   1764 	os_memcpy(&ssid[P2P_WILDCARD_SSID_LEN + 2],
   1765 		  p2p->cfg->ssid_postfix, p2p->cfg->ssid_postfix_len);
   1766 	*ssid_len = P2P_WILDCARD_SSID_LEN + 2 + p2p->cfg->ssid_postfix_len;
   1767 }
   1768 
   1769 
   1770 int p2p_go_params(struct p2p_data *p2p, struct p2p_go_neg_results *params)
   1771 {
   1772 	if (p2p->ssid_set) {
   1773 		os_memcpy(params->ssid, p2p->ssid, p2p->ssid_len);
   1774 		params->ssid_len = p2p->ssid_len;
   1775 	} else {
   1776 		p2p_build_ssid(p2p, params->ssid, &params->ssid_len);
   1777 	}
   1778 	p2p->ssid_set = 0;
   1779 
   1780 	p2p_random(params->passphrase, p2p->cfg->passphrase_len);
   1781 	return 0;
   1782 }
   1783 
   1784 
   1785 void p2p_go_complete(struct p2p_data *p2p, struct p2p_device *peer)
   1786 {
   1787 	struct p2p_go_neg_results res;
   1788 	int go = peer->go_state == LOCAL_GO;
   1789 	struct p2p_channels intersection;
   1790 
   1791 	p2p_dbg(p2p, "GO Negotiation with " MACSTR " completed (%s will be GO)",
   1792 		MAC2STR(peer->info.p2p_device_addr), go ? "local end" : "peer");
   1793 
   1794 	os_memset(&res, 0, sizeof(res));
   1795 	res.role_go = go;
   1796 	os_memcpy(res.peer_device_addr, peer->info.p2p_device_addr, ETH_ALEN);
   1797 	os_memcpy(res.peer_interface_addr, peer->intended_addr, ETH_ALEN);
   1798 	res.wps_method = peer->wps_method;
   1799 	if (peer->flags & P2P_DEV_PREFER_PERSISTENT_GROUP) {
   1800 		if (peer->flags & P2P_DEV_PREFER_PERSISTENT_RECONN)
   1801 			res.persistent_group = 2;
   1802 		else
   1803 			res.persistent_group = 1;
   1804 	}
   1805 
   1806 	if (go) {
   1807 		/* Setup AP mode for WPS provisioning */
   1808 		res.freq = p2p_channel_to_freq(p2p->op_reg_class,
   1809 					       p2p->op_channel);
   1810 		os_memcpy(res.ssid, p2p->ssid, p2p->ssid_len);
   1811 		res.ssid_len = p2p->ssid_len;
   1812 		p2p_random(res.passphrase, p2p->cfg->passphrase_len);
   1813 	} else {
   1814 		res.freq = peer->oper_freq;
   1815 		if (p2p->ssid_len) {
   1816 			os_memcpy(res.ssid, p2p->ssid, p2p->ssid_len);
   1817 			res.ssid_len = p2p->ssid_len;
   1818 		}
   1819 	}
   1820 
   1821 	p2p_channels_dump(p2p, "own channels", &p2p->channels);
   1822 	p2p_channels_dump(p2p, "peer channels", &peer->channels);
   1823 	p2p_channels_intersect(&p2p->channels, &peer->channels,
   1824 			       &intersection);
   1825 	if (go) {
   1826 		p2p_channels_remove_freqs(&intersection, &p2p->no_go_freq);
   1827 		p2p_channels_dump(p2p, "intersection after no-GO removal",
   1828 				  &intersection);
   1829 	}
   1830 
   1831 	p2p_channels_to_freqs(&intersection, res.freq_list,
   1832 			      P2P_MAX_CHANNELS);
   1833 
   1834 	res.peer_config_timeout = go ? peer->client_timeout : peer->go_timeout;
   1835 
   1836 	p2p_clear_timeout(p2p);
   1837 	p2p->ssid_set = 0;
   1838 	peer->go_neg_req_sent = 0;
   1839 	peer->wps_method = WPS_NOT_READY;
   1840 	peer->oob_pw_id = 0;
   1841 	wpabuf_free(peer->go_neg_conf);
   1842 	peer->go_neg_conf = NULL;
   1843 
   1844 	p2p_set_state(p2p, P2P_PROVISIONING);
   1845 	p2p->cfg->go_neg_completed(p2p->cfg->cb_ctx, &res);
   1846 }
   1847 
   1848 
   1849 static void p2p_rx_p2p_action(struct p2p_data *p2p, const u8 *sa,
   1850 			      const u8 *data, size_t len, int rx_freq)
   1851 {
   1852 	p2p_dbg(p2p, "RX P2P Public Action from " MACSTR, MAC2STR(sa));
   1853 	wpa_hexdump(MSG_MSGDUMP, "P2P: P2P Public Action contents", data, len);
   1854 
   1855 	if (len < 1)
   1856 		return;
   1857 
   1858 	switch (data[0]) {
   1859 	case P2P_GO_NEG_REQ:
   1860 		p2p_process_go_neg_req(p2p, sa, data + 1, len - 1, rx_freq);
   1861 		break;
   1862 	case P2P_GO_NEG_RESP:
   1863 		p2p_process_go_neg_resp(p2p, sa, data + 1, len - 1, rx_freq);
   1864 		break;
   1865 	case P2P_GO_NEG_CONF:
   1866 		p2p_process_go_neg_conf(p2p, sa, data + 1, len - 1);
   1867 		break;
   1868 	case P2P_INVITATION_REQ:
   1869 		p2p_process_invitation_req(p2p, sa, data + 1, len - 1,
   1870 					   rx_freq);
   1871 		break;
   1872 	case P2P_INVITATION_RESP:
   1873 		p2p_process_invitation_resp(p2p, sa, data + 1, len - 1);
   1874 		break;
   1875 	case P2P_PROV_DISC_REQ:
   1876 		p2p_process_prov_disc_req(p2p, sa, data + 1, len - 1, rx_freq);
   1877 		break;
   1878 	case P2P_PROV_DISC_RESP:
   1879 		p2p_process_prov_disc_resp(p2p, sa, data + 1, len - 1);
   1880 		break;
   1881 	case P2P_DEV_DISC_REQ:
   1882 		p2p_process_dev_disc_req(p2p, sa, data + 1, len - 1, rx_freq);
   1883 		break;
   1884 	case P2P_DEV_DISC_RESP:
   1885 		p2p_process_dev_disc_resp(p2p, sa, data + 1, len - 1);
   1886 		break;
   1887 	default:
   1888 		p2p_dbg(p2p, "Unsupported P2P Public Action frame type %d",
   1889 			data[0]);
   1890 		break;
   1891 	}
   1892 }
   1893 
   1894 
   1895 static void p2p_rx_action_public(struct p2p_data *p2p, const u8 *da,
   1896 				 const u8 *sa, const u8 *bssid, const u8 *data,
   1897 				 size_t len, int freq)
   1898 {
   1899 	if (len < 1)
   1900 		return;
   1901 
   1902 	switch (data[0]) {
   1903 	case WLAN_PA_VENDOR_SPECIFIC:
   1904 		data++;
   1905 		len--;
   1906 		if (len < 4)
   1907 			return;
   1908 		if (WPA_GET_BE32(data) != P2P_IE_VENDOR_TYPE)
   1909 			return;
   1910 
   1911 		data += 4;
   1912 		len -= 4;
   1913 
   1914 		p2p_rx_p2p_action(p2p, sa, data, len, freq);
   1915 		break;
   1916 	case WLAN_PA_GAS_INITIAL_REQ:
   1917 		p2p_rx_gas_initial_req(p2p, sa, data + 1, len - 1, freq);
   1918 		break;
   1919 	case WLAN_PA_GAS_INITIAL_RESP:
   1920 		p2p_rx_gas_initial_resp(p2p, sa, data + 1, len - 1, freq);
   1921 		break;
   1922 	case WLAN_PA_GAS_COMEBACK_REQ:
   1923 		p2p_rx_gas_comeback_req(p2p, sa, data + 1, len - 1, freq);
   1924 		break;
   1925 	case WLAN_PA_GAS_COMEBACK_RESP:
   1926 		p2p_rx_gas_comeback_resp(p2p, sa, data + 1, len - 1, freq);
   1927 		break;
   1928 	}
   1929 }
   1930 
   1931 
   1932 void p2p_rx_action(struct p2p_data *p2p, const u8 *da, const u8 *sa,
   1933 		   const u8 *bssid, u8 category,
   1934 		   const u8 *data, size_t len, int freq)
   1935 {
   1936 	if (category == WLAN_ACTION_PUBLIC) {
   1937 		p2p_rx_action_public(p2p, da, sa, bssid, data, len, freq);
   1938 		return;
   1939 	}
   1940 
   1941 	if (category != WLAN_ACTION_VENDOR_SPECIFIC)
   1942 		return;
   1943 
   1944 	if (len < 4)
   1945 		return;
   1946 
   1947 	if (WPA_GET_BE32(data) != P2P_IE_VENDOR_TYPE)
   1948 		return;
   1949 	data += 4;
   1950 	len -= 4;
   1951 
   1952 	/* P2P action frame */
   1953 	p2p_dbg(p2p, "RX P2P Action from " MACSTR, MAC2STR(sa));
   1954 	wpa_hexdump(MSG_MSGDUMP, "P2P: P2P Action contents", data, len);
   1955 
   1956 	if (len < 1)
   1957 		return;
   1958 	switch (data[0]) {
   1959 	case P2P_NOA:
   1960 		p2p_dbg(p2p, "Received P2P Action - Notice of Absence");
   1961 		/* TODO */
   1962 		break;
   1963 	case P2P_PRESENCE_REQ:
   1964 		p2p_process_presence_req(p2p, da, sa, data + 1, len - 1, freq);
   1965 		break;
   1966 	case P2P_PRESENCE_RESP:
   1967 		p2p_process_presence_resp(p2p, da, sa, data + 1, len - 1);
   1968 		break;
   1969 	case P2P_GO_DISC_REQ:
   1970 		p2p_process_go_disc_req(p2p, da, sa, data + 1, len - 1, freq);
   1971 		break;
   1972 	default:
   1973 		p2p_dbg(p2p, "Received P2P Action - unknown type %u", data[0]);
   1974 		break;
   1975 	}
   1976 }
   1977 
   1978 
   1979 static void p2p_go_neg_start(void *eloop_ctx, void *timeout_ctx)
   1980 {
   1981 	struct p2p_data *p2p = eloop_ctx;
   1982 	if (p2p->go_neg_peer == NULL)
   1983 		return;
   1984 	if (p2p->pending_listen_freq) {
   1985 		p2p_dbg(p2p, "Clear pending_listen_freq for p2p_go_neg_start");
   1986 		p2p->pending_listen_freq = 0;
   1987 	}
   1988 	p2p->cfg->stop_listen(p2p->cfg->cb_ctx);
   1989 	p2p->go_neg_peer->status = P2P_SC_SUCCESS;
   1990 	/*
   1991 	 * Set new timeout to make sure a previously set one does not expire
   1992 	 * too quickly while waiting for the GO Negotiation to complete.
   1993 	 */
   1994 	p2p_set_timeout(p2p, 0, 500000);
   1995 	p2p_connect_send(p2p, p2p->go_neg_peer);
   1996 }
   1997 
   1998 
   1999 static void p2p_invite_start(void *eloop_ctx, void *timeout_ctx)
   2000 {
   2001 	struct p2p_data *p2p = eloop_ctx;
   2002 	if (p2p->invite_peer == NULL)
   2003 		return;
   2004 	if (p2p->pending_listen_freq) {
   2005 		p2p_dbg(p2p, "Clear pending_listen_freq for p2p_invite_start");
   2006 		p2p->pending_listen_freq = 0;
   2007 	}
   2008 	p2p->cfg->stop_listen(p2p->cfg->cb_ctx);
   2009 	p2p_invite_send(p2p, p2p->invite_peer, p2p->invite_go_dev_addr,
   2010 			p2p->invite_dev_pw_id);
   2011 }
   2012 
   2013 
   2014 static void p2p_add_dev_from_probe_req(struct p2p_data *p2p, const u8 *addr,
   2015 				       const u8 *ie, size_t ie_len)
   2016 {
   2017 	struct p2p_message msg;
   2018 	struct p2p_device *dev;
   2019 
   2020 	os_memset(&msg, 0, sizeof(msg));
   2021 	if (p2p_parse_ies(ie, ie_len, &msg) < 0 || msg.p2p_attributes == NULL)
   2022 	{
   2023 		p2p_parse_free(&msg);
   2024 		return; /* not a P2P probe */
   2025 	}
   2026 
   2027 	if (msg.ssid == NULL || msg.ssid[1] != P2P_WILDCARD_SSID_LEN ||
   2028 	    os_memcmp(msg.ssid + 2, P2P_WILDCARD_SSID, P2P_WILDCARD_SSID_LEN)
   2029 	    != 0) {
   2030 		/* The Probe Request is not part of P2P Device Discovery. It is
   2031 		 * not known whether the source address of the frame is the P2P
   2032 		 * Device Address or P2P Interface Address. Do not add a new
   2033 		 * peer entry based on this frames.
   2034 		 */
   2035 		p2p_parse_free(&msg);
   2036 		return;
   2037 	}
   2038 
   2039 	dev = p2p_get_device(p2p, addr);
   2040 	if (dev) {
   2041 		if (dev->country[0] == 0 && msg.listen_channel)
   2042 			os_memcpy(dev->country, msg.listen_channel, 3);
   2043 		os_get_reltime(&dev->last_seen);
   2044 		p2p_parse_free(&msg);
   2045 		return; /* already known */
   2046 	}
   2047 
   2048 	dev = p2p_create_device(p2p, addr);
   2049 	if (dev == NULL) {
   2050 		p2p_parse_free(&msg);
   2051 		return;
   2052 	}
   2053 
   2054 	os_get_reltime(&dev->last_seen);
   2055 	dev->flags |= P2P_DEV_PROBE_REQ_ONLY;
   2056 
   2057 	if (msg.listen_channel) {
   2058 		os_memcpy(dev->country, msg.listen_channel, 3);
   2059 		dev->listen_freq = p2p_channel_to_freq(msg.listen_channel[3],
   2060 						       msg.listen_channel[4]);
   2061 	}
   2062 
   2063 	p2p_copy_wps_info(p2p, dev, 1, &msg);
   2064 
   2065 	if (msg.wfd_subelems) {
   2066 		wpabuf_free(dev->info.wfd_subelems);
   2067 		dev->info.wfd_subelems = wpabuf_dup(msg.wfd_subelems);
   2068 	}
   2069 
   2070 	p2p_parse_free(&msg);
   2071 
   2072 	p2p_dbg(p2p, "Created device entry based on Probe Req: " MACSTR
   2073 		" dev_capab=0x%x group_capab=0x%x name='%s' listen_freq=%d",
   2074 		MAC2STR(dev->info.p2p_device_addr), dev->info.dev_capab,
   2075 		dev->info.group_capab, dev->info.device_name,
   2076 		dev->listen_freq);
   2077 }
   2078 
   2079 
   2080 struct p2p_device * p2p_add_dev_from_go_neg_req(struct p2p_data *p2p,
   2081 						const u8 *addr,
   2082 						struct p2p_message *msg)
   2083 {
   2084 	struct p2p_device *dev;
   2085 
   2086 	dev = p2p_get_device(p2p, addr);
   2087 	if (dev) {
   2088 		os_get_reltime(&dev->last_seen);
   2089 		return dev; /* already known */
   2090 	}
   2091 
   2092 	dev = p2p_create_device(p2p, addr);
   2093 	if (dev == NULL)
   2094 		return NULL;
   2095 
   2096 	p2p_add_dev_info(p2p, addr, dev, msg);
   2097 
   2098 	return dev;
   2099 }
   2100 
   2101 
   2102 static int dev_type_match(const u8 *dev_type, const u8 *req_dev_type)
   2103 {
   2104 	if (os_memcmp(dev_type, req_dev_type, WPS_DEV_TYPE_LEN) == 0)
   2105 		return 1;
   2106 	if (os_memcmp(dev_type, req_dev_type, 2) == 0 &&
   2107 	    WPA_GET_BE32(&req_dev_type[2]) == 0 &&
   2108 	    WPA_GET_BE16(&req_dev_type[6]) == 0)
   2109 		return 1; /* Category match with wildcard OUI/sub-category */
   2110 	return 0;
   2111 }
   2112 
   2113 
   2114 int dev_type_list_match(const u8 *dev_type, const u8 *req_dev_type[],
   2115 			size_t num_req_dev_type)
   2116 {
   2117 	size_t i;
   2118 	for (i = 0; i < num_req_dev_type; i++) {
   2119 		if (dev_type_match(dev_type, req_dev_type[i]))
   2120 			return 1;
   2121 	}
   2122 	return 0;
   2123 }
   2124 
   2125 
   2126 /**
   2127  * p2p_match_dev_type - Match local device type with requested type
   2128  * @p2p: P2P module context from p2p_init()
   2129  * @wps: WPS TLVs from Probe Request frame (concatenated WPS IEs)
   2130  * Returns: 1 on match, 0 on mismatch
   2131  *
   2132  * This function can be used to match the Requested Device Type attribute in
   2133  * WPS IE with the local device types for deciding whether to reply to a Probe
   2134  * Request frame.
   2135  */
   2136 int p2p_match_dev_type(struct p2p_data *p2p, struct wpabuf *wps)
   2137 {
   2138 	struct wps_parse_attr attr;
   2139 	size_t i;
   2140 
   2141 	if (wps_parse_msg(wps, &attr))
   2142 		return 1; /* assume no Requested Device Type attributes */
   2143 
   2144 	if (attr.num_req_dev_type == 0)
   2145 		return 1; /* no Requested Device Type attributes -> match */
   2146 
   2147 	if (dev_type_list_match(p2p->cfg->pri_dev_type, attr.req_dev_type,
   2148 				attr.num_req_dev_type))
   2149 		return 1; /* Own Primary Device Type matches */
   2150 
   2151 	for (i = 0; i < p2p->cfg->num_sec_dev_types; i++) {
   2152 		if (dev_type_list_match(p2p->cfg->sec_dev_type[i],
   2153 					attr.req_dev_type,
   2154 					attr.num_req_dev_type))
   2155 			return 1; /* Own Secondary Device Type matches */
   2156 	}
   2157 
   2158 	/* No matching device type found */
   2159 	return 0;
   2160 }
   2161 
   2162 
   2163 struct wpabuf * p2p_build_probe_resp_ies(struct p2p_data *p2p,
   2164 					 const u8 *query_hash,
   2165 					 u8 query_count)
   2166 {
   2167 	struct wpabuf *buf;
   2168 	u8 *len;
   2169 	int pw_id = -1;
   2170 	size_t extra = 0;
   2171 
   2172 #ifdef CONFIG_WIFI_DISPLAY
   2173 	if (p2p->wfd_ie_probe_resp)
   2174 		extra = wpabuf_len(p2p->wfd_ie_probe_resp);
   2175 #endif /* CONFIG_WIFI_DISPLAY */
   2176 
   2177 	if (p2p->vendor_elem && p2p->vendor_elem[VENDOR_ELEM_PROBE_RESP_P2P])
   2178 		extra += wpabuf_len(p2p->vendor_elem[VENDOR_ELEM_PROBE_RESP_P2P]);
   2179 
   2180 	if (query_count)
   2181 		extra += MAX_SVC_ADV_IE_LEN;
   2182 
   2183 	buf = wpabuf_alloc(1000 + extra);
   2184 	if (buf == NULL)
   2185 		return NULL;
   2186 
   2187 	if (p2p->go_neg_peer) {
   2188 		/* Advertise immediate availability of WPS credential */
   2189 		pw_id = p2p_wps_method_pw_id(p2p->go_neg_peer->wps_method);
   2190 	}
   2191 
   2192 	if (p2p_build_wps_ie(p2p, buf, pw_id, 1) < 0) {
   2193 		p2p_dbg(p2p, "Failed to build WPS IE for Probe Response");
   2194 		wpabuf_free(buf);
   2195 		return NULL;
   2196 	}
   2197 
   2198 #ifdef CONFIG_WIFI_DISPLAY
   2199 	if (p2p->wfd_ie_probe_resp)
   2200 		wpabuf_put_buf(buf, p2p->wfd_ie_probe_resp);
   2201 #endif /* CONFIG_WIFI_DISPLAY */
   2202 
   2203 	if (p2p->vendor_elem && p2p->vendor_elem[VENDOR_ELEM_PROBE_RESP_P2P])
   2204 		wpabuf_put_buf(buf,
   2205 			       p2p->vendor_elem[VENDOR_ELEM_PROBE_RESP_P2P]);
   2206 
   2207 	/* P2P IE */
   2208 	len = p2p_buf_add_ie_hdr(buf);
   2209 	p2p_buf_add_capability(buf, p2p->dev_capab &
   2210 			       ~P2P_DEV_CAPAB_CLIENT_DISCOVERABILITY, 0);
   2211 	if (p2p->ext_listen_interval)
   2212 		p2p_buf_add_ext_listen_timing(buf, p2p->ext_listen_period,
   2213 					      p2p->ext_listen_interval);
   2214 	p2p_buf_add_device_info(buf, p2p, NULL);
   2215 	p2p_buf_update_ie_hdr(buf, len);
   2216 
   2217 	if (query_count) {
   2218 		p2p_buf_add_service_instance(buf, p2p, query_count, query_hash,
   2219 					     p2p->p2ps_adv_list);
   2220 	}
   2221 
   2222 	return buf;
   2223 }
   2224 
   2225 
   2226 static int p2p_service_find_asp(struct p2p_data *p2p, const u8 *hash)
   2227 {
   2228 	struct p2ps_advertisement *adv_data;
   2229 	int any_wfa;
   2230 
   2231 	p2p_dbg(p2p, "ASP find - ASP list: %p", p2p->p2ps_adv_list);
   2232 
   2233 	/* Wildcard org.wi-fi.wfds matches any WFA spec defined service */
   2234 	any_wfa = os_memcmp(hash, p2p->wild_card_hash, P2PS_HASH_LEN) == 0;
   2235 
   2236 	adv_data = p2p->p2ps_adv_list;
   2237 	while (adv_data) {
   2238 		if (os_memcmp(hash, adv_data->hash, P2PS_HASH_LEN) == 0)
   2239 			return 1; /* exact hash match */
   2240 		if (any_wfa &&
   2241 		    os_strncmp(adv_data->svc_name, P2PS_WILD_HASH_STR,
   2242 			       os_strlen(P2PS_WILD_HASH_STR)) == 0)
   2243 			return 1; /* WFA service match */
   2244 		adv_data = adv_data->next;
   2245 	}
   2246 
   2247 	return 0;
   2248 }
   2249 
   2250 
   2251 static enum p2p_probe_req_status
   2252 p2p_reply_probe(struct p2p_data *p2p, const u8 *addr, const u8 *dst,
   2253 		const u8 *bssid, const u8 *ie, size_t ie_len,
   2254 		unsigned int rx_freq)
   2255 {
   2256 	struct ieee802_11_elems elems;
   2257 	struct wpabuf *buf;
   2258 	struct ieee80211_mgmt *resp;
   2259 	struct p2p_message msg;
   2260 	struct wpabuf *ies;
   2261 	u8 channel, op_class;
   2262 
   2263 	if (ieee802_11_parse_elems((u8 *) ie, ie_len, &elems, 0) ==
   2264 	    ParseFailed) {
   2265 		/* Ignore invalid Probe Request frames */
   2266 		p2p_dbg(p2p, "Could not parse Probe Request frame - ignore it");
   2267 		return P2P_PREQ_MALFORMED;
   2268 	}
   2269 
   2270 	if (elems.p2p == NULL) {
   2271 		/* not a P2P probe - ignore it */
   2272 		p2p_dbg(p2p, "Not a P2P probe - ignore it");
   2273 		return P2P_PREQ_NOT_P2P;
   2274 	}
   2275 
   2276 	if (dst && !is_broadcast_ether_addr(dst) &&
   2277 	    os_memcmp(dst, p2p->cfg->dev_addr, ETH_ALEN) != 0) {
   2278 		/* Not sent to the broadcast address or our P2P Device Address
   2279 		 */
   2280 		p2p_dbg(p2p, "Probe Req DA " MACSTR " not ours - ignore it",
   2281 			MAC2STR(dst));
   2282 		return P2P_PREQ_NOT_PROCESSED;
   2283 	}
   2284 
   2285 	if (bssid && !is_broadcast_ether_addr(bssid)) {
   2286 		/* Not sent to the Wildcard BSSID */
   2287 		p2p_dbg(p2p, "Probe Req BSSID " MACSTR " not wildcard - ignore it",
   2288 			MAC2STR(bssid));
   2289 		return P2P_PREQ_NOT_PROCESSED;
   2290 	}
   2291 
   2292 	if (elems.ssid == NULL || elems.ssid_len != P2P_WILDCARD_SSID_LEN ||
   2293 	    os_memcmp(elems.ssid, P2P_WILDCARD_SSID, P2P_WILDCARD_SSID_LEN) !=
   2294 	    0) {
   2295 		/* not using P2P Wildcard SSID - ignore */
   2296 		p2p_dbg(p2p, "Probe Req not using P2P Wildcard SSID - ignore it");
   2297 		return P2P_PREQ_NOT_PROCESSED;
   2298 	}
   2299 
   2300 	if (supp_rates_11b_only(&elems)) {
   2301 		/* Indicates support for 11b rates only */
   2302 		p2p_dbg(p2p, "Probe Req with 11b rates only supported - ignore it");
   2303 		return P2P_PREQ_NOT_P2P;
   2304 	}
   2305 
   2306 	os_memset(&msg, 0, sizeof(msg));
   2307 	if (p2p_parse_ies(ie, ie_len, &msg) < 0) {
   2308 		/* Could not parse P2P attributes */
   2309 		p2p_dbg(p2p, "Could not parse P2P attributes in Probe Req - ignore it");
   2310 		return P2P_PREQ_NOT_P2P;
   2311 	}
   2312 
   2313 	if (msg.service_hash && msg.service_hash_count) {
   2314 		const u8 *hash = msg.service_hash;
   2315 		u8 i;
   2316 		int p2ps_svc_found = 0;
   2317 
   2318 		p2p_dbg(p2p, "in_listen=%d drv_in_listen=%d when received P2PS Probe Request at %u MHz; own Listen channel %u, pending listen freq %u MHz",
   2319 			p2p->in_listen, p2p->drv_in_listen, rx_freq,
   2320 			p2p->cfg->channel, p2p->pending_listen_freq);
   2321 
   2322 		if (!p2p->in_listen && !p2p->drv_in_listen &&
   2323 		    p2p->pending_listen_freq && rx_freq &&
   2324 		    rx_freq != p2p->pending_listen_freq) {
   2325 			p2p_dbg(p2p, "Do not reply to Probe Request frame that was received on %u MHz while waiting to start Listen state on %u MHz",
   2326 				rx_freq, p2p->pending_listen_freq);
   2327 			p2p_parse_free(&msg);
   2328 			return P2P_PREQ_NOT_LISTEN;
   2329 		}
   2330 
   2331 		for (i = 0; i < msg.service_hash_count; i++) {
   2332 			if (p2p_service_find_asp(p2p, hash)) {
   2333 				p2p_dbg(p2p, "Service Hash match found: "
   2334 					MACSTR, MAC2STR(hash));
   2335 				p2ps_svc_found = 1;
   2336 				break;
   2337 			}
   2338 			hash += P2PS_HASH_LEN;
   2339 		}
   2340 
   2341 		/* Probed hash unknown */
   2342 		if (!p2ps_svc_found) {
   2343 			p2p_dbg(p2p, "No Service Hash match found");
   2344 			p2p_parse_free(&msg);
   2345 			return P2P_PREQ_NOT_PROCESSED;
   2346 		}
   2347 	} else {
   2348 		/* This is not a P2PS Probe Request */
   2349 		p2p_dbg(p2p, "No P2PS Hash in Probe Request");
   2350 
   2351 		if (!p2p->in_listen || !p2p->drv_in_listen) {
   2352 			/* not in Listen state - ignore Probe Request */
   2353 			p2p_dbg(p2p, "Not in Listen state (in_listen=%d drv_in_listen=%d) - ignore Probe Request",
   2354 				p2p->in_listen, p2p->drv_in_listen);
   2355 			p2p_parse_free(&msg);
   2356 			return P2P_PREQ_NOT_LISTEN;
   2357 		}
   2358 	}
   2359 
   2360 	if (msg.device_id &&
   2361 	    os_memcmp(msg.device_id, p2p->cfg->dev_addr, ETH_ALEN) != 0) {
   2362 		/* Device ID did not match */
   2363 		p2p_dbg(p2p, "Probe Req requested Device ID " MACSTR " did not match - ignore it",
   2364 			MAC2STR(msg.device_id));
   2365 		p2p_parse_free(&msg);
   2366 		return P2P_PREQ_NOT_PROCESSED;
   2367 	}
   2368 
   2369 	/* Check Requested Device Type match */
   2370 	if (msg.wps_attributes &&
   2371 	    !p2p_match_dev_type(p2p, msg.wps_attributes)) {
   2372 		/* No match with Requested Device Type */
   2373 		p2p_dbg(p2p, "Probe Req requestred Device Type did not match - ignore it");
   2374 		p2p_parse_free(&msg);
   2375 		return P2P_PREQ_NOT_PROCESSED;
   2376 	}
   2377 
   2378 	if (!p2p->cfg->send_probe_resp) {
   2379 		/* Response generated elsewhere */
   2380 		p2p_dbg(p2p, "Probe Resp generated elsewhere - do not generate additional response");
   2381 		p2p_parse_free(&msg);
   2382 		return P2P_PREQ_NOT_PROCESSED;
   2383 	}
   2384 
   2385 	p2p_dbg(p2p, "Reply to P2P Probe Request in Listen state");
   2386 
   2387 	/*
   2388 	 * We do not really have a specific BSS that this frame is advertising,
   2389 	 * so build a frame that has some information in valid format. This is
   2390 	 * really only used for discovery purposes, not to learn exact BSS
   2391 	 * parameters.
   2392 	 */
   2393 	ies = p2p_build_probe_resp_ies(p2p, msg.service_hash,
   2394 				       msg.service_hash_count);
   2395 	p2p_parse_free(&msg);
   2396 	if (ies == NULL)
   2397 		return P2P_PREQ_NOT_PROCESSED;
   2398 
   2399 	buf = wpabuf_alloc(200 + wpabuf_len(ies));
   2400 	if (buf == NULL) {
   2401 		wpabuf_free(ies);
   2402 		return P2P_PREQ_NOT_PROCESSED;
   2403 	}
   2404 
   2405 	resp = wpabuf_put(buf, offsetof(struct ieee80211_mgmt,
   2406 					u.probe_resp.variable));
   2407 
   2408 	resp->frame_control = host_to_le16((WLAN_FC_TYPE_MGMT << 2) |
   2409 					   (WLAN_FC_STYPE_PROBE_RESP << 4));
   2410 	os_memcpy(resp->da, addr, ETH_ALEN);
   2411 	os_memcpy(resp->sa, p2p->cfg->dev_addr, ETH_ALEN);
   2412 	os_memcpy(resp->bssid, p2p->cfg->dev_addr, ETH_ALEN);
   2413 	resp->u.probe_resp.beacon_int = host_to_le16(100);
   2414 	/* hardware or low-level driver will setup seq_ctrl and timestamp */
   2415 	resp->u.probe_resp.capab_info =
   2416 		host_to_le16(WLAN_CAPABILITY_SHORT_PREAMBLE |
   2417 			     WLAN_CAPABILITY_PRIVACY |
   2418 			     WLAN_CAPABILITY_SHORT_SLOT_TIME);
   2419 
   2420 	wpabuf_put_u8(buf, WLAN_EID_SSID);
   2421 	wpabuf_put_u8(buf, P2P_WILDCARD_SSID_LEN);
   2422 	wpabuf_put_data(buf, P2P_WILDCARD_SSID, P2P_WILDCARD_SSID_LEN);
   2423 
   2424 	wpabuf_put_u8(buf, WLAN_EID_SUPP_RATES);
   2425 	wpabuf_put_u8(buf, 8);
   2426 	wpabuf_put_u8(buf, (60 / 5) | 0x80);
   2427 	wpabuf_put_u8(buf, 90 / 5);
   2428 	wpabuf_put_u8(buf, (120 / 5) | 0x80);
   2429 	wpabuf_put_u8(buf, 180 / 5);
   2430 	wpabuf_put_u8(buf, (240 / 5) | 0x80);
   2431 	wpabuf_put_u8(buf, 360 / 5);
   2432 	wpabuf_put_u8(buf, 480 / 5);
   2433 	wpabuf_put_u8(buf, 540 / 5);
   2434 
   2435 	if (!rx_freq) {
   2436 		channel = p2p->cfg->channel;
   2437 	} else if (p2p_freq_to_channel(rx_freq, &op_class, &channel)) {
   2438 		wpabuf_free(ies);
   2439 		wpabuf_free(buf);
   2440 		return P2P_PREQ_NOT_PROCESSED;
   2441 	}
   2442 
   2443 	wpabuf_put_u8(buf, WLAN_EID_DS_PARAMS);
   2444 	wpabuf_put_u8(buf, 1);
   2445 	wpabuf_put_u8(buf, channel);
   2446 
   2447 	wpabuf_put_buf(buf, ies);
   2448 	wpabuf_free(ies);
   2449 
   2450 	p2p->cfg->send_probe_resp(p2p->cfg->cb_ctx, buf, rx_freq);
   2451 
   2452 	wpabuf_free(buf);
   2453 
   2454 	return P2P_PREQ_PROCESSED;
   2455 }
   2456 
   2457 
   2458 enum p2p_probe_req_status
   2459 p2p_probe_req_rx(struct p2p_data *p2p, const u8 *addr, const u8 *dst,
   2460 		 const u8 *bssid, const u8 *ie, size_t ie_len,
   2461 		 unsigned int rx_freq)
   2462 {
   2463 	enum p2p_probe_req_status res;
   2464 
   2465 	p2p_add_dev_from_probe_req(p2p, addr, ie, ie_len);
   2466 
   2467 	res = p2p_reply_probe(p2p, addr, dst, bssid, ie, ie_len, rx_freq);
   2468 	if (res != P2P_PREQ_PROCESSED && res != P2P_PREQ_NOT_PROCESSED)
   2469 		return res;
   2470 
   2471 	/*
   2472 	 * Activate a pending GO Negotiation/Invite flow if a received Probe
   2473 	 * Request frame is from an expected peer. Some devices may share the
   2474 	 * same address for P2P and non-P2P STA running simultaneously. The
   2475 	 * P2P_PREQ_PROCESSED and P2P_PREQ_NOT_PROCESSED p2p_reply_probe()
   2476 	 * return values verified above ensure we are handling a Probe Request
   2477 	 * frame from a P2P peer.
   2478 	 */
   2479 	if ((p2p->state == P2P_CONNECT || p2p->state == P2P_CONNECT_LISTEN) &&
   2480 	    p2p->go_neg_peer &&
   2481 	    os_memcmp(addr, p2p->go_neg_peer->info.p2p_device_addr, ETH_ALEN)
   2482 	    == 0 &&
   2483 	    !(p2p->go_neg_peer->flags & P2P_DEV_WAIT_GO_NEG_CONFIRM)) {
   2484 		/* Received a Probe Request from GO Negotiation peer */
   2485 		p2p_dbg(p2p, "Found GO Negotiation peer - try to start GO negotiation from timeout");
   2486 		eloop_cancel_timeout(p2p_go_neg_start, p2p, NULL);
   2487 		eloop_register_timeout(0, 0, p2p_go_neg_start, p2p, NULL);
   2488 		return res;
   2489 	}
   2490 
   2491 	if ((p2p->state == P2P_INVITE || p2p->state == P2P_INVITE_LISTEN) &&
   2492 	    p2p->invite_peer &&
   2493 	    (p2p->invite_peer->flags & P2P_DEV_WAIT_INV_REQ_ACK) &&
   2494 	    os_memcmp(addr, p2p->invite_peer->info.p2p_device_addr, ETH_ALEN)
   2495 	    == 0) {
   2496 		/* Received a Probe Request from Invite peer */
   2497 		p2p_dbg(p2p, "Found Invite peer - try to start Invite from timeout");
   2498 		eloop_cancel_timeout(p2p_invite_start, p2p, NULL);
   2499 		eloop_register_timeout(0, 0, p2p_invite_start, p2p, NULL);
   2500 		return res;
   2501 	}
   2502 
   2503 	return res;
   2504 }
   2505 
   2506 
   2507 static int p2p_assoc_req_ie_wlan_ap(struct p2p_data *p2p, const u8 *bssid,
   2508 				    u8 *buf, size_t len, struct wpabuf *p2p_ie)
   2509 {
   2510 	struct wpabuf *tmp;
   2511 	u8 *lpos;
   2512 	size_t tmplen;
   2513 	int res;
   2514 	u8 group_capab;
   2515 	struct p2p_message msg;
   2516 
   2517 	if (p2p_ie == NULL)
   2518 		return 0; /* WLAN AP is not a P2P manager */
   2519 
   2520 	os_memset(&msg, 0, sizeof(msg));
   2521 	if (p2p_parse_p2p_ie(p2p_ie, &msg) < 0)
   2522 		return 0;
   2523 
   2524 	p2p_dbg(p2p, "BSS P2P manageability %s",
   2525 		msg.manageability ? "enabled" : "disabled");
   2526 
   2527 	if (!msg.manageability)
   2528 		return 0;
   2529 
   2530 	/*
   2531 	 * (Re)Association Request - P2P IE
   2532 	 * P2P Capability attribute (shall be present)
   2533 	 * P2P Interface attribute (present if concurrent device and
   2534 	 *	P2P Management is enabled)
   2535 	 */
   2536 	tmp = wpabuf_alloc(200);
   2537 	if (tmp == NULL)
   2538 		return -1;
   2539 
   2540 	lpos = p2p_buf_add_ie_hdr(tmp);
   2541 	group_capab = 0;
   2542 	if (p2p->num_groups > 0) {
   2543 		group_capab |= P2P_GROUP_CAPAB_GROUP_OWNER;
   2544 		if ((p2p->dev_capab & P2P_DEV_CAPAB_CONCURRENT_OPER) &&
   2545 		    (p2p->dev_capab & P2P_DEV_CAPAB_INFRA_MANAGED) &&
   2546 		    p2p->cross_connect)
   2547 			group_capab |= P2P_GROUP_CAPAB_CROSS_CONN;
   2548 	}
   2549 	p2p_buf_add_capability(tmp, p2p->dev_capab, group_capab);
   2550 	if ((p2p->dev_capab & P2P_DEV_CAPAB_CONCURRENT_OPER) &&
   2551 	    (p2p->dev_capab & P2P_DEV_CAPAB_INFRA_MANAGED))
   2552 		p2p_buf_add_p2p_interface(tmp, p2p);
   2553 	p2p_buf_update_ie_hdr(tmp, lpos);
   2554 
   2555 	tmplen = wpabuf_len(tmp);
   2556 	if (tmplen > len)
   2557 		res = -1;
   2558 	else {
   2559 		os_memcpy(buf, wpabuf_head(tmp), tmplen);
   2560 		res = tmplen;
   2561 	}
   2562 	wpabuf_free(tmp);
   2563 
   2564 	return res;
   2565 }
   2566 
   2567 
   2568 int p2p_assoc_req_ie(struct p2p_data *p2p, const u8 *bssid, u8 *buf,
   2569 		     size_t len, int p2p_group, struct wpabuf *p2p_ie)
   2570 {
   2571 	struct wpabuf *tmp;
   2572 	u8 *lpos;
   2573 	struct p2p_device *peer;
   2574 	size_t tmplen;
   2575 	int res;
   2576 	size_t extra = 0;
   2577 
   2578 	if (!p2p_group)
   2579 		return p2p_assoc_req_ie_wlan_ap(p2p, bssid, buf, len, p2p_ie);
   2580 
   2581 #ifdef CONFIG_WIFI_DISPLAY
   2582 	if (p2p->wfd_ie_assoc_req)
   2583 		extra = wpabuf_len(p2p->wfd_ie_assoc_req);
   2584 #endif /* CONFIG_WIFI_DISPLAY */
   2585 
   2586 	if (p2p->vendor_elem && p2p->vendor_elem[VENDOR_ELEM_P2P_ASSOC_REQ])
   2587 		extra += wpabuf_len(p2p->vendor_elem[VENDOR_ELEM_P2P_ASSOC_REQ]);
   2588 
   2589 	/*
   2590 	 * (Re)Association Request - P2P IE
   2591 	 * P2P Capability attribute (shall be present)
   2592 	 * Extended Listen Timing (may be present)
   2593 	 * P2P Device Info attribute (shall be present)
   2594 	 */
   2595 	tmp = wpabuf_alloc(200 + extra);
   2596 	if (tmp == NULL)
   2597 		return -1;
   2598 
   2599 #ifdef CONFIG_WIFI_DISPLAY
   2600 	if (p2p->wfd_ie_assoc_req)
   2601 		wpabuf_put_buf(tmp, p2p->wfd_ie_assoc_req);
   2602 #endif /* CONFIG_WIFI_DISPLAY */
   2603 
   2604 	if (p2p->vendor_elem && p2p->vendor_elem[VENDOR_ELEM_P2P_ASSOC_REQ])
   2605 		wpabuf_put_buf(tmp,
   2606 			       p2p->vendor_elem[VENDOR_ELEM_P2P_ASSOC_REQ]);
   2607 
   2608 	peer = bssid ? p2p_get_device(p2p, bssid) : NULL;
   2609 
   2610 	lpos = p2p_buf_add_ie_hdr(tmp);
   2611 	p2p_buf_add_capability(tmp, p2p->dev_capab, 0);
   2612 	if (p2p->ext_listen_interval)
   2613 		p2p_buf_add_ext_listen_timing(tmp, p2p->ext_listen_period,
   2614 					      p2p->ext_listen_interval);
   2615 	p2p_buf_add_device_info(tmp, p2p, peer);
   2616 	p2p_buf_update_ie_hdr(tmp, lpos);
   2617 
   2618 	tmplen = wpabuf_len(tmp);
   2619 	if (tmplen > len)
   2620 		res = -1;
   2621 	else {
   2622 		os_memcpy(buf, wpabuf_head(tmp), tmplen);
   2623 		res = tmplen;
   2624 	}
   2625 	wpabuf_free(tmp);
   2626 
   2627 	return res;
   2628 }
   2629 
   2630 
   2631 int p2p_scan_result_text(const u8 *ies, size_t ies_len, char *buf, char *end)
   2632 {
   2633 	struct wpabuf *p2p_ie;
   2634 	int ret;
   2635 
   2636 	p2p_ie = ieee802_11_vendor_ie_concat(ies, ies_len, P2P_IE_VENDOR_TYPE);
   2637 	if (p2p_ie == NULL)
   2638 		return 0;
   2639 
   2640 	ret = p2p_attr_text(p2p_ie, buf, end);
   2641 	wpabuf_free(p2p_ie);
   2642 	return ret;
   2643 }
   2644 
   2645 
   2646 struct p2ps_advertisement *
   2647 p2p_service_p2ps_id(struct p2p_data *p2p, u32 adv_id)
   2648 {
   2649 	struct p2ps_advertisement *adv_data;
   2650 
   2651 	if (!p2p)
   2652 		return NULL;
   2653 
   2654 	adv_data = p2p->p2ps_adv_list;
   2655 	while (adv_data) {
   2656 		if (adv_data->id == adv_id)
   2657 			return adv_data;
   2658 		adv_data = adv_data->next;
   2659 	}
   2660 
   2661 	return NULL;
   2662 }
   2663 
   2664 
   2665 int p2p_service_del_asp(struct p2p_data *p2p, u32 adv_id)
   2666 {
   2667 	struct p2ps_advertisement *adv_data;
   2668 	struct p2ps_advertisement **prior;
   2669 
   2670 	if (!p2p)
   2671 		return -1;
   2672 
   2673 	adv_data = p2p->p2ps_adv_list;
   2674 	prior = &p2p->p2ps_adv_list;
   2675 	while (adv_data) {
   2676 		if (adv_data->id == adv_id) {
   2677 			p2p_dbg(p2p, "Delete ASP adv_id=0x%x", adv_id);
   2678 			*prior = adv_data->next;
   2679 			os_free(adv_data);
   2680 			return 0;
   2681 		}
   2682 		prior = &adv_data->next;
   2683 		adv_data = adv_data->next;
   2684 	}
   2685 
   2686 	return -1;
   2687 }
   2688 
   2689 
   2690 int p2p_service_add_asp(struct p2p_data *p2p, int auto_accept, u32 adv_id,
   2691 			const char *adv_str, u8 svc_state, u16 config_methods,
   2692 			const char *svc_info)
   2693 {
   2694 	struct p2ps_advertisement *adv_data, *tmp, **prev;
   2695 	u8 buf[P2PS_HASH_LEN];
   2696 	size_t adv_data_len, adv_len, info_len = 0;
   2697 
   2698 	if (!p2p || !adv_str || !adv_str[0])
   2699 		return -1;
   2700 
   2701 	if (!(config_methods & p2p->cfg->config_methods)) {
   2702 		p2p_dbg(p2p, "Config methods not supported svc: 0x%x dev: 0x%x",
   2703 			config_methods, p2p->cfg->config_methods);
   2704 		return -1;
   2705 	}
   2706 
   2707 	if (!p2ps_gen_hash(p2p, adv_str, buf))
   2708 		return -1;
   2709 
   2710 	if (svc_info)
   2711 		info_len = os_strlen(svc_info);
   2712 	adv_len = os_strlen(adv_str);
   2713 	adv_data_len = sizeof(struct p2ps_advertisement) + adv_len + 1 +
   2714 		info_len + 1;
   2715 
   2716 	adv_data = os_zalloc(adv_data_len);
   2717 	if (!adv_data)
   2718 		return -1;
   2719 
   2720 	os_memcpy(adv_data->hash, buf, P2PS_HASH_LEN);
   2721 	adv_data->id = adv_id;
   2722 	adv_data->state = svc_state;
   2723 	adv_data->config_methods = config_methods & p2p->cfg->config_methods;
   2724 	adv_data->auto_accept = (u8) auto_accept;
   2725 	os_memcpy(adv_data->svc_name, adv_str, adv_len);
   2726 
   2727 	if (svc_info && info_len) {
   2728 		adv_data->svc_info = &adv_data->svc_name[adv_len + 1];
   2729 		os_memcpy(adv_data->svc_info, svc_info, info_len);
   2730 	}
   2731 
   2732 	/*
   2733 	 * Group Advertisements by service string. They do not need to be
   2734 	 * sorted, but groups allow easier Probe Response instance grouping
   2735 	 */
   2736 	tmp = p2p->p2ps_adv_list;
   2737 	prev = &p2p->p2ps_adv_list;
   2738 	while (tmp) {
   2739 		if (tmp->id == adv_data->id) {
   2740 			if (os_strcmp(tmp->svc_name, adv_data->svc_name) != 0) {
   2741 				os_free(adv_data);
   2742 				return -1;
   2743 			}
   2744 			adv_data->next = tmp->next;
   2745 			*prev = adv_data;
   2746 			os_free(tmp);
   2747 			goto inserted;
   2748 		} else {
   2749 			if (os_strcmp(tmp->svc_name, adv_data->svc_name) == 0) {
   2750 				adv_data->next = tmp->next;
   2751 				tmp->next = adv_data;
   2752 				goto inserted;
   2753 			}
   2754 		}
   2755 		prev = &tmp->next;
   2756 		tmp = tmp->next;
   2757 	}
   2758 
   2759 	/* No svc_name match found */
   2760 	adv_data->next = p2p->p2ps_adv_list;
   2761 	p2p->p2ps_adv_list = adv_data;
   2762 
   2763 inserted:
   2764 	p2p_dbg(p2p,
   2765 		"Added ASP advertisement adv_id=0x%x config_methods=0x%x svc_state=0x%x adv_str='%s'",
   2766 		adv_id, adv_data->config_methods, svc_state, adv_str);
   2767 
   2768 	return 0;
   2769 }
   2770 
   2771 
   2772 void p2p_service_flush_asp(struct p2p_data *p2p)
   2773 {
   2774 	struct p2ps_advertisement *adv, *prev;
   2775 
   2776 	if (!p2p)
   2777 		return;
   2778 
   2779 	adv = p2p->p2ps_adv_list;
   2780 	while (adv) {
   2781 		prev = adv;
   2782 		adv = adv->next;
   2783 		os_free(prev);
   2784 	}
   2785 
   2786 	p2p->p2ps_adv_list = NULL;
   2787 	p2p_dbg(p2p, "All ASP advertisements flushed");
   2788 }
   2789 
   2790 
   2791 int p2p_parse_dev_addr_in_p2p_ie(struct wpabuf *p2p_ie, u8 *dev_addr)
   2792 {
   2793 	struct p2p_message msg;
   2794 
   2795 	os_memset(&msg, 0, sizeof(msg));
   2796 	if (p2p_parse_p2p_ie(p2p_ie, &msg))
   2797 		return -1;
   2798 
   2799 	if (msg.p2p_device_addr) {
   2800 		os_memcpy(dev_addr, msg.p2p_device_addr, ETH_ALEN);
   2801 		return 0;
   2802 	} else if (msg.device_id) {
   2803 		os_memcpy(dev_addr, msg.device_id, ETH_ALEN);
   2804 		return 0;
   2805 	}
   2806 	return -1;
   2807 }
   2808 
   2809 
   2810 int p2p_parse_dev_addr(const u8 *ies, size_t ies_len, u8 *dev_addr)
   2811 {
   2812 	struct wpabuf *p2p_ie;
   2813 	int ret;
   2814 
   2815 	p2p_ie = ieee802_11_vendor_ie_concat(ies, ies_len,
   2816 					     P2P_IE_VENDOR_TYPE);
   2817 	if (p2p_ie == NULL)
   2818 		return -1;
   2819 	ret = p2p_parse_dev_addr_in_p2p_ie(p2p_ie, dev_addr);
   2820 	wpabuf_free(p2p_ie);
   2821 	return ret;
   2822 }
   2823 
   2824 
   2825 static void p2p_clear_go_neg(struct p2p_data *p2p)
   2826 {
   2827 	p2p->go_neg_peer = NULL;
   2828 	p2p_clear_timeout(p2p);
   2829 	p2p_set_state(p2p, P2P_IDLE);
   2830 }
   2831 
   2832 
   2833 void p2p_wps_success_cb(struct p2p_data *p2p, const u8 *mac_addr)
   2834 {
   2835 	if (p2p->go_neg_peer == NULL) {
   2836 		p2p_dbg(p2p, "No pending Group Formation - ignore WPS registration success notification");
   2837 		return; /* No pending Group Formation */
   2838 	}
   2839 
   2840 	if (os_memcmp(mac_addr, p2p->go_neg_peer->intended_addr, ETH_ALEN) !=
   2841 	    0) {
   2842 		p2p_dbg(p2p, "Ignore WPS registration success notification for "
   2843 			MACSTR " (GO Negotiation peer " MACSTR ")",
   2844 			MAC2STR(mac_addr),
   2845 			MAC2STR(p2p->go_neg_peer->intended_addr));
   2846 		return; /* Ignore unexpected peer address */
   2847 	}
   2848 
   2849 	p2p_dbg(p2p, "Group Formation completed successfully with " MACSTR,
   2850 		MAC2STR(mac_addr));
   2851 
   2852 	p2p_clear_go_neg(p2p);
   2853 }
   2854 
   2855 
   2856 void p2p_group_formation_failed(struct p2p_data *p2p)
   2857 {
   2858 	if (p2p->go_neg_peer == NULL) {
   2859 		p2p_dbg(p2p, "No pending Group Formation - ignore group formation failure notification");
   2860 		return; /* No pending Group Formation */
   2861 	}
   2862 
   2863 	p2p_dbg(p2p, "Group Formation failed with " MACSTR,
   2864 		MAC2STR(p2p->go_neg_peer->intended_addr));
   2865 
   2866 	p2p_clear_go_neg(p2p);
   2867 }
   2868 
   2869 
   2870 struct p2p_data * p2p_init(const struct p2p_config *cfg)
   2871 {
   2872 	struct p2p_data *p2p;
   2873 
   2874 	if (cfg->max_peers < 1 ||
   2875 	    cfg->passphrase_len < 8 || cfg->passphrase_len > 63)
   2876 		return NULL;
   2877 
   2878 	p2p = os_zalloc(sizeof(*p2p) + sizeof(*cfg));
   2879 	if (p2p == NULL)
   2880 		return NULL;
   2881 	p2p->cfg = (struct p2p_config *) (p2p + 1);
   2882 	os_memcpy(p2p->cfg, cfg, sizeof(*cfg));
   2883 	if (cfg->dev_name)
   2884 		p2p->cfg->dev_name = os_strdup(cfg->dev_name);
   2885 	if (cfg->manufacturer)
   2886 		p2p->cfg->manufacturer = os_strdup(cfg->manufacturer);
   2887 	if (cfg->model_name)
   2888 		p2p->cfg->model_name = os_strdup(cfg->model_name);
   2889 	if (cfg->model_number)
   2890 		p2p->cfg->model_number = os_strdup(cfg->model_number);
   2891 	if (cfg->serial_number)
   2892 		p2p->cfg->serial_number = os_strdup(cfg->serial_number);
   2893 	if (cfg->pref_chan) {
   2894 		p2p->cfg->pref_chan = os_malloc(cfg->num_pref_chan *
   2895 						sizeof(struct p2p_channel));
   2896 		if (p2p->cfg->pref_chan) {
   2897 			os_memcpy(p2p->cfg->pref_chan, cfg->pref_chan,
   2898 				  cfg->num_pref_chan *
   2899 				  sizeof(struct p2p_channel));
   2900 		} else
   2901 			p2p->cfg->num_pref_chan = 0;
   2902 	}
   2903 
   2904 	p2ps_gen_hash(p2p, P2PS_WILD_HASH_STR, p2p->wild_card_hash);
   2905 
   2906 	p2p->min_disc_int = 1;
   2907 	p2p->max_disc_int = 3;
   2908 	p2p->max_disc_tu = -1;
   2909 
   2910 	if (os_get_random(&p2p->next_tie_breaker, 1) < 0)
   2911 		p2p->next_tie_breaker = 0;
   2912 	p2p->next_tie_breaker &= 0x01;
   2913 	if (cfg->sd_request)
   2914 		p2p->dev_capab |= P2P_DEV_CAPAB_SERVICE_DISCOVERY;
   2915 	p2p->dev_capab |= P2P_DEV_CAPAB_INVITATION_PROCEDURE;
   2916 	if (cfg->concurrent_operations)
   2917 		p2p->dev_capab |= P2P_DEV_CAPAB_CONCURRENT_OPER;
   2918 	p2p->dev_capab |= P2P_DEV_CAPAB_CLIENT_DISCOVERABILITY;
   2919 
   2920 	dl_list_init(&p2p->devices);
   2921 
   2922 	eloop_register_timeout(P2P_PEER_EXPIRATION_INTERVAL, 0,
   2923 			       p2p_expiration_timeout, p2p, NULL);
   2924 
   2925 	p2p->go_timeout = 100;
   2926 	p2p->client_timeout = 20;
   2927 	p2p->num_p2p_sd_queries = 0;
   2928 
   2929 	p2p_dbg(p2p, "initialized");
   2930 	p2p_channels_dump(p2p, "channels", &p2p->cfg->channels);
   2931 	p2p_channels_dump(p2p, "cli_channels", &p2p->cfg->cli_channels);
   2932 
   2933 	return p2p;
   2934 }
   2935 
   2936 
   2937 void p2p_deinit(struct p2p_data *p2p)
   2938 {
   2939 #ifdef CONFIG_WIFI_DISPLAY
   2940 	wpabuf_free(p2p->wfd_ie_beacon);
   2941 	wpabuf_free(p2p->wfd_ie_probe_req);
   2942 	wpabuf_free(p2p->wfd_ie_probe_resp);
   2943 	wpabuf_free(p2p->wfd_ie_assoc_req);
   2944 	wpabuf_free(p2p->wfd_ie_invitation);
   2945 	wpabuf_free(p2p->wfd_ie_prov_disc_req);
   2946 	wpabuf_free(p2p->wfd_ie_prov_disc_resp);
   2947 	wpabuf_free(p2p->wfd_ie_go_neg);
   2948 	wpabuf_free(p2p->wfd_dev_info);
   2949 	wpabuf_free(p2p->wfd_assoc_bssid);
   2950 	wpabuf_free(p2p->wfd_coupled_sink_info);
   2951 #endif /* CONFIG_WIFI_DISPLAY */
   2952 
   2953 	eloop_cancel_timeout(p2p_expiration_timeout, p2p, NULL);
   2954 	eloop_cancel_timeout(p2p_ext_listen_timeout, p2p, NULL);
   2955 	eloop_cancel_timeout(p2p_scan_timeout, p2p, NULL);
   2956 	eloop_cancel_timeout(p2p_go_neg_start, p2p, NULL);
   2957 	eloop_cancel_timeout(p2p_go_neg_wait_timeout, p2p, NULL);
   2958 	p2p_flush(p2p);
   2959 	p2p_free_req_dev_types(p2p);
   2960 	os_free(p2p->cfg->dev_name);
   2961 	os_free(p2p->cfg->manufacturer);
   2962 	os_free(p2p->cfg->model_name);
   2963 	os_free(p2p->cfg->model_number);
   2964 	os_free(p2p->cfg->serial_number);
   2965 	os_free(p2p->cfg->pref_chan);
   2966 	os_free(p2p->groups);
   2967 	p2ps_prov_free(p2p);
   2968 	wpabuf_free(p2p->sd_resp);
   2969 	os_free(p2p->after_scan_tx);
   2970 	p2p_remove_wps_vendor_extensions(p2p);
   2971 	os_free(p2p->no_go_freq.range);
   2972 	p2p_service_flush_asp(p2p);
   2973 
   2974 	os_free(p2p);
   2975 }
   2976 
   2977 
   2978 void p2p_flush(struct p2p_data *p2p)
   2979 {
   2980 	struct p2p_device *dev, *prev;
   2981 	p2p_stop_find(p2p);
   2982 	dl_list_for_each_safe(dev, prev, &p2p->devices, struct p2p_device,
   2983 			      list) {
   2984 		dl_list_del(&dev->list);
   2985 		p2p_device_free(p2p, dev);
   2986 	}
   2987 	p2p_free_sd_queries(p2p);
   2988 	os_free(p2p->after_scan_tx);
   2989 	p2p->after_scan_tx = NULL;
   2990 }
   2991 
   2992 
   2993 int p2p_unauthorize(struct p2p_data *p2p, const u8 *addr)
   2994 {
   2995 	struct p2p_device *dev;
   2996 
   2997 	dev = p2p_get_device(p2p, addr);
   2998 	if (dev == NULL)
   2999 		return -1;
   3000 
   3001 	p2p_dbg(p2p, "Unauthorizing " MACSTR, MAC2STR(addr));
   3002 
   3003 	if (p2p->go_neg_peer == dev) {
   3004 		eloop_cancel_timeout(p2p_go_neg_wait_timeout, p2p, NULL);
   3005 		p2p->go_neg_peer = NULL;
   3006 	}
   3007 
   3008 	dev->wps_method = WPS_NOT_READY;
   3009 	dev->oob_pw_id = 0;
   3010 	dev->flags &= ~P2P_DEV_WAIT_GO_NEG_RESPONSE;
   3011 	dev->flags &= ~P2P_DEV_WAIT_GO_NEG_CONFIRM;
   3012 
   3013 	/* Check if after_scan_tx is for this peer. If so free it */
   3014 	if (p2p->after_scan_tx &&
   3015 	    os_memcmp(addr, p2p->after_scan_tx->dst, ETH_ALEN) == 0) {
   3016 		os_free(p2p->after_scan_tx);
   3017 		p2p->after_scan_tx = NULL;
   3018 	}
   3019 
   3020 	return 0;
   3021 }
   3022 
   3023 
   3024 int p2p_set_dev_name(struct p2p_data *p2p, const char *dev_name)
   3025 {
   3026 	os_free(p2p->cfg->dev_name);
   3027 	if (dev_name) {
   3028 		p2p->cfg->dev_name = os_strdup(dev_name);
   3029 		if (p2p->cfg->dev_name == NULL)
   3030 			return -1;
   3031 	} else
   3032 		p2p->cfg->dev_name = NULL;
   3033 	return 0;
   3034 }
   3035 
   3036 
   3037 int p2p_set_manufacturer(struct p2p_data *p2p, const char *manufacturer)
   3038 {
   3039 	os_free(p2p->cfg->manufacturer);
   3040 	p2p->cfg->manufacturer = NULL;
   3041 	if (manufacturer) {
   3042 		p2p->cfg->manufacturer = os_strdup(manufacturer);
   3043 		if (p2p->cfg->manufacturer == NULL)
   3044 			return -1;
   3045 	}
   3046 
   3047 	return 0;
   3048 }
   3049 
   3050 
   3051 int p2p_set_model_name(struct p2p_data *p2p, const char *model_name)
   3052 {
   3053 	os_free(p2p->cfg->model_name);
   3054 	p2p->cfg->model_name = NULL;
   3055 	if (model_name) {
   3056 		p2p->cfg->model_name = os_strdup(model_name);
   3057 		if (p2p->cfg->model_name == NULL)
   3058 			return -1;
   3059 	}
   3060 
   3061 	return 0;
   3062 }
   3063 
   3064 
   3065 int p2p_set_model_number(struct p2p_data *p2p, const char *model_number)
   3066 {
   3067 	os_free(p2p->cfg->model_number);
   3068 	p2p->cfg->model_number = NULL;
   3069 	if (model_number) {
   3070 		p2p->cfg->model_number = os_strdup(model_number);
   3071 		if (p2p->cfg->model_number == NULL)
   3072 			return -1;
   3073 	}
   3074 
   3075 	return 0;
   3076 }
   3077 
   3078 
   3079 int p2p_set_serial_number(struct p2p_data *p2p, const char *serial_number)
   3080 {
   3081 	os_free(p2p->cfg->serial_number);
   3082 	p2p->cfg->serial_number = NULL;
   3083 	if (serial_number) {
   3084 		p2p->cfg->serial_number = os_strdup(serial_number);
   3085 		if (p2p->cfg->serial_number == NULL)
   3086 			return -1;
   3087 	}
   3088 
   3089 	return 0;
   3090 }
   3091 
   3092 
   3093 void p2p_set_config_methods(struct p2p_data *p2p, u16 config_methods)
   3094 {
   3095 	p2p->cfg->config_methods = config_methods;
   3096 }
   3097 
   3098 
   3099 void p2p_set_uuid(struct p2p_data *p2p, const u8 *uuid)
   3100 {
   3101 	os_memcpy(p2p->cfg->uuid, uuid, 16);
   3102 }
   3103 
   3104 
   3105 int p2p_set_pri_dev_type(struct p2p_data *p2p, const u8 *pri_dev_type)
   3106 {
   3107 	os_memcpy(p2p->cfg->pri_dev_type, pri_dev_type, 8);
   3108 	return 0;
   3109 }
   3110 
   3111 
   3112 int p2p_set_sec_dev_types(struct p2p_data *p2p, const u8 dev_types[][8],
   3113 			  size_t num_dev_types)
   3114 {
   3115 	if (num_dev_types > P2P_SEC_DEVICE_TYPES)
   3116 		num_dev_types = P2P_SEC_DEVICE_TYPES;
   3117 	p2p->cfg->num_sec_dev_types = num_dev_types;
   3118 	os_memcpy(p2p->cfg->sec_dev_type, dev_types, num_dev_types * 8);
   3119 	return 0;
   3120 }
   3121 
   3122 
   3123 void p2p_remove_wps_vendor_extensions(struct p2p_data *p2p)
   3124 {
   3125 	int i;
   3126 
   3127 	for (i = 0; i < P2P_MAX_WPS_VENDOR_EXT; i++) {
   3128 		wpabuf_free(p2p->wps_vendor_ext[i]);
   3129 		p2p->wps_vendor_ext[i] = NULL;
   3130 	}
   3131 }
   3132 
   3133 
   3134 int p2p_add_wps_vendor_extension(struct p2p_data *p2p,
   3135 				 const struct wpabuf *vendor_ext)
   3136 {
   3137 	int i;
   3138 
   3139 	if (vendor_ext == NULL)
   3140 		return -1;
   3141 
   3142 	for (i = 0; i < P2P_MAX_WPS_VENDOR_EXT; i++) {
   3143 		if (p2p->wps_vendor_ext[i] == NULL)
   3144 			break;
   3145 	}
   3146 	if (i >= P2P_MAX_WPS_VENDOR_EXT)
   3147 		return -1;
   3148 
   3149 	p2p->wps_vendor_ext[i] = wpabuf_dup(vendor_ext);
   3150 	if (p2p->wps_vendor_ext[i] == NULL)
   3151 		return -1;
   3152 
   3153 	return 0;
   3154 }
   3155 
   3156 
   3157 int p2p_set_country(struct p2p_data *p2p, const char *country)
   3158 {
   3159 	os_memcpy(p2p->cfg->country, country, 3);
   3160 	return 0;
   3161 }
   3162 
   3163 
   3164 static int p2p_pre_find_operation(struct p2p_data *p2p, struct p2p_device *dev)
   3165 {
   3166 	if (dev->sd_pending_bcast_queries == 0) {
   3167 		/* Initialize with total number of registered broadcast
   3168 		 * SD queries. */
   3169 		dev->sd_pending_bcast_queries = p2p->num_p2p_sd_queries;
   3170 	}
   3171 
   3172 	if (p2p_start_sd(p2p, dev) == 0)
   3173 		return 1;
   3174 
   3175 	if (dev->req_config_methods &&
   3176 	    !(dev->flags & P2P_DEV_PD_FOR_JOIN)) {
   3177 		p2p_dbg(p2p, "Send pending Provision Discovery Request to "
   3178 			MACSTR " (config methods 0x%x)",
   3179 			MAC2STR(dev->info.p2p_device_addr),
   3180 			dev->req_config_methods);
   3181 		if (p2p_send_prov_disc_req(p2p, dev, 0, 0) == 0)
   3182 			return 1;
   3183 	}
   3184 
   3185 	return 0;
   3186 }
   3187 
   3188 
   3189 void p2p_continue_find(struct p2p_data *p2p)
   3190 {
   3191 	struct p2p_device *dev;
   3192 	int found;
   3193 
   3194 	p2p_set_state(p2p, P2P_SEARCH);
   3195 
   3196 	/* Continue from the device following the last iteration */
   3197 	found = 0;
   3198 	dl_list_for_each(dev, &p2p->devices, struct p2p_device, list) {
   3199 		if (dev == p2p->last_p2p_find_oper) {
   3200 			found = 1;
   3201 			continue;
   3202 		}
   3203 		if (!found)
   3204 			continue;
   3205 		if (p2p_pre_find_operation(p2p, dev) > 0) {
   3206 			p2p->last_p2p_find_oper = dev;
   3207 			return;
   3208 		}
   3209 	}
   3210 
   3211 	/*
   3212 	 * Wrap around to the beginning of the list and continue until the last
   3213 	 * iteration device.
   3214 	 */
   3215 	dl_list_for_each(dev, &p2p->devices, struct p2p_device, list) {
   3216 		if (p2p_pre_find_operation(p2p, dev) > 0) {
   3217 			p2p->last_p2p_find_oper = dev;
   3218 			return;
   3219 		}
   3220 		if (dev == p2p->last_p2p_find_oper)
   3221 			break;
   3222 	}
   3223 
   3224 	p2p_listen_in_find(p2p, 1);
   3225 }
   3226 
   3227 
   3228 static void p2p_sd_cb(struct p2p_data *p2p, int success)
   3229 {
   3230 	p2p_dbg(p2p, "Service Discovery Query TX callback: success=%d",
   3231 		success);
   3232 	p2p->pending_action_state = P2P_NO_PENDING_ACTION;
   3233 
   3234 	if (!success) {
   3235 		if (p2p->sd_peer)
   3236 			p2p->cfg->send_action_done(p2p->cfg->cb_ctx);
   3237 		p2p->sd_peer = NULL;
   3238 		if (p2p->state != P2P_IDLE)
   3239 			p2p_continue_find(p2p);
   3240 		return;
   3241 	}
   3242 
   3243 	if (p2p->sd_peer == NULL) {
   3244 		p2p_dbg(p2p, "No SD peer entry known");
   3245 		if (p2p->state != P2P_IDLE)
   3246 			p2p_continue_find(p2p);
   3247 		return;
   3248 	}
   3249 
   3250 	if (p2p->sd_query && p2p->sd_query->for_all_peers) {
   3251 		/* Update the pending broadcast SD query count for this device
   3252 		 */
   3253 		p2p->sd_peer->sd_pending_bcast_queries--;
   3254 
   3255 		/*
   3256 		 * If there are no pending broadcast queries for this device,
   3257 		 * mark it as done (-1).
   3258 		 */
   3259 		if (p2p->sd_peer->sd_pending_bcast_queries == 0)
   3260 			p2p->sd_peer->sd_pending_bcast_queries = -1;
   3261 	}
   3262 
   3263 	/* Wait for response from the peer */
   3264 	p2p_set_state(p2p, P2P_SD_DURING_FIND);
   3265 	p2p_set_timeout(p2p, 0, 200000);
   3266 }
   3267 
   3268 
   3269 /**
   3270  * p2p_retry_pd - Retry any pending provision disc requests in IDLE state
   3271  * @p2p: P2P module context from p2p_init()
   3272  */
   3273 static void p2p_retry_pd(struct p2p_data *p2p)
   3274 {
   3275 	struct p2p_device *dev;
   3276 
   3277 	/*
   3278 	 * Retry the prov disc req attempt only for the peer that the user had
   3279 	 * requested.
   3280 	 */
   3281 
   3282 	dl_list_for_each(dev, &p2p->devices, struct p2p_device, list) {
   3283 		if (os_memcmp(p2p->pending_pd_devaddr,
   3284 			      dev->info.p2p_device_addr, ETH_ALEN) != 0)
   3285 			continue;
   3286 		if (!dev->req_config_methods)
   3287 			continue;
   3288 
   3289 		p2p_dbg(p2p, "Send pending Provision Discovery Request to "
   3290 			MACSTR " (config methods 0x%x)",
   3291 			MAC2STR(dev->info.p2p_device_addr),
   3292 			dev->req_config_methods);
   3293 		p2p_send_prov_disc_req(p2p, dev,
   3294 				       dev->flags & P2P_DEV_PD_FOR_JOIN,
   3295 				       p2p->pd_force_freq);
   3296 		return;
   3297 	}
   3298 }
   3299 
   3300 
   3301 static void p2p_prov_disc_cb(struct p2p_data *p2p, int success)
   3302 {
   3303 	p2p_dbg(p2p, "Provision Discovery Request TX callback: success=%d",
   3304 		success);
   3305 
   3306 	/*
   3307 	 * Postpone resetting the pending action state till after we actually
   3308 	 * time out. This allows us to take some action like notifying any
   3309 	 * interested parties about no response to the request.
   3310 	 *
   3311 	 * When the timer (below) goes off we check in IDLE, SEARCH, or
   3312 	 * LISTEN_ONLY state, which are the only allowed states to issue a PD
   3313 	 * requests in, if this was still pending and then raise notification.
   3314 	 */
   3315 
   3316 	if (!success) {
   3317 		p2p->pending_action_state = P2P_NO_PENDING_ACTION;
   3318 
   3319 		if (p2p->user_initiated_pd &&
   3320 		    (p2p->state == P2P_SEARCH || p2p->state == P2P_LISTEN_ONLY))
   3321 		{
   3322 			/* Retry request from timeout to avoid busy loops */
   3323 			p2p->pending_action_state = P2P_PENDING_PD;
   3324 			p2p_set_timeout(p2p, 0, 50000);
   3325 		} else if (p2p->state != P2P_IDLE)
   3326 			p2p_continue_find(p2p);
   3327 		else if (p2p->user_initiated_pd) {
   3328 			p2p->pending_action_state = P2P_PENDING_PD;
   3329 			p2p_set_timeout(p2p, 0, 300000);
   3330 		}
   3331 		return;
   3332 	}
   3333 
   3334 	/*
   3335 	 * This postponing, of resetting pending_action_state, needs to be
   3336 	 * done only for user initiated PD requests and not internal ones.
   3337 	 */
   3338 	if (p2p->user_initiated_pd)
   3339 		p2p->pending_action_state = P2P_PENDING_PD;
   3340 	else
   3341 		p2p->pending_action_state = P2P_NO_PENDING_ACTION;
   3342 
   3343 	/* Wait for response from the peer */
   3344 	if (p2p->state == P2P_SEARCH)
   3345 		p2p_set_state(p2p, P2P_PD_DURING_FIND);
   3346 	p2p_set_timeout(p2p, 0, 200000);
   3347 }
   3348 
   3349 
   3350 static int p2p_check_after_scan_tx_continuation(struct p2p_data *p2p)
   3351 {
   3352 	if (p2p->after_scan_tx_in_progress) {
   3353 		p2p->after_scan_tx_in_progress = 0;
   3354 		if (p2p->start_after_scan != P2P_AFTER_SCAN_NOTHING &&
   3355 		    p2p_run_after_scan(p2p))
   3356 			return 1;
   3357 		if (p2p->state == P2P_SEARCH) {
   3358 			p2p_dbg(p2p, "Continue find after after_scan_tx completion");
   3359 			p2p_continue_find(p2p);
   3360 		}
   3361 	}
   3362 
   3363 	return 0;
   3364 }
   3365 
   3366 
   3367 static void p2p_prov_disc_resp_cb(struct p2p_data *p2p, int success)
   3368 {
   3369 	p2p_dbg(p2p, "Provision Discovery Response TX callback: success=%d",
   3370 		success);
   3371 
   3372 	if (p2p->send_action_in_progress) {
   3373 		p2p->send_action_in_progress = 0;
   3374 		p2p->cfg->send_action_done(p2p->cfg->cb_ctx);
   3375 	}
   3376 
   3377 	p2p->pending_action_state = P2P_NO_PENDING_ACTION;
   3378 
   3379 	if (!success)
   3380 		goto continue_search;
   3381 
   3382 	if (!p2p->cfg->prov_disc_resp_cb ||
   3383 	    p2p->cfg->prov_disc_resp_cb(p2p->cfg->cb_ctx) < 1)
   3384 		goto continue_search;
   3385 
   3386 	p2p_dbg(p2p,
   3387 		"Post-Provision Discovery operations started - do not try to continue other P2P operations");
   3388 	return;
   3389 
   3390 continue_search:
   3391 	p2p_check_after_scan_tx_continuation(p2p);
   3392 }
   3393 
   3394 
   3395 int p2p_scan_res_handler(struct p2p_data *p2p, const u8 *bssid, int freq,
   3396 			 struct os_reltime *rx_time, int level, const u8 *ies,
   3397 			 size_t ies_len)
   3398 {
   3399 	if (os_reltime_before(rx_time, &p2p->find_start)) {
   3400 		/*
   3401 		 * The driver may have cached (e.g., in cfg80211 BSS table) the
   3402 		 * scan results for relatively long time. To avoid reporting
   3403 		 * stale information, update P2P peers only based on results
   3404 		 * that have based on frames received after the last p2p_find
   3405 		 * operation was started.
   3406 		 */
   3407 		p2p_dbg(p2p, "Ignore old scan result for " MACSTR
   3408 			" (rx_time=%u.%06u)",
   3409 			MAC2STR(bssid), (unsigned int) rx_time->sec,
   3410 			(unsigned int) rx_time->usec);
   3411 		return 0;
   3412 	}
   3413 
   3414 	p2p_add_device(p2p, bssid, freq, rx_time, level, ies, ies_len, 1);
   3415 
   3416 	return 0;
   3417 }
   3418 
   3419 
   3420 void p2p_scan_res_handled(struct p2p_data *p2p)
   3421 {
   3422 	if (!p2p->p2p_scan_running) {
   3423 		p2p_dbg(p2p, "p2p_scan was not running, but scan results received");
   3424 	}
   3425 	p2p->p2p_scan_running = 0;
   3426 	eloop_cancel_timeout(p2p_scan_timeout, p2p, NULL);
   3427 
   3428 	if (p2p_run_after_scan(p2p))
   3429 		return;
   3430 	if (p2p->state == P2P_SEARCH)
   3431 		p2p_continue_find(p2p);
   3432 }
   3433 
   3434 
   3435 void p2p_scan_ie(struct p2p_data *p2p, struct wpabuf *ies, const u8 *dev_id)
   3436 {
   3437 	u8 dev_capab;
   3438 	u8 *len;
   3439 
   3440 #ifdef CONFIG_WIFI_DISPLAY
   3441 	if (p2p->wfd_ie_probe_req)
   3442 		wpabuf_put_buf(ies, p2p->wfd_ie_probe_req);
   3443 #endif /* CONFIG_WIFI_DISPLAY */
   3444 
   3445 	if (p2p->vendor_elem && p2p->vendor_elem[VENDOR_ELEM_PROBE_REQ_P2P])
   3446 		wpabuf_put_buf(ies,
   3447 			       p2p->vendor_elem[VENDOR_ELEM_PROBE_REQ_P2P]);
   3448 
   3449 	len = p2p_buf_add_ie_hdr(ies);
   3450 
   3451 	dev_capab = p2p->dev_capab & ~P2P_DEV_CAPAB_CLIENT_DISCOVERABILITY;
   3452 
   3453 	/* P2PS requires Probe Request frames to include SD bit */
   3454 	if (p2p->p2ps_seek && p2p->p2ps_seek_count)
   3455 		dev_capab |= P2P_DEV_CAPAB_SERVICE_DISCOVERY;
   3456 
   3457 	p2p_buf_add_capability(ies, dev_capab, 0);
   3458 
   3459 	if (dev_id)
   3460 		p2p_buf_add_device_id(ies, dev_id);
   3461 	if (p2p->cfg->reg_class && p2p->cfg->channel)
   3462 		p2p_buf_add_listen_channel(ies, p2p->cfg->country,
   3463 					   p2p->cfg->reg_class,
   3464 					   p2p->cfg->channel);
   3465 	if (p2p->ext_listen_interval)
   3466 		p2p_buf_add_ext_listen_timing(ies, p2p->ext_listen_period,
   3467 					      p2p->ext_listen_interval);
   3468 
   3469 	if (p2p->p2ps_seek && p2p->p2ps_seek_count)
   3470 		p2p_buf_add_service_hash(ies, p2p);
   3471 
   3472 	/* TODO: p2p_buf_add_operating_channel() if GO */
   3473 	p2p_buf_update_ie_hdr(ies, len);
   3474 }
   3475 
   3476 
   3477 size_t p2p_scan_ie_buf_len(struct p2p_data *p2p)
   3478 {
   3479 	size_t len = 100;
   3480 
   3481 #ifdef CONFIG_WIFI_DISPLAY
   3482 	if (p2p && p2p->wfd_ie_probe_req)
   3483 		len += wpabuf_len(p2p->wfd_ie_probe_req);
   3484 #endif /* CONFIG_WIFI_DISPLAY */
   3485 
   3486 	if (p2p && p2p->vendor_elem &&
   3487 	    p2p->vendor_elem[VENDOR_ELEM_PROBE_REQ_P2P])
   3488 		len += wpabuf_len(p2p->vendor_elem[VENDOR_ELEM_PROBE_REQ_P2P]);
   3489 
   3490 	return len;
   3491 }
   3492 
   3493 
   3494 int p2p_ie_text(struct wpabuf *p2p_ie, char *buf, char *end)
   3495 {
   3496 	return p2p_attr_text(p2p_ie, buf, end);
   3497 }
   3498 
   3499 
   3500 static void p2p_go_neg_req_cb(struct p2p_data *p2p, int success)
   3501 {
   3502 	struct p2p_device *dev = p2p->go_neg_peer;
   3503 	int timeout;
   3504 
   3505 	p2p_dbg(p2p, "GO Negotiation Request TX callback: success=%d", success);
   3506 
   3507 	if (dev == NULL) {
   3508 		p2p_dbg(p2p, "No pending GO Negotiation");
   3509 		return;
   3510 	}
   3511 
   3512 	if (success) {
   3513 		if (dev->flags & P2P_DEV_USER_REJECTED) {
   3514 			p2p_set_state(p2p, P2P_IDLE);
   3515 			return;
   3516 		}
   3517 	} else if (dev->go_neg_req_sent) {
   3518 		/* Cancel the increment from p2p_connect_send() on failure */
   3519 		dev->go_neg_req_sent--;
   3520 	}
   3521 
   3522 	if (!success &&
   3523 	    (dev->info.dev_capab & P2P_DEV_CAPAB_CLIENT_DISCOVERABILITY) &&
   3524 	    !is_zero_ether_addr(dev->member_in_go_dev)) {
   3525 		p2p_dbg(p2p, "Peer " MACSTR " did not acknowledge request - try to use device discoverability through its GO",
   3526 			MAC2STR(dev->info.p2p_device_addr));
   3527 		p2p->cfg->send_action_done(p2p->cfg->cb_ctx);
   3528 		p2p_send_dev_disc_req(p2p, dev);
   3529 		return;
   3530 	}
   3531 
   3532 	/*
   3533 	 * Use P2P find, if needed, to find the other device from its listen
   3534 	 * channel.
   3535 	 */
   3536 	p2p_set_state(p2p, P2P_CONNECT);
   3537 	timeout = success ? 500000 : 100000;
   3538 	if (!success && p2p->go_neg_peer &&
   3539 	    (p2p->go_neg_peer->flags & P2P_DEV_PEER_WAITING_RESPONSE)) {
   3540 		unsigned int r;
   3541 		/*
   3542 		 * Peer is expected to wait our response and we will skip the
   3543 		 * listen phase. Add some randomness to the wait time here to
   3544 		 * make it less likely to hit cases where we could end up in
   3545 		 * sync with peer not listening.
   3546 		 */
   3547 		if (os_get_random((u8 *) &r, sizeof(r)) < 0)
   3548 			r = 0;
   3549 		timeout += r % 100000;
   3550 	}
   3551 	p2p_set_timeout(p2p, 0, timeout);
   3552 }
   3553 
   3554 
   3555 static void p2p_go_neg_resp_cb(struct p2p_data *p2p, int success)
   3556 {
   3557 	p2p_dbg(p2p, "GO Negotiation Response TX callback: success=%d",
   3558 		success);
   3559 	if (!p2p->go_neg_peer && p2p->state == P2P_PROVISIONING) {
   3560 		p2p_dbg(p2p, "Ignore TX callback event - GO Negotiation is not running anymore");
   3561 		return;
   3562 	}
   3563 	p2p_set_state(p2p, P2P_CONNECT);
   3564 	p2p_set_timeout(p2p, 0, 500000);
   3565 }
   3566 
   3567 
   3568 static void p2p_go_neg_resp_failure_cb(struct p2p_data *p2p, int success,
   3569 				       const u8 *addr)
   3570 {
   3571 	p2p_dbg(p2p, "GO Negotiation Response (failure) TX callback: success=%d", success);
   3572 	if (p2p->go_neg_peer && p2p->go_neg_peer->status != P2P_SC_SUCCESS) {
   3573 		p2p_go_neg_failed(p2p, p2p->go_neg_peer->status);
   3574 		return;
   3575 	}
   3576 
   3577 	if (success) {
   3578 		struct p2p_device *dev;
   3579 		dev = p2p_get_device(p2p, addr);
   3580 		if (dev &&
   3581 		    dev->status == P2P_SC_FAIL_INFO_CURRENTLY_UNAVAILABLE)
   3582 			dev->flags |= P2P_DEV_PEER_WAITING_RESPONSE;
   3583 	}
   3584 
   3585 	if (p2p->state == P2P_SEARCH || p2p->state == P2P_SD_DURING_FIND)
   3586 		p2p_continue_find(p2p);
   3587 }
   3588 
   3589 
   3590 static void p2p_go_neg_conf_cb(struct p2p_data *p2p,
   3591 			       enum p2p_send_action_result result)
   3592 {
   3593 	struct p2p_device *dev;
   3594 
   3595 	p2p_dbg(p2p, "GO Negotiation Confirm TX callback: result=%d", result);
   3596 	if (result == P2P_SEND_ACTION_FAILED) {
   3597 		p2p->cfg->send_action_done(p2p->cfg->cb_ctx);
   3598 		p2p_go_neg_failed(p2p, -1);
   3599 		return;
   3600 	}
   3601 
   3602 	dev = p2p->go_neg_peer;
   3603 
   3604 	if (result == P2P_SEND_ACTION_NO_ACK) {
   3605 		/*
   3606 		 * Retry GO Negotiation Confirmation
   3607 		 * P2P_GO_NEG_CNF_MAX_RETRY_COUNT times if we did not receive
   3608 		 * ACK for confirmation.
   3609 		 */
   3610 		if (dev && dev->go_neg_conf &&
   3611 		    dev->go_neg_conf_sent <= P2P_GO_NEG_CNF_MAX_RETRY_COUNT) {
   3612 			p2p_dbg(p2p, "GO Negotiation Confirm retry %d",
   3613 				dev->go_neg_conf_sent);
   3614 			p2p->pending_action_state = P2P_PENDING_GO_NEG_CONFIRM;
   3615 			if (p2p_send_action(p2p, dev->go_neg_conf_freq,
   3616 					    dev->info.p2p_device_addr,
   3617 					    p2p->cfg->dev_addr,
   3618 					    dev->info.p2p_device_addr,
   3619 					    wpabuf_head(dev->go_neg_conf),
   3620 					    wpabuf_len(dev->go_neg_conf), 0) >=
   3621 			    0) {
   3622 				dev->go_neg_conf_sent++;
   3623 				return;
   3624 			}
   3625 			p2p_dbg(p2p, "Failed to re-send Action frame");
   3626 
   3627 			/*
   3628 			 * Continue with the assumption that the first attempt
   3629 			 * went through and just the ACK frame was lost.
   3630 			 */
   3631 		}
   3632 
   3633 		/*
   3634 		 * It looks like the TX status for GO Negotiation Confirm is
   3635 		 * often showing failure even when the peer has actually
   3636 		 * received the frame. Since the peer may change channels
   3637 		 * immediately after having received the frame, we may not see
   3638 		 * an Ack for retries, so just dropping a single frame may
   3639 		 * trigger this. To allow the group formation to succeed if the
   3640 		 * peer did indeed receive the frame, continue regardless of
   3641 		 * the TX status.
   3642 		 */
   3643 		p2p_dbg(p2p, "Assume GO Negotiation Confirm TX was actually received by the peer even though Ack was not reported");
   3644 	}
   3645 
   3646 	p2p->cfg->send_action_done(p2p->cfg->cb_ctx);
   3647 
   3648 	if (dev == NULL)
   3649 		return;
   3650 
   3651 	p2p_go_complete(p2p, dev);
   3652 }
   3653 
   3654 
   3655 void p2p_send_action_cb(struct p2p_data *p2p, unsigned int freq, const u8 *dst,
   3656 			const u8 *src, const u8 *bssid,
   3657 			enum p2p_send_action_result result)
   3658 {
   3659 	enum p2p_pending_action_state state;
   3660 	int success;
   3661 
   3662 	p2p_dbg(p2p, "Action frame TX callback (state=%d freq=%u dst=" MACSTR
   3663 		" src=" MACSTR " bssid=" MACSTR " result=%d p2p_state=%s)",
   3664 		p2p->pending_action_state, freq, MAC2STR(dst), MAC2STR(src),
   3665 		MAC2STR(bssid), result, p2p_state_txt(p2p->state));
   3666 	success = result == P2P_SEND_ACTION_SUCCESS;
   3667 	state = p2p->pending_action_state;
   3668 	p2p->pending_action_state = P2P_NO_PENDING_ACTION;
   3669 	switch (state) {
   3670 	case P2P_NO_PENDING_ACTION:
   3671 		if (p2p->send_action_in_progress) {
   3672 			p2p->send_action_in_progress = 0;
   3673 			p2p->cfg->send_action_done(p2p->cfg->cb_ctx);
   3674 		}
   3675 		p2p_check_after_scan_tx_continuation(p2p);
   3676 		break;
   3677 	case P2P_PENDING_GO_NEG_REQUEST:
   3678 		p2p_go_neg_req_cb(p2p, success);
   3679 		break;
   3680 	case P2P_PENDING_GO_NEG_RESPONSE:
   3681 		p2p_go_neg_resp_cb(p2p, success);
   3682 		break;
   3683 	case P2P_PENDING_GO_NEG_RESPONSE_FAILURE:
   3684 		p2p_go_neg_resp_failure_cb(p2p, success, dst);
   3685 		break;
   3686 	case P2P_PENDING_GO_NEG_CONFIRM:
   3687 		p2p_go_neg_conf_cb(p2p, result);
   3688 		break;
   3689 	case P2P_PENDING_SD:
   3690 		p2p_sd_cb(p2p, success);
   3691 		break;
   3692 	case P2P_PENDING_PD:
   3693 		p2p_prov_disc_cb(p2p, success);
   3694 		break;
   3695 	case P2P_PENDING_PD_RESPONSE:
   3696 		p2p_prov_disc_resp_cb(p2p, success);
   3697 		break;
   3698 	case P2P_PENDING_INVITATION_REQUEST:
   3699 		p2p_invitation_req_cb(p2p, success);
   3700 		break;
   3701 	case P2P_PENDING_INVITATION_RESPONSE:
   3702 		p2p_invitation_resp_cb(p2p, success);
   3703 		break;
   3704 	case P2P_PENDING_DEV_DISC_REQUEST:
   3705 		p2p_dev_disc_req_cb(p2p, success);
   3706 		break;
   3707 	case P2P_PENDING_DEV_DISC_RESPONSE:
   3708 		p2p_dev_disc_resp_cb(p2p, success);
   3709 		break;
   3710 	case P2P_PENDING_GO_DISC_REQ:
   3711 		p2p_go_disc_req_cb(p2p, success);
   3712 		break;
   3713 	}
   3714 
   3715 	p2p->after_scan_tx_in_progress = 0;
   3716 }
   3717 
   3718 
   3719 void p2p_listen_cb(struct p2p_data *p2p, unsigned int freq,
   3720 		   unsigned int duration)
   3721 {
   3722 	if (freq == p2p->pending_client_disc_freq) {
   3723 		p2p_dbg(p2p, "Client discoverability remain-awake completed");
   3724 		p2p->pending_client_disc_freq = 0;
   3725 		return;
   3726 	}
   3727 
   3728 	if (freq != p2p->pending_listen_freq) {
   3729 		p2p_dbg(p2p, "Unexpected listen callback for freq=%u duration=%u (pending_listen_freq=%u)",
   3730 			freq, duration, p2p->pending_listen_freq);
   3731 		return;
   3732 	}
   3733 
   3734 	p2p_dbg(p2p, "Starting Listen timeout(%u,%u) on freq=%u based on callback",
   3735 		p2p->pending_listen_sec, p2p->pending_listen_usec,
   3736 		p2p->pending_listen_freq);
   3737 	p2p->in_listen = 1;
   3738 	p2p->drv_in_listen = freq;
   3739 	if (p2p->pending_listen_sec || p2p->pending_listen_usec) {
   3740 		/*
   3741 		 * Add 20 msec extra wait to avoid race condition with driver
   3742 		 * remain-on-channel end event, i.e., give driver more time to
   3743 		 * complete the operation before our timeout expires.
   3744 		 */
   3745 		p2p_set_timeout(p2p, p2p->pending_listen_sec,
   3746 				p2p->pending_listen_usec + 20000);
   3747 	}
   3748 
   3749 	p2p->pending_listen_freq = 0;
   3750 }
   3751 
   3752 
   3753 int p2p_listen_end(struct p2p_data *p2p, unsigned int freq)
   3754 {
   3755 	p2p_dbg(p2p, "Driver ended Listen state (freq=%u)", freq);
   3756 	p2p->drv_in_listen = 0;
   3757 	if (p2p->in_listen)
   3758 		return 0; /* Internal timeout will trigger the next step */
   3759 
   3760 	if (p2p->state == P2P_CONNECT_LISTEN && p2p->go_neg_peer) {
   3761 		if (p2p->go_neg_peer->connect_reqs >= 120) {
   3762 			p2p_dbg(p2p, "Timeout on sending GO Negotiation Request without getting response");
   3763 			p2p_go_neg_failed(p2p, -1);
   3764 			return 0;
   3765 		}
   3766 
   3767 		p2p_set_state(p2p, P2P_CONNECT);
   3768 		p2p_connect_send(p2p, p2p->go_neg_peer);
   3769 		return 1;
   3770 	} else if (p2p->state == P2P_SEARCH) {
   3771 		if (p2p->p2p_scan_running) {
   3772 			 /*
   3773 			  * Search is already in progress. This can happen if
   3774 			  * an Action frame RX is reported immediately after
   3775 			  * the end of a remain-on-channel operation and the
   3776 			  * response frame to that is sent using an offchannel
   3777 			  * operation while in p2p_find. Avoid an attempt to
   3778 			  * restart a scan here.
   3779 			  */
   3780 			p2p_dbg(p2p, "p2p_scan already in progress - do not try to start a new one");
   3781 			return 1;
   3782 		}
   3783 		if (p2p->pending_listen_freq) {
   3784 			/*
   3785 			 * Better wait a bit if the driver is unable to start
   3786 			 * offchannel operation for some reason. p2p_search()
   3787 			 * will be started from internal timeout.
   3788 			 */
   3789 			p2p_dbg(p2p, "Listen operation did not seem to start - delay search phase to avoid busy loop");
   3790 			p2p_set_timeout(p2p, 0, 100000);
   3791 			return 1;
   3792 		}
   3793 		if (p2p->search_delay) {
   3794 			p2p_dbg(p2p, "Delay search operation by %u ms",
   3795 				p2p->search_delay);
   3796 			p2p_set_timeout(p2p, p2p->search_delay / 1000,
   3797 					(p2p->search_delay % 1000) * 1000);
   3798 			return 1;
   3799 		}
   3800 		p2p_search(p2p);
   3801 		return 1;
   3802 	}
   3803 
   3804 	return 0;
   3805 }
   3806 
   3807 
   3808 static void p2p_timeout_connect(struct p2p_data *p2p)
   3809 {
   3810 	p2p->cfg->send_action_done(p2p->cfg->cb_ctx);
   3811 	if (p2p->go_neg_peer &&
   3812 	    (p2p->go_neg_peer->flags & P2P_DEV_WAIT_GO_NEG_CONFIRM)) {
   3813 		p2p_dbg(p2p, "Wait for GO Negotiation Confirm timed out - assume GO Negotiation failed");
   3814 		p2p_go_neg_failed(p2p, -1);
   3815 		return;
   3816 	}
   3817 	if (p2p->go_neg_peer &&
   3818 	    (p2p->go_neg_peer->flags & P2P_DEV_PEER_WAITING_RESPONSE) &&
   3819 	    p2p->go_neg_peer->connect_reqs < 120) {
   3820 		p2p_dbg(p2p, "Peer expected to wait our response - skip listen");
   3821 		p2p_connect_send(p2p, p2p->go_neg_peer);
   3822 		return;
   3823 	}
   3824 	if (p2p->go_neg_peer && p2p->go_neg_peer->oob_go_neg_freq > 0) {
   3825 		p2p_dbg(p2p, "Skip connect-listen since GO Neg channel known (OOB)");
   3826 		p2p_set_state(p2p, P2P_CONNECT_LISTEN);
   3827 		p2p_set_timeout(p2p, 0, 30000);
   3828 		return;
   3829 	}
   3830 	p2p_set_state(p2p, P2P_CONNECT_LISTEN);
   3831 	p2p_listen_in_find(p2p, 0);
   3832 }
   3833 
   3834 
   3835 static void p2p_timeout_connect_listen(struct p2p_data *p2p)
   3836 {
   3837 	if (p2p->go_neg_peer) {
   3838 		if (p2p->drv_in_listen) {
   3839 			p2p_dbg(p2p, "Driver is still in Listen state; wait for it to complete");
   3840 			return;
   3841 		}
   3842 
   3843 		if (p2p->go_neg_peer->connect_reqs >= 120) {
   3844 			p2p_dbg(p2p, "Timeout on sending GO Negotiation Request without getting response");
   3845 			p2p_go_neg_failed(p2p, -1);
   3846 			return;
   3847 		}
   3848 
   3849 		p2p_set_state(p2p, P2P_CONNECT);
   3850 		p2p_connect_send(p2p, p2p->go_neg_peer);
   3851 	} else
   3852 		p2p_set_state(p2p, P2P_IDLE);
   3853 }
   3854 
   3855 
   3856 static void p2p_timeout_wait_peer_connect(struct p2p_data *p2p)
   3857 {
   3858 	p2p_set_state(p2p, P2P_WAIT_PEER_IDLE);
   3859 
   3860 	if (p2p->cfg->is_concurrent_session_active &&
   3861 	    p2p->cfg->is_concurrent_session_active(p2p->cfg->cb_ctx))
   3862 		p2p_set_timeout(p2p, 0, 500000);
   3863 	else
   3864 		p2p_set_timeout(p2p, 0, 200000);
   3865 }
   3866 
   3867 
   3868 static void p2p_timeout_wait_peer_idle(struct p2p_data *p2p)
   3869 {
   3870 	struct p2p_device *dev = p2p->go_neg_peer;
   3871 
   3872 	if (dev == NULL) {
   3873 		p2p_dbg(p2p, "Unknown GO Neg peer - stop GO Neg wait");
   3874 		return;
   3875 	}
   3876 
   3877 	p2p_dbg(p2p, "Go to Listen state while waiting for the peer to become ready for GO Negotiation");
   3878 	p2p_set_state(p2p, P2P_WAIT_PEER_CONNECT);
   3879 	p2p_listen_in_find(p2p, 0);
   3880 }
   3881 
   3882 
   3883 static void p2p_timeout_sd_during_find(struct p2p_data *p2p)
   3884 {
   3885 	p2p_dbg(p2p, "Service Discovery Query timeout");
   3886 	if (p2p->sd_peer) {
   3887 		p2p->cfg->send_action_done(p2p->cfg->cb_ctx);
   3888 		p2p->sd_peer = NULL;
   3889 	}
   3890 	p2p_continue_find(p2p);
   3891 }
   3892 
   3893 
   3894 static void p2p_timeout_prov_disc_during_find(struct p2p_data *p2p)
   3895 {
   3896 	p2p_dbg(p2p, "Provision Discovery Request timeout");
   3897 	p2p->cfg->send_action_done(p2p->cfg->cb_ctx);
   3898 	p2p_continue_find(p2p);
   3899 }
   3900 
   3901 
   3902 static void p2p_timeout_prov_disc_req(struct p2p_data *p2p)
   3903 {
   3904 	u32 adv_id = 0;
   3905 	u8 *adv_mac = NULL;
   3906 
   3907 	p2p->pending_action_state = P2P_NO_PENDING_ACTION;
   3908 
   3909 	/*
   3910 	 * For user initiated PD requests that we have not gotten any responses
   3911 	 * for while in IDLE state, we retry them a couple of times before
   3912 	 * giving up.
   3913 	 */
   3914 	if (!p2p->user_initiated_pd)
   3915 		return;
   3916 
   3917 	p2p_dbg(p2p, "User initiated Provision Discovery Request timeout");
   3918 
   3919 	if (p2p->pd_retries) {
   3920 		p2p->pd_retries--;
   3921 		p2p_retry_pd(p2p);
   3922 	} else {
   3923 		struct p2p_device *dev;
   3924 		int for_join = 0;
   3925 
   3926 		dl_list_for_each(dev, &p2p->devices, struct p2p_device, list) {
   3927 			if (os_memcmp(p2p->pending_pd_devaddr,
   3928 				      dev->info.p2p_device_addr, ETH_ALEN) != 0)
   3929 				continue;
   3930 			if (dev->req_config_methods &&
   3931 			    (dev->flags & P2P_DEV_PD_FOR_JOIN))
   3932 				for_join = 1;
   3933 		}
   3934 
   3935 		if (p2p->p2ps_prov) {
   3936 			adv_id = p2p->p2ps_prov->adv_id;
   3937 			adv_mac = p2p->p2ps_prov->adv_mac;
   3938 		}
   3939 
   3940 		if (p2p->cfg->prov_disc_fail)
   3941 			p2p->cfg->prov_disc_fail(p2p->cfg->cb_ctx,
   3942 						 p2p->pending_pd_devaddr,
   3943 						 for_join ?
   3944 						 P2P_PROV_DISC_TIMEOUT_JOIN :
   3945 						 P2P_PROV_DISC_TIMEOUT,
   3946 						 adv_id, adv_mac, NULL);
   3947 		p2p_reset_pending_pd(p2p);
   3948 	}
   3949 }
   3950 
   3951 
   3952 static void p2p_timeout_invite(struct p2p_data *p2p)
   3953 {
   3954 	p2p->cfg->send_action_done(p2p->cfg->cb_ctx);
   3955 	p2p_set_state(p2p, P2P_INVITE_LISTEN);
   3956 	if (p2p->inv_role == P2P_INVITE_ROLE_ACTIVE_GO) {
   3957 		/*
   3958 		 * Better remain on operating channel instead of listen channel
   3959 		 * when running a group.
   3960 		 */
   3961 		p2p_dbg(p2p, "Inviting in active GO role - wait on operating channel");
   3962 		p2p_set_timeout(p2p, 0, 100000);
   3963 		return;
   3964 	}
   3965 	p2p_listen_in_find(p2p, 0);
   3966 }
   3967 
   3968 
   3969 static void p2p_timeout_invite_listen(struct p2p_data *p2p)
   3970 {
   3971 	if (p2p->invite_peer && p2p->invite_peer->invitation_reqs < 100) {
   3972 		p2p_set_state(p2p, P2P_INVITE);
   3973 		p2p_invite_send(p2p, p2p->invite_peer,
   3974 				p2p->invite_go_dev_addr, p2p->invite_dev_pw_id);
   3975 	} else {
   3976 		if (p2p->invite_peer) {
   3977 			p2p_dbg(p2p, "Invitation Request retry limit reached");
   3978 			if (p2p->cfg->invitation_result)
   3979 				p2p->cfg->invitation_result(
   3980 					p2p->cfg->cb_ctx, -1, NULL, NULL,
   3981 					p2p->invite_peer->info.p2p_device_addr,
   3982 					0, 0);
   3983 		}
   3984 		p2p_set_state(p2p, P2P_IDLE);
   3985 	}
   3986 }
   3987 
   3988 
   3989 static void p2p_state_timeout(void *eloop_ctx, void *timeout_ctx)
   3990 {
   3991 	struct p2p_data *p2p = eloop_ctx;
   3992 
   3993 	p2p_dbg(p2p, "Timeout (state=%s)", p2p_state_txt(p2p->state));
   3994 
   3995 	p2p->in_listen = 0;
   3996 	if (p2p->drv_in_listen) {
   3997 		p2p_dbg(p2p, "Driver is still in listen state - stop it");
   3998 		p2p->cfg->stop_listen(p2p->cfg->cb_ctx);
   3999 	}
   4000 
   4001 	switch (p2p->state) {
   4002 	case P2P_IDLE:
   4003 		/* Check if we timed out waiting for PD req */
   4004 		if (p2p->pending_action_state == P2P_PENDING_PD)
   4005 			p2p_timeout_prov_disc_req(p2p);
   4006 		break;
   4007 	case P2P_SEARCH:
   4008 		/* Check if we timed out waiting for PD req */
   4009 		if (p2p->pending_action_state == P2P_PENDING_PD)
   4010 			p2p_timeout_prov_disc_req(p2p);
   4011 		if (p2p->search_delay && !p2p->in_search_delay) {
   4012 			p2p_dbg(p2p, "Delay search operation by %u ms",
   4013 				p2p->search_delay);
   4014 			p2p->in_search_delay = 1;
   4015 			p2p_set_timeout(p2p, p2p->search_delay / 1000,
   4016 					(p2p->search_delay % 1000) * 1000);
   4017 			break;
   4018 		}
   4019 		p2p->in_search_delay = 0;
   4020 		p2p_search(p2p);
   4021 		break;
   4022 	case P2P_CONNECT:
   4023 		p2p_timeout_connect(p2p);
   4024 		break;
   4025 	case P2P_CONNECT_LISTEN:
   4026 		p2p_timeout_connect_listen(p2p);
   4027 		break;
   4028 	case P2P_GO_NEG:
   4029 		break;
   4030 	case P2P_LISTEN_ONLY:
   4031 		/* Check if we timed out waiting for PD req */
   4032 		if (p2p->pending_action_state == P2P_PENDING_PD)
   4033 			p2p_timeout_prov_disc_req(p2p);
   4034 
   4035 		if (p2p->ext_listen_only) {
   4036 			p2p_dbg(p2p, "Extended Listen Timing - Listen State completed");
   4037 			p2p->ext_listen_only = 0;
   4038 			p2p_set_state(p2p, P2P_IDLE);
   4039 		}
   4040 		break;
   4041 	case P2P_WAIT_PEER_CONNECT:
   4042 		p2p_timeout_wait_peer_connect(p2p);
   4043 		break;
   4044 	case P2P_WAIT_PEER_IDLE:
   4045 		p2p_timeout_wait_peer_idle(p2p);
   4046 		break;
   4047 	case P2P_SD_DURING_FIND:
   4048 		p2p_timeout_sd_during_find(p2p);
   4049 		break;
   4050 	case P2P_PROVISIONING:
   4051 		break;
   4052 	case P2P_PD_DURING_FIND:
   4053 		p2p_timeout_prov_disc_during_find(p2p);
   4054 		break;
   4055 	case P2P_INVITE:
   4056 		p2p_timeout_invite(p2p);
   4057 		break;
   4058 	case P2P_INVITE_LISTEN:
   4059 		p2p_timeout_invite_listen(p2p);
   4060 		break;
   4061 	}
   4062 }
   4063 
   4064 
   4065 int p2p_reject(struct p2p_data *p2p, const u8 *peer_addr)
   4066 {
   4067 	struct p2p_device *dev;
   4068 
   4069 	dev = p2p_get_device(p2p, peer_addr);
   4070 	p2p_dbg(p2p, "Local request to reject connection attempts by peer "
   4071 		MACSTR, MAC2STR(peer_addr));
   4072 	if (dev == NULL) {
   4073 		p2p_dbg(p2p, "Peer " MACSTR " unknown", MAC2STR(peer_addr));
   4074 		return -1;
   4075 	}
   4076 	dev->status = P2P_SC_FAIL_REJECTED_BY_USER;
   4077 	dev->flags |= P2P_DEV_USER_REJECTED;
   4078 	return 0;
   4079 }
   4080 
   4081 
   4082 const char * p2p_wps_method_text(enum p2p_wps_method method)
   4083 {
   4084 	switch (method) {
   4085 	case WPS_NOT_READY:
   4086 		return "not-ready";
   4087 	case WPS_PIN_DISPLAY:
   4088 		return "Display";
   4089 	case WPS_PIN_KEYPAD:
   4090 		return "Keypad";
   4091 	case WPS_PBC:
   4092 		return "PBC";
   4093 	case WPS_NFC:
   4094 		return "NFC";
   4095 	case WPS_P2PS:
   4096 		return "P2PS";
   4097 	}
   4098 
   4099 	return "??";
   4100 }
   4101 
   4102 
   4103 static const char * p2p_go_state_text(enum p2p_go_state go_state)
   4104 {
   4105 	switch (go_state) {
   4106 	case UNKNOWN_GO:
   4107 		return "unknown";
   4108 	case LOCAL_GO:
   4109 		return "local";
   4110 	case  REMOTE_GO:
   4111 		return "remote";
   4112 	}
   4113 
   4114 	return "??";
   4115 }
   4116 
   4117 
   4118 const struct p2p_peer_info * p2p_get_peer_info(struct p2p_data *p2p,
   4119 					       const u8 *addr, int next)
   4120 {
   4121 	struct p2p_device *dev;
   4122 
   4123 	if (addr)
   4124 		dev = p2p_get_device(p2p, addr);
   4125 	else
   4126 		dev = dl_list_first(&p2p->devices, struct p2p_device, list);
   4127 
   4128 	if (dev && next) {
   4129 		dev = dl_list_first(&dev->list, struct p2p_device, list);
   4130 		if (&dev->list == &p2p->devices)
   4131 			dev = NULL;
   4132 	}
   4133 
   4134 	if (dev == NULL)
   4135 		return NULL;
   4136 
   4137 	return &dev->info;
   4138 }
   4139 
   4140 
   4141 int p2p_get_peer_info_txt(const struct p2p_peer_info *info,
   4142 			  char *buf, size_t buflen)
   4143 {
   4144 	struct p2p_device *dev;
   4145 	int res;
   4146 	char *pos, *end;
   4147 	struct os_reltime now;
   4148 
   4149 	if (info == NULL)
   4150 		return -1;
   4151 
   4152 	dev = (struct p2p_device *) (((u8 *) info) -
   4153 				     offsetof(struct p2p_device, info));
   4154 
   4155 	pos = buf;
   4156 	end = buf + buflen;
   4157 
   4158 	os_get_reltime(&now);
   4159 	res = os_snprintf(pos, end - pos,
   4160 			  "age=%d\n"
   4161 			  "listen_freq=%d\n"
   4162 			  "wps_method=%s\n"
   4163 			  "interface_addr=" MACSTR "\n"
   4164 			  "member_in_go_dev=" MACSTR "\n"
   4165 			  "member_in_go_iface=" MACSTR "\n"
   4166 			  "go_neg_req_sent=%d\n"
   4167 			  "go_state=%s\n"
   4168 			  "dialog_token=%u\n"
   4169 			  "intended_addr=" MACSTR "\n"
   4170 			  "country=%c%c\n"
   4171 			  "oper_freq=%d\n"
   4172 			  "req_config_methods=0x%x\n"
   4173 			  "flags=%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n"
   4174 			  "status=%d\n"
   4175 			  "invitation_reqs=%u\n",
   4176 			  (int) (now.sec - dev->last_seen.sec),
   4177 			  dev->listen_freq,
   4178 			  p2p_wps_method_text(dev->wps_method),
   4179 			  MAC2STR(dev->interface_addr),
   4180 			  MAC2STR(dev->member_in_go_dev),
   4181 			  MAC2STR(dev->member_in_go_iface),
   4182 			  dev->go_neg_req_sent,
   4183 			  p2p_go_state_text(dev->go_state),
   4184 			  dev->dialog_token,
   4185 			  MAC2STR(dev->intended_addr),
   4186 			  dev->country[0] ? dev->country[0] : '_',
   4187 			  dev->country[1] ? dev->country[1] : '_',
   4188 			  dev->oper_freq,
   4189 			  dev->req_config_methods,
   4190 			  dev->flags & P2P_DEV_PROBE_REQ_ONLY ?
   4191 			  "[PROBE_REQ_ONLY]" : "",
   4192 			  dev->flags & P2P_DEV_REPORTED ? "[REPORTED]" : "",
   4193 			  dev->flags & P2P_DEV_NOT_YET_READY ?
   4194 			  "[NOT_YET_READY]" : "",
   4195 			  dev->flags & P2P_DEV_PD_PEER_DISPLAY ?
   4196 			  "[PD_PEER_DISPLAY]" : "",
   4197 			  dev->flags & P2P_DEV_PD_PEER_KEYPAD ?
   4198 			  "[PD_PEER_KEYPAD]" : "",
   4199 			  dev->flags & P2P_DEV_PD_PEER_P2PS ?
   4200 			  "[PD_PEER_P2PS]" : "",
   4201 			  dev->flags & P2P_DEV_USER_REJECTED ?
   4202 			  "[USER_REJECTED]" : "",
   4203 			  dev->flags & P2P_DEV_PEER_WAITING_RESPONSE ?
   4204 			  "[PEER_WAITING_RESPONSE]" : "",
   4205 			  dev->flags & P2P_DEV_PREFER_PERSISTENT_GROUP ?
   4206 			  "[PREFER_PERSISTENT_GROUP]" : "",
   4207 			  dev->flags & P2P_DEV_WAIT_GO_NEG_RESPONSE ?
   4208 			  "[WAIT_GO_NEG_RESPONSE]" : "",
   4209 			  dev->flags & P2P_DEV_WAIT_GO_NEG_CONFIRM ?
   4210 			  "[WAIT_GO_NEG_CONFIRM]" : "",
   4211 			  dev->flags & P2P_DEV_GROUP_CLIENT_ONLY ?
   4212 			  "[GROUP_CLIENT_ONLY]" : "",
   4213 			  dev->flags & P2P_DEV_FORCE_FREQ ?
   4214 			  "[FORCE_FREQ]" : "",
   4215 			  dev->flags & P2P_DEV_PD_FOR_JOIN ?
   4216 			  "[PD_FOR_JOIN]" : "",
   4217 			  dev->flags & P2P_DEV_LAST_SEEN_AS_GROUP_CLIENT ?
   4218 			  "[LAST_SEEN_AS_GROUP_CLIENT]" : "",
   4219 			  dev->status,
   4220 			  dev->invitation_reqs);
   4221 	if (os_snprintf_error(end - pos, res))
   4222 		return pos - buf;
   4223 	pos += res;
   4224 
   4225 	if (dev->ext_listen_period) {
   4226 		res = os_snprintf(pos, end - pos,
   4227 				  "ext_listen_period=%u\n"
   4228 				  "ext_listen_interval=%u\n",
   4229 				  dev->ext_listen_period,
   4230 				  dev->ext_listen_interval);
   4231 		if (os_snprintf_error(end - pos, res))
   4232 			return pos - buf;
   4233 		pos += res;
   4234 	}
   4235 
   4236 	if (dev->oper_ssid_len) {
   4237 		res = os_snprintf(pos, end - pos,
   4238 				  "oper_ssid=%s\n",
   4239 				  wpa_ssid_txt(dev->oper_ssid,
   4240 					       dev->oper_ssid_len));
   4241 		if (os_snprintf_error(end - pos, res))
   4242 			return pos - buf;
   4243 		pos += res;
   4244 	}
   4245 
   4246 #ifdef CONFIG_WIFI_DISPLAY
   4247 	if (dev->info.wfd_subelems) {
   4248 		res = os_snprintf(pos, end - pos, "wfd_subelems=");
   4249 		if (os_snprintf_error(end - pos, res))
   4250 			return pos - buf;
   4251 		pos += res;
   4252 
   4253 		pos += wpa_snprintf_hex(pos, end - pos,
   4254 					wpabuf_head(dev->info.wfd_subelems),
   4255 					wpabuf_len(dev->info.wfd_subelems));
   4256 
   4257 		res = os_snprintf(pos, end - pos, "\n");
   4258 		if (os_snprintf_error(end - pos, res))
   4259 			return pos - buf;
   4260 		pos += res;
   4261 	}
   4262 #endif /* CONFIG_WIFI_DISPLAY */
   4263 
   4264 	return pos - buf;
   4265 }
   4266 
   4267 
   4268 int p2p_peer_known(struct p2p_data *p2p, const u8 *addr)
   4269 {
   4270 	return p2p_get_device(p2p, addr) != NULL;
   4271 }
   4272 
   4273 
   4274 void p2p_set_client_discoverability(struct p2p_data *p2p, int enabled)
   4275 {
   4276 	if (enabled) {
   4277 		p2p_dbg(p2p, "Client discoverability enabled");
   4278 		p2p->dev_capab |= P2P_DEV_CAPAB_CLIENT_DISCOVERABILITY;
   4279 	} else {
   4280 		p2p_dbg(p2p, "Client discoverability disabled");
   4281 		p2p->dev_capab &= ~P2P_DEV_CAPAB_CLIENT_DISCOVERABILITY;
   4282 	}
   4283 }
   4284 
   4285 
   4286 static struct wpabuf * p2p_build_presence_req(u32 duration1, u32 interval1,
   4287 					      u32 duration2, u32 interval2)
   4288 {
   4289 	struct wpabuf *req;
   4290 	struct p2p_noa_desc desc1, desc2, *ptr1 = NULL, *ptr2 = NULL;
   4291 	u8 *len;
   4292 
   4293 	req = wpabuf_alloc(100);
   4294 	if (req == NULL)
   4295 		return NULL;
   4296 
   4297 	if (duration1 || interval1) {
   4298 		os_memset(&desc1, 0, sizeof(desc1));
   4299 		desc1.count_type = 1;
   4300 		desc1.duration = duration1;
   4301 		desc1.interval = interval1;
   4302 		ptr1 = &desc1;
   4303 
   4304 		if (duration2 || interval2) {
   4305 			os_memset(&desc2, 0, sizeof(desc2));
   4306 			desc2.count_type = 2;
   4307 			desc2.duration = duration2;
   4308 			desc2.interval = interval2;
   4309 			ptr2 = &desc2;
   4310 		}
   4311 	}
   4312 
   4313 	p2p_buf_add_action_hdr(req, P2P_PRESENCE_REQ, 1);
   4314 	len = p2p_buf_add_ie_hdr(req);
   4315 	p2p_buf_add_noa(req, 0, 0, 0, ptr1, ptr2);
   4316 	p2p_buf_update_ie_hdr(req, len);
   4317 
   4318 	return req;
   4319 }
   4320 
   4321 
   4322 int p2p_presence_req(struct p2p_data *p2p, const u8 *go_interface_addr,
   4323 		     const u8 *own_interface_addr, unsigned int freq,
   4324 		     u32 duration1, u32 interval1, u32 duration2,
   4325 		     u32 interval2)
   4326 {
   4327 	struct wpabuf *req;
   4328 
   4329 	p2p_dbg(p2p, "Send Presence Request to GO " MACSTR
   4330 		" (own interface " MACSTR ") freq=%u dur1=%u int1=%u "
   4331 		"dur2=%u int2=%u",
   4332 		MAC2STR(go_interface_addr), MAC2STR(own_interface_addr),
   4333 		freq, duration1, interval1, duration2, interval2);
   4334 
   4335 	req = p2p_build_presence_req(duration1, interval1, duration2,
   4336 				     interval2);
   4337 	if (req == NULL)
   4338 		return -1;
   4339 
   4340 	p2p->pending_action_state = P2P_NO_PENDING_ACTION;
   4341 	if (p2p_send_action(p2p, freq, go_interface_addr, own_interface_addr,
   4342 			    go_interface_addr,
   4343 			    wpabuf_head(req), wpabuf_len(req), 200) < 0) {
   4344 		p2p_dbg(p2p, "Failed to send Action frame");
   4345 	}
   4346 	wpabuf_free(req);
   4347 
   4348 	return 0;
   4349 }
   4350 
   4351 
   4352 static struct wpabuf * p2p_build_presence_resp(u8 status, const u8 *noa,
   4353 					       size_t noa_len, u8 dialog_token)
   4354 {
   4355 	struct wpabuf *resp;
   4356 	u8 *len;
   4357 
   4358 	resp = wpabuf_alloc(100 + noa_len);
   4359 	if (resp == NULL)
   4360 		return NULL;
   4361 
   4362 	p2p_buf_add_action_hdr(resp, P2P_PRESENCE_RESP, dialog_token);
   4363 	len = p2p_buf_add_ie_hdr(resp);
   4364 	p2p_buf_add_status(resp, status);
   4365 	if (noa) {
   4366 		wpabuf_put_u8(resp, P2P_ATTR_NOTICE_OF_ABSENCE);
   4367 		wpabuf_put_le16(resp, noa_len);
   4368 		wpabuf_put_data(resp, noa, noa_len);
   4369 	} else
   4370 		p2p_buf_add_noa(resp, 0, 0, 0, NULL, NULL);
   4371 	p2p_buf_update_ie_hdr(resp, len);
   4372 
   4373 	return resp;
   4374 }
   4375 
   4376 
   4377 static void p2p_process_presence_req(struct p2p_data *p2p, const u8 *da,
   4378 				     const u8 *sa, const u8 *data, size_t len,
   4379 				     int rx_freq)
   4380 {
   4381 	struct p2p_message msg;
   4382 	u8 status;
   4383 	struct wpabuf *resp;
   4384 	size_t g;
   4385 	struct p2p_group *group = NULL;
   4386 	int parsed = 0;
   4387 	u8 noa[50];
   4388 	int noa_len;
   4389 
   4390 	p2p_dbg(p2p, "Received P2P Action - P2P Presence Request");
   4391 
   4392 	for (g = 0; g < p2p->num_groups; g++) {
   4393 		if (os_memcmp(da, p2p_group_get_interface_addr(p2p->groups[g]),
   4394 			      ETH_ALEN) == 0) {
   4395 			group = p2p->groups[g];
   4396 			break;
   4397 		}
   4398 	}
   4399 	if (group == NULL) {
   4400 		p2p_dbg(p2p, "Ignore P2P Presence Request for unknown group "
   4401 			MACSTR, MAC2STR(da));
   4402 		return;
   4403 	}
   4404 
   4405 	if (p2p_parse(data, len, &msg) < 0) {
   4406 		p2p_dbg(p2p, "Failed to parse P2P Presence Request");
   4407 		status = P2P_SC_FAIL_INVALID_PARAMS;
   4408 		goto fail;
   4409 	}
   4410 	parsed = 1;
   4411 
   4412 	if (msg.noa == NULL) {
   4413 		p2p_dbg(p2p, "No NoA attribute in P2P Presence Request");
   4414 		status = P2P_SC_FAIL_INVALID_PARAMS;
   4415 		goto fail;
   4416 	}
   4417 
   4418 	status = p2p_group_presence_req(group, sa, msg.noa, msg.noa_len);
   4419 
   4420 fail:
   4421 	if (p2p->cfg->get_noa)
   4422 		noa_len = p2p->cfg->get_noa(p2p->cfg->cb_ctx, da, noa,
   4423 					    sizeof(noa));
   4424 	else
   4425 		noa_len = -1;
   4426 	resp = p2p_build_presence_resp(status, noa_len > 0 ? noa : NULL,
   4427 				       noa_len > 0 ? noa_len : 0,
   4428 				       msg.dialog_token);
   4429 	if (parsed)
   4430 		p2p_parse_free(&msg);
   4431 	if (resp == NULL)
   4432 		return;
   4433 
   4434 	p2p->pending_action_state = P2P_NO_PENDING_ACTION;
   4435 	if (p2p_send_action(p2p, rx_freq, sa, da, da,
   4436 			    wpabuf_head(resp), wpabuf_len(resp), 200) < 0) {
   4437 		p2p_dbg(p2p, "Failed to send Action frame");
   4438 	}
   4439 	wpabuf_free(resp);
   4440 }
   4441 
   4442 
   4443 static void p2p_process_presence_resp(struct p2p_data *p2p, const u8 *da,
   4444 				      const u8 *sa, const u8 *data, size_t len)
   4445 {
   4446 	struct p2p_message msg;
   4447 
   4448 	p2p_dbg(p2p, "Received P2P Action - P2P Presence Response");
   4449 
   4450 	if (p2p_parse(data, len, &msg) < 0) {
   4451 		p2p_dbg(p2p, "Failed to parse P2P Presence Response");
   4452 		return;
   4453 	}
   4454 
   4455 	if (msg.status == NULL || msg.noa == NULL) {
   4456 		p2p_dbg(p2p, "No Status or NoA attribute in P2P Presence Response");
   4457 		p2p_parse_free(&msg);
   4458 		return;
   4459 	}
   4460 
   4461 	if (p2p->cfg->presence_resp) {
   4462 		p2p->cfg->presence_resp(p2p->cfg->cb_ctx, sa, *msg.status,
   4463 					msg.noa, msg.noa_len);
   4464 	}
   4465 
   4466 	if (*msg.status) {
   4467 		p2p_dbg(p2p, "P2P Presence Request was rejected: status %u",
   4468 			*msg.status);
   4469 		p2p_parse_free(&msg);
   4470 		return;
   4471 	}
   4472 
   4473 	p2p_dbg(p2p, "P2P Presence Request was accepted");
   4474 	wpa_hexdump(MSG_DEBUG, "P2P: P2P Presence Response - NoA",
   4475 		    msg.noa, msg.noa_len);
   4476 	/* TODO: process NoA */
   4477 	p2p_parse_free(&msg);
   4478 }
   4479 
   4480 
   4481 static void p2p_ext_listen_timeout(void *eloop_ctx, void *timeout_ctx)
   4482 {
   4483 	struct p2p_data *p2p = eloop_ctx;
   4484 
   4485 	if (p2p->ext_listen_interval) {
   4486 		/* Schedule next extended listen timeout */
   4487 		eloop_register_timeout(p2p->ext_listen_interval_sec,
   4488 				       p2p->ext_listen_interval_usec,
   4489 				       p2p_ext_listen_timeout, p2p, NULL);
   4490 	}
   4491 
   4492 	if ((p2p->cfg->is_p2p_in_progress &&
   4493 	     p2p->cfg->is_p2p_in_progress(p2p->cfg->cb_ctx)) ||
   4494 	    (p2p->pending_action_state == P2P_PENDING_PD &&
   4495 	     p2p->pd_retries > 0)) {
   4496 		p2p_dbg(p2p, "Operation in progress - skip Extended Listen timeout (%s)",
   4497 			p2p_state_txt(p2p->state));
   4498 		return;
   4499 	}
   4500 
   4501 	if (p2p->state == P2P_LISTEN_ONLY && p2p->ext_listen_only) {
   4502 		/*
   4503 		 * This should not really happen, but it looks like the Listen
   4504 		 * command may fail is something else (e.g., a scan) was
   4505 		 * running at an inconvenient time. As a workaround, allow new
   4506 		 * Extended Listen operation to be started.
   4507 		 */
   4508 		p2p_dbg(p2p, "Previous Extended Listen operation had not been completed - try again");
   4509 		p2p->ext_listen_only = 0;
   4510 		p2p_set_state(p2p, P2P_IDLE);
   4511 	}
   4512 
   4513 	if (p2p->state != P2P_IDLE) {
   4514 		p2p_dbg(p2p, "Skip Extended Listen timeout in active state (%s)", p2p_state_txt(p2p->state));
   4515 		return;
   4516 	}
   4517 
   4518 	p2p_dbg(p2p, "Extended Listen timeout");
   4519 	p2p->ext_listen_only = 1;
   4520 	if (p2p_listen(p2p, p2p->ext_listen_period) < 0) {
   4521 		p2p_dbg(p2p, "Failed to start Listen state for Extended Listen Timing");
   4522 		p2p->ext_listen_only = 0;
   4523 	}
   4524 }
   4525 
   4526 
   4527 int p2p_ext_listen(struct p2p_data *p2p, unsigned int period,
   4528 		   unsigned int interval)
   4529 {
   4530 	if (period > 65535 || interval > 65535 || period > interval ||
   4531 	    (period == 0 && interval > 0) || (period > 0 && interval == 0)) {
   4532 		p2p_dbg(p2p, "Invalid Extended Listen Timing request: period=%u interval=%u",
   4533 			period, interval);
   4534 		return -1;
   4535 	}
   4536 
   4537 	eloop_cancel_timeout(p2p_ext_listen_timeout, p2p, NULL);
   4538 
   4539 	if (interval == 0) {
   4540 		p2p_dbg(p2p, "Disabling Extended Listen Timing");
   4541 		p2p->ext_listen_period = 0;
   4542 		p2p->ext_listen_interval = 0;
   4543 		return 0;
   4544 	}
   4545 
   4546 	p2p_dbg(p2p, "Enabling Extended Listen Timing: period %u msec, interval %u msec",
   4547 		period, interval);
   4548 	p2p->ext_listen_period = period;
   4549 	p2p->ext_listen_interval = interval;
   4550 	p2p->ext_listen_interval_sec = interval / 1000;
   4551 	p2p->ext_listen_interval_usec = (interval % 1000) * 1000;
   4552 
   4553 	eloop_register_timeout(p2p->ext_listen_interval_sec,
   4554 			       p2p->ext_listen_interval_usec,
   4555 			       p2p_ext_listen_timeout, p2p, NULL);
   4556 
   4557 	return 0;
   4558 }
   4559 
   4560 
   4561 void p2p_deauth_notif(struct p2p_data *p2p, const u8 *bssid, u16 reason_code,
   4562 		      const u8 *ie, size_t ie_len)
   4563 {
   4564 	struct p2p_message msg;
   4565 
   4566 	if (bssid == NULL || ie == NULL)
   4567 		return;
   4568 
   4569 	os_memset(&msg, 0, sizeof(msg));
   4570 	if (p2p_parse_ies(ie, ie_len, &msg))
   4571 		return;
   4572 	if (msg.minor_reason_code == NULL) {
   4573 		p2p_parse_free(&msg);
   4574 		return;
   4575 	}
   4576 
   4577 	p2p_dbg(p2p, "Deauthentication notification BSSID " MACSTR
   4578 		" reason_code=%u minor_reason_code=%u",
   4579 		MAC2STR(bssid), reason_code, *msg.minor_reason_code);
   4580 
   4581 	p2p_parse_free(&msg);
   4582 }
   4583 
   4584 
   4585 void p2p_disassoc_notif(struct p2p_data *p2p, const u8 *bssid, u16 reason_code,
   4586 			const u8 *ie, size_t ie_len)
   4587 {
   4588 	struct p2p_message msg;
   4589 
   4590 	if (bssid == NULL || ie == NULL)
   4591 		return;
   4592 
   4593 	os_memset(&msg, 0, sizeof(msg));
   4594 	if (p2p_parse_ies(ie, ie_len, &msg))
   4595 		return;
   4596 	if (msg.minor_reason_code == NULL) {
   4597 		p2p_parse_free(&msg);
   4598 		return;
   4599 	}
   4600 
   4601 	p2p_dbg(p2p, "Disassociation notification BSSID " MACSTR
   4602 		" reason_code=%u minor_reason_code=%u",
   4603 		MAC2STR(bssid), reason_code, *msg.minor_reason_code);
   4604 
   4605 	p2p_parse_free(&msg);
   4606 }
   4607 
   4608 
   4609 void p2p_set_managed_oper(struct p2p_data *p2p, int enabled)
   4610 {
   4611 	if (enabled) {
   4612 		p2p_dbg(p2p, "Managed P2P Device operations enabled");
   4613 		p2p->dev_capab |= P2P_DEV_CAPAB_INFRA_MANAGED;
   4614 	} else {
   4615 		p2p_dbg(p2p, "Managed P2P Device operations disabled");
   4616 		p2p->dev_capab &= ~P2P_DEV_CAPAB_INFRA_MANAGED;
   4617 	}
   4618 }
   4619 
   4620 
   4621 int p2p_config_get_random_social(struct p2p_config *p2p, u8 *op_class,
   4622 				 u8 *op_channel)
   4623 {
   4624 	return p2p_channel_random_social(&p2p->channels, op_class, op_channel);
   4625 }
   4626 
   4627 
   4628 int p2p_set_listen_channel(struct p2p_data *p2p, u8 reg_class, u8 channel,
   4629 			   u8 forced)
   4630 {
   4631 	if (p2p_channel_to_freq(reg_class, channel) < 0)
   4632 		return -1;
   4633 
   4634 	/*
   4635 	 * Listen channel was set in configuration or set by control interface;
   4636 	 * cannot override it.
   4637 	 */
   4638 	if (p2p->cfg->channel_forced && forced == 0) {
   4639 		p2p_dbg(p2p,
   4640 			"Listen channel was previously configured - do not override based on optimization");
   4641 		return -1;
   4642 	}
   4643 
   4644 	p2p_dbg(p2p, "Set Listen channel: reg_class %u channel %u",
   4645 		reg_class, channel);
   4646 
   4647 	if (p2p->state == P2P_IDLE) {
   4648 		p2p->cfg->reg_class = reg_class;
   4649 		p2p->cfg->channel = channel;
   4650 		p2p->cfg->channel_forced = forced;
   4651 	} else {
   4652 		p2p_dbg(p2p, "Defer setting listen channel");
   4653 		p2p->pending_reg_class = reg_class;
   4654 		p2p->pending_channel = channel;
   4655 		p2p->pending_channel_forced = forced;
   4656 	}
   4657 
   4658 	return 0;
   4659 }
   4660 
   4661 
   4662 u8 p2p_get_listen_channel(struct p2p_data *p2p)
   4663 {
   4664 	return p2p->cfg->channel;
   4665 }
   4666 
   4667 
   4668 int p2p_set_ssid_postfix(struct p2p_data *p2p, const u8 *postfix, size_t len)
   4669 {
   4670 	p2p_dbg(p2p, "New SSID postfix: %s", wpa_ssid_txt(postfix, len));
   4671 	if (postfix == NULL) {
   4672 		p2p->cfg->ssid_postfix_len = 0;
   4673 		return 0;
   4674 	}
   4675 	if (len > sizeof(p2p->cfg->ssid_postfix))
   4676 		return -1;
   4677 	os_memcpy(p2p->cfg->ssid_postfix, postfix, len);
   4678 	p2p->cfg->ssid_postfix_len = len;
   4679 	return 0;
   4680 }
   4681 
   4682 
   4683 int p2p_set_oper_channel(struct p2p_data *p2p, u8 op_reg_class, u8 op_channel,
   4684 			 int cfg_op_channel)
   4685 {
   4686 	if (p2p_channel_to_freq(op_reg_class, op_channel) < 0)
   4687 		return -1;
   4688 
   4689 	p2p_dbg(p2p, "Set Operating channel: reg_class %u channel %u",
   4690 		op_reg_class, op_channel);
   4691 	p2p->cfg->op_reg_class = op_reg_class;
   4692 	p2p->cfg->op_channel = op_channel;
   4693 	p2p->cfg->cfg_op_channel = cfg_op_channel;
   4694 	return 0;
   4695 }
   4696 
   4697 
   4698 int p2p_set_pref_chan(struct p2p_data *p2p, unsigned int num_pref_chan,
   4699 		      const struct p2p_channel *pref_chan)
   4700 {
   4701 	struct p2p_channel *n;
   4702 
   4703 	if (pref_chan) {
   4704 		n = os_malloc(num_pref_chan * sizeof(struct p2p_channel));
   4705 		if (n == NULL)
   4706 			return -1;
   4707 		os_memcpy(n, pref_chan,
   4708 			  num_pref_chan * sizeof(struct p2p_channel));
   4709 	} else
   4710 		n = NULL;
   4711 
   4712 	os_free(p2p->cfg->pref_chan);
   4713 	p2p->cfg->pref_chan = n;
   4714 	p2p->cfg->num_pref_chan = num_pref_chan;
   4715 
   4716 	return 0;
   4717 }
   4718 
   4719 
   4720 int p2p_set_no_go_freq(struct p2p_data *p2p,
   4721 		       const struct wpa_freq_range_list *list)
   4722 {
   4723 	struct wpa_freq_range *tmp;
   4724 
   4725 	if (list == NULL || list->num == 0) {
   4726 		os_free(p2p->no_go_freq.range);
   4727 		p2p->no_go_freq.range = NULL;
   4728 		p2p->no_go_freq.num = 0;
   4729 		return 0;
   4730 	}
   4731 
   4732 	tmp = os_calloc(list->num, sizeof(struct wpa_freq_range));
   4733 	if (tmp == NULL)
   4734 		return -1;
   4735 	os_memcpy(tmp, list->range, list->num * sizeof(struct wpa_freq_range));
   4736 	os_free(p2p->no_go_freq.range);
   4737 	p2p->no_go_freq.range = tmp;
   4738 	p2p->no_go_freq.num = list->num;
   4739 	p2p_dbg(p2p, "Updated no GO chan list");
   4740 
   4741 	return 0;
   4742 }
   4743 
   4744 
   4745 int p2p_get_interface_addr(struct p2p_data *p2p, const u8 *dev_addr,
   4746 			   u8 *iface_addr)
   4747 {
   4748 	struct p2p_device *dev = p2p_get_device(p2p, dev_addr);
   4749 	if (dev == NULL || is_zero_ether_addr(dev->interface_addr))
   4750 		return -1;
   4751 	os_memcpy(iface_addr, dev->interface_addr, ETH_ALEN);
   4752 	return 0;
   4753 }
   4754 
   4755 
   4756 int p2p_get_dev_addr(struct p2p_data *p2p, const u8 *iface_addr,
   4757 			   u8 *dev_addr)
   4758 {
   4759 	struct p2p_device *dev = p2p_get_device_interface(p2p, iface_addr);
   4760 	if (dev == NULL)
   4761 		return -1;
   4762 	os_memcpy(dev_addr, dev->info.p2p_device_addr, ETH_ALEN);
   4763 	return 0;
   4764 }
   4765 
   4766 
   4767 void p2p_set_peer_filter(struct p2p_data *p2p, const u8 *addr)
   4768 {
   4769 	os_memcpy(p2p->peer_filter, addr, ETH_ALEN);
   4770 	if (is_zero_ether_addr(p2p->peer_filter))
   4771 		p2p_dbg(p2p, "Disable peer filter");
   4772 	else
   4773 		p2p_dbg(p2p, "Enable peer filter for " MACSTR,
   4774 			MAC2STR(p2p->peer_filter));
   4775 }
   4776 
   4777 
   4778 void p2p_set_cross_connect(struct p2p_data *p2p, int enabled)
   4779 {
   4780 	p2p_dbg(p2p, "Cross connection %s", enabled ? "enabled" : "disabled");
   4781 	if (p2p->cross_connect == enabled)
   4782 		return;
   4783 	p2p->cross_connect = enabled;
   4784 	/* TODO: may need to tear down any action group where we are GO(?) */
   4785 }
   4786 
   4787 
   4788 int p2p_get_oper_freq(struct p2p_data *p2p, const u8 *iface_addr)
   4789 {
   4790 	struct p2p_device *dev = p2p_get_device_interface(p2p, iface_addr);
   4791 	if (dev == NULL)
   4792 		return -1;
   4793 	if (dev->oper_freq <= 0)
   4794 		return -1;
   4795 	return dev->oper_freq;
   4796 }
   4797 
   4798 
   4799 void p2p_set_intra_bss_dist(struct p2p_data *p2p, int enabled)
   4800 {
   4801 	p2p_dbg(p2p, "Intra BSS distribution %s",
   4802 		enabled ? "enabled" : "disabled");
   4803 	p2p->cfg->p2p_intra_bss = enabled;
   4804 }
   4805 
   4806 
   4807 void p2p_update_channel_list(struct p2p_data *p2p,
   4808 			     const struct p2p_channels *chan,
   4809 			     const struct p2p_channels *cli_chan)
   4810 {
   4811 	p2p_dbg(p2p, "Update channel list");
   4812 	os_memcpy(&p2p->cfg->channels, chan, sizeof(struct p2p_channels));
   4813 	p2p_channels_dump(p2p, "channels", &p2p->cfg->channels);
   4814 	os_memcpy(&p2p->cfg->cli_channels, cli_chan,
   4815 		  sizeof(struct p2p_channels));
   4816 	p2p_channels_dump(p2p, "cli_channels", &p2p->cfg->cli_channels);
   4817 }
   4818 
   4819 
   4820 int p2p_send_action(struct p2p_data *p2p, unsigned int freq, const u8 *dst,
   4821 		    const u8 *src, const u8 *bssid, const u8 *buf,
   4822 		    size_t len, unsigned int wait_time)
   4823 {
   4824 	if (p2p->p2p_scan_running) {
   4825 		p2p_dbg(p2p, "Delay Action frame TX until p2p_scan completes");
   4826 		if (p2p->after_scan_tx) {
   4827 			p2p_dbg(p2p, "Dropped previous pending Action frame TX");
   4828 			os_free(p2p->after_scan_tx);
   4829 		}
   4830 		p2p->after_scan_tx = os_malloc(sizeof(*p2p->after_scan_tx) +
   4831 					       len);
   4832 		if (p2p->after_scan_tx == NULL)
   4833 			return -1;
   4834 		p2p->after_scan_tx->freq = freq;
   4835 		os_memcpy(p2p->after_scan_tx->dst, dst, ETH_ALEN);
   4836 		os_memcpy(p2p->after_scan_tx->src, src, ETH_ALEN);
   4837 		os_memcpy(p2p->after_scan_tx->bssid, bssid, ETH_ALEN);
   4838 		p2p->after_scan_tx->len = len;
   4839 		p2p->after_scan_tx->wait_time = wait_time;
   4840 		os_memcpy(p2p->after_scan_tx + 1, buf, len);
   4841 		return 0;
   4842 	}
   4843 
   4844 	return p2p->cfg->send_action(p2p->cfg->cb_ctx, freq, dst, src, bssid,
   4845 				     buf, len, wait_time);
   4846 }
   4847 
   4848 
   4849 void p2p_set_best_channels(struct p2p_data *p2p, int freq_24, int freq_5,
   4850 			   int freq_overall)
   4851 {
   4852 	p2p_dbg(p2p, "Best channel: 2.4 GHz: %d,  5 GHz: %d,  overall: %d",
   4853 		freq_24, freq_5, freq_overall);
   4854 	p2p->best_freq_24 = freq_24;
   4855 	p2p->best_freq_5 = freq_5;
   4856 	p2p->best_freq_overall = freq_overall;
   4857 }
   4858 
   4859 
   4860 void p2p_set_own_freq_preference(struct p2p_data *p2p, int freq)
   4861 {
   4862 	p2p_dbg(p2p, "Own frequency preference: %d MHz", freq);
   4863 	p2p->own_freq_preference = freq;
   4864 }
   4865 
   4866 
   4867 const u8 * p2p_get_go_neg_peer(struct p2p_data *p2p)
   4868 {
   4869 	if (p2p == NULL || p2p->go_neg_peer == NULL)
   4870 		return NULL;
   4871 	return p2p->go_neg_peer->info.p2p_device_addr;
   4872 }
   4873 
   4874 
   4875 const struct p2p_peer_info *
   4876 p2p_get_peer_found(struct p2p_data *p2p, const u8 *addr, int next)
   4877 {
   4878 	struct p2p_device *dev;
   4879 
   4880 	if (addr) {
   4881 		dev = p2p_get_device(p2p, addr);
   4882 		if (!dev)
   4883 			return NULL;
   4884 
   4885 		if (!next) {
   4886 			if (dev->flags & P2P_DEV_PROBE_REQ_ONLY)
   4887 				return NULL;
   4888 
   4889 			return &dev->info;
   4890 		} else {
   4891 			do {
   4892 				dev = dl_list_first(&dev->list,
   4893 						    struct p2p_device,
   4894 						    list);
   4895 				if (!dev || &dev->list == &p2p->devices)
   4896 					return NULL;
   4897 			} while (dev->flags & P2P_DEV_PROBE_REQ_ONLY);
   4898 		}
   4899 	} else {
   4900 		dev = dl_list_first(&p2p->devices, struct p2p_device, list);
   4901 		if (!dev)
   4902 			return NULL;
   4903 		while (dev->flags & P2P_DEV_PROBE_REQ_ONLY) {
   4904 			dev = dl_list_first(&dev->list,
   4905 					    struct p2p_device,
   4906 					    list);
   4907 			if (!dev || &dev->list == &p2p->devices)
   4908 				return NULL;
   4909 		}
   4910 	}
   4911 
   4912 	return &dev->info;
   4913 }
   4914 
   4915 
   4916 int p2p_in_progress(struct p2p_data *p2p)
   4917 {
   4918 	if (p2p == NULL)
   4919 		return 0;
   4920 	if (p2p->state == P2P_SEARCH)
   4921 		return 2;
   4922 	return p2p->state != P2P_IDLE && p2p->state != P2P_PROVISIONING;
   4923 }
   4924 
   4925 
   4926 void p2p_set_config_timeout(struct p2p_data *p2p, u8 go_timeout,
   4927 			    u8 client_timeout)
   4928 {
   4929 	if (p2p) {
   4930 		p2p->go_timeout = go_timeout;
   4931 		p2p->client_timeout = client_timeout;
   4932 	}
   4933 }
   4934 
   4935 
   4936 #ifdef CONFIG_WIFI_DISPLAY
   4937 
   4938 static void p2p_update_wfd_ie_groups(struct p2p_data *p2p)
   4939 {
   4940 	size_t g;
   4941 	struct p2p_group *group;
   4942 
   4943 	for (g = 0; g < p2p->num_groups; g++) {
   4944 		group = p2p->groups[g];
   4945 		p2p_group_force_beacon_update_ies(group);
   4946 	}
   4947 }
   4948 
   4949 
   4950 int p2p_set_wfd_ie_beacon(struct p2p_data *p2p, struct wpabuf *ie)
   4951 {
   4952 	wpabuf_free(p2p->wfd_ie_beacon);
   4953 	p2p->wfd_ie_beacon = ie;
   4954 	p2p_update_wfd_ie_groups(p2p);
   4955 	return 0;
   4956 }
   4957 
   4958 
   4959 int p2p_set_wfd_ie_probe_req(struct p2p_data *p2p, struct wpabuf *ie)
   4960 {
   4961 	wpabuf_free(p2p->wfd_ie_probe_req);
   4962 	p2p->wfd_ie_probe_req = ie;
   4963 	return 0;
   4964 }
   4965 
   4966 
   4967 int p2p_set_wfd_ie_probe_resp(struct p2p_data *p2p, struct wpabuf *ie)
   4968 {
   4969 	wpabuf_free(p2p->wfd_ie_probe_resp);
   4970 	p2p->wfd_ie_probe_resp = ie;
   4971 	p2p_update_wfd_ie_groups(p2p);
   4972 	return 0;
   4973 }
   4974 
   4975 
   4976 int p2p_set_wfd_ie_assoc_req(struct p2p_data *p2p, struct wpabuf *ie)
   4977 {
   4978 	wpabuf_free(p2p->wfd_ie_assoc_req);
   4979 	p2p->wfd_ie_assoc_req = ie;
   4980 	return 0;
   4981 }
   4982 
   4983 
   4984 int p2p_set_wfd_ie_invitation(struct p2p_data *p2p, struct wpabuf *ie)
   4985 {
   4986 	wpabuf_free(p2p->wfd_ie_invitation);
   4987 	p2p->wfd_ie_invitation = ie;
   4988 	return 0;
   4989 }
   4990 
   4991 
   4992 int p2p_set_wfd_ie_prov_disc_req(struct p2p_data *p2p, struct wpabuf *ie)
   4993 {
   4994 	wpabuf_free(p2p->wfd_ie_prov_disc_req);
   4995 	p2p->wfd_ie_prov_disc_req = ie;
   4996 	return 0;
   4997 }
   4998 
   4999 
   5000 int p2p_set_wfd_ie_prov_disc_resp(struct p2p_data *p2p, struct wpabuf *ie)
   5001 {
   5002 	wpabuf_free(p2p->wfd_ie_prov_disc_resp);
   5003 	p2p->wfd_ie_prov_disc_resp = ie;
   5004 	return 0;
   5005 }
   5006 
   5007 
   5008 int p2p_set_wfd_ie_go_neg(struct p2p_data *p2p, struct wpabuf *ie)
   5009 {
   5010 	wpabuf_free(p2p->wfd_ie_go_neg);
   5011 	p2p->wfd_ie_go_neg = ie;
   5012 	return 0;
   5013 }
   5014 
   5015 
   5016 int p2p_set_wfd_dev_info(struct p2p_data *p2p, const struct wpabuf *elem)
   5017 {
   5018 	wpabuf_free(p2p->wfd_dev_info);
   5019 	if (elem) {
   5020 		p2p->wfd_dev_info = wpabuf_dup(elem);
   5021 		if (p2p->wfd_dev_info == NULL)
   5022 			return -1;
   5023 	} else
   5024 		p2p->wfd_dev_info = NULL;
   5025 
   5026 	return 0;
   5027 }
   5028 
   5029 
   5030 int p2p_set_wfd_assoc_bssid(struct p2p_data *p2p, const struct wpabuf *elem)
   5031 {
   5032 	wpabuf_free(p2p->wfd_assoc_bssid);
   5033 	if (elem) {
   5034 		p2p->wfd_assoc_bssid = wpabuf_dup(elem);
   5035 		if (p2p->wfd_assoc_bssid == NULL)
   5036 			return -1;
   5037 	} else
   5038 		p2p->wfd_assoc_bssid = NULL;
   5039 
   5040 	return 0;
   5041 }
   5042 
   5043 
   5044 int p2p_set_wfd_coupled_sink_info(struct p2p_data *p2p,
   5045 				  const struct wpabuf *elem)
   5046 {
   5047 	wpabuf_free(p2p->wfd_coupled_sink_info);
   5048 	if (elem) {
   5049 		p2p->wfd_coupled_sink_info = wpabuf_dup(elem);
   5050 		if (p2p->wfd_coupled_sink_info == NULL)
   5051 			return -1;
   5052 	} else
   5053 		p2p->wfd_coupled_sink_info = NULL;
   5054 
   5055 	return 0;
   5056 }
   5057 
   5058 #endif /* CONFIG_WIFI_DISPLAY */
   5059 
   5060 
   5061 int p2p_set_disc_int(struct p2p_data *p2p, int min_disc_int, int max_disc_int,
   5062 		     int max_disc_tu)
   5063 {
   5064 	if (min_disc_int > max_disc_int || min_disc_int < 0 || max_disc_int < 0)
   5065 		return -1;
   5066 
   5067 	p2p->min_disc_int = min_disc_int;
   5068 	p2p->max_disc_int = max_disc_int;
   5069 	p2p->max_disc_tu = max_disc_tu;
   5070 	p2p_dbg(p2p, "Set discoverable interval: min=%d max=%d max_tu=%d",
   5071 		min_disc_int, max_disc_int, max_disc_tu);
   5072 
   5073 	return 0;
   5074 }
   5075 
   5076 
   5077 void p2p_dbg(struct p2p_data *p2p, const char *fmt, ...)
   5078 {
   5079 	va_list ap;
   5080 	char buf[500];
   5081 
   5082 	if (!p2p->cfg->debug_print)
   5083 		return;
   5084 
   5085 	va_start(ap, fmt);
   5086 	vsnprintf(buf, sizeof(buf), fmt, ap);
   5087 	buf[sizeof(buf) - 1] = '\0';
   5088 	va_end(ap);
   5089 	p2p->cfg->debug_print(p2p->cfg->cb_ctx, MSG_DEBUG, buf);
   5090 }
   5091 
   5092 
   5093 void p2p_info(struct p2p_data *p2p, const char *fmt, ...)
   5094 {
   5095 	va_list ap;
   5096 	char buf[500];
   5097 
   5098 	if (!p2p->cfg->debug_print)
   5099 		return;
   5100 
   5101 	va_start(ap, fmt);
   5102 	vsnprintf(buf, sizeof(buf), fmt, ap);
   5103 	buf[sizeof(buf) - 1] = '\0';
   5104 	va_end(ap);
   5105 	p2p->cfg->debug_print(p2p->cfg->cb_ctx, MSG_INFO, buf);
   5106 }
   5107 
   5108 
   5109 void p2p_err(struct p2p_data *p2p, const char *fmt, ...)
   5110 {
   5111 	va_list ap;
   5112 	char buf[500];
   5113 
   5114 	if (!p2p->cfg->debug_print)
   5115 		return;
   5116 
   5117 	va_start(ap, fmt);
   5118 	vsnprintf(buf, sizeof(buf), fmt, ap);
   5119 	buf[sizeof(buf) - 1] = '\0';
   5120 	va_end(ap);
   5121 	p2p->cfg->debug_print(p2p->cfg->cb_ctx, MSG_ERROR, buf);
   5122 }
   5123 
   5124 
   5125 void p2p_loop_on_known_peers(struct p2p_data *p2p,
   5126 			     void (*peer_callback)(struct p2p_peer_info *peer,
   5127 						   void *user_data),
   5128 			     void *user_data)
   5129 {
   5130 	struct p2p_device *dev, *n;
   5131 
   5132 	dl_list_for_each_safe(dev, n, &p2p->devices, struct p2p_device, list) {
   5133 		peer_callback(&dev->info, user_data);
   5134 	}
   5135 }
   5136 
   5137 
   5138 #ifdef CONFIG_WPS_NFC
   5139 
   5140 static struct wpabuf * p2p_build_nfc_handover(struct p2p_data *p2p,
   5141 					      int client_freq,
   5142 					      const u8 *go_dev_addr,
   5143 					      const u8 *ssid, size_t ssid_len)
   5144 {
   5145 	struct wpabuf *buf;
   5146 	u8 op_class, channel;
   5147 	enum p2p_role_indication role = P2P_DEVICE_NOT_IN_GROUP;
   5148 
   5149 	buf = wpabuf_alloc(1000);
   5150 	if (buf == NULL)
   5151 		return NULL;
   5152 
   5153 	op_class = p2p->cfg->reg_class;
   5154 	channel = p2p->cfg->channel;
   5155 
   5156 	p2p_buf_add_capability(buf, p2p->dev_capab &
   5157 			       ~P2P_DEV_CAPAB_CLIENT_DISCOVERABILITY, 0);
   5158 	p2p_buf_add_device_info(buf, p2p, NULL);
   5159 
   5160 	if (p2p->num_groups > 0) {
   5161 		int freq = p2p_group_get_freq(p2p->groups[0]);
   5162 		role = P2P_GO_IN_A_GROUP;
   5163 		if (p2p_freq_to_channel(freq, &op_class, &channel) < 0) {
   5164 			p2p_dbg(p2p,
   5165 				"Unknown GO operating frequency %d MHz for NFC handover",
   5166 				freq);
   5167 			wpabuf_free(buf);
   5168 			return NULL;
   5169 		}
   5170 	} else if (client_freq > 0) {
   5171 		role = P2P_CLIENT_IN_A_GROUP;
   5172 		if (p2p_freq_to_channel(client_freq, &op_class, &channel) < 0) {
   5173 			p2p_dbg(p2p,
   5174 				"Unknown client operating frequency %d MHz for NFC handover",
   5175 				client_freq);
   5176 			wpabuf_free(buf);
   5177 			return NULL;
   5178 		}
   5179 	}
   5180 
   5181 	p2p_buf_add_oob_go_neg_channel(buf, p2p->cfg->country, op_class,
   5182 				       channel, role);
   5183 
   5184 	if (p2p->num_groups > 0) {
   5185 		/* Limit number of clients to avoid very long message */
   5186 		p2p_buf_add_group_info(p2p->groups[0], buf, 5);
   5187 		p2p_group_buf_add_id(p2p->groups[0], buf);
   5188 	} else if (client_freq > 0 &&
   5189 		   go_dev_addr && !is_zero_ether_addr(go_dev_addr) &&
   5190 		   ssid && ssid_len > 0) {
   5191 		/*
   5192 		 * Add the optional P2P Group ID to indicate in which group this
   5193 		 * device is a P2P Client.
   5194 		 */
   5195 		p2p_buf_add_group_id(buf, go_dev_addr, ssid, ssid_len);
   5196 	}
   5197 
   5198 	return buf;
   5199 }
   5200 
   5201 
   5202 struct wpabuf * p2p_build_nfc_handover_req(struct p2p_data *p2p,
   5203 					   int client_freq,
   5204 					   const u8 *go_dev_addr,
   5205 					   const u8 *ssid, size_t ssid_len)
   5206 {
   5207 	return p2p_build_nfc_handover(p2p, client_freq, go_dev_addr, ssid,
   5208 				      ssid_len);
   5209 }
   5210 
   5211 
   5212 struct wpabuf * p2p_build_nfc_handover_sel(struct p2p_data *p2p,
   5213 					   int client_freq,
   5214 					   const u8 *go_dev_addr,
   5215 					   const u8 *ssid, size_t ssid_len)
   5216 {
   5217 	return p2p_build_nfc_handover(p2p, client_freq, go_dev_addr, ssid,
   5218 				      ssid_len);
   5219 }
   5220 
   5221 
   5222 int p2p_process_nfc_connection_handover(struct p2p_data *p2p,
   5223 					struct p2p_nfc_params *params)
   5224 {
   5225 	struct p2p_message msg;
   5226 	struct p2p_device *dev;
   5227 	const u8 *p2p_dev_addr;
   5228 	int freq;
   5229 	enum p2p_role_indication role;
   5230 
   5231 	params->next_step = NO_ACTION;
   5232 
   5233 	if (p2p_parse_ies_separate(params->wsc_attr, params->wsc_len,
   5234 				   params->p2p_attr, params->p2p_len, &msg)) {
   5235 		p2p_dbg(p2p, "Failed to parse WSC/P2P attributes from NFC");
   5236 		p2p_parse_free(&msg);
   5237 		return -1;
   5238 	}
   5239 
   5240 	if (msg.p2p_device_addr)
   5241 		p2p_dev_addr = msg.p2p_device_addr;
   5242 	else if (msg.device_id)
   5243 		p2p_dev_addr = msg.device_id;
   5244 	else {
   5245 		p2p_dbg(p2p, "Ignore scan data without P2P Device Info or P2P Device Id");
   5246 		p2p_parse_free(&msg);
   5247 		return -1;
   5248 	}
   5249 
   5250 	if (msg.oob_dev_password) {
   5251 		os_memcpy(params->oob_dev_pw, msg.oob_dev_password,
   5252 			  msg.oob_dev_password_len);
   5253 		params->oob_dev_pw_len = msg.oob_dev_password_len;
   5254 	}
   5255 
   5256 	dev = p2p_create_device(p2p, p2p_dev_addr);
   5257 	if (dev == NULL) {
   5258 		p2p_parse_free(&msg);
   5259 		return -1;
   5260 	}
   5261 
   5262 	params->peer = &dev->info;
   5263 
   5264 	os_get_reltime(&dev->last_seen);
   5265 	dev->flags &= ~(P2P_DEV_PROBE_REQ_ONLY | P2P_DEV_GROUP_CLIENT_ONLY);
   5266 	p2p_copy_wps_info(p2p, dev, 0, &msg);
   5267 
   5268 	if (!msg.oob_go_neg_channel) {
   5269 		p2p_dbg(p2p, "OOB GO Negotiation Channel attribute not included");
   5270 		p2p_parse_free(&msg);
   5271 		return -1;
   5272 	}
   5273 
   5274 	if (msg.oob_go_neg_channel[3] == 0 &&
   5275 	    msg.oob_go_neg_channel[4] == 0)
   5276 		freq = 0;
   5277 	else
   5278 		freq = p2p_channel_to_freq(msg.oob_go_neg_channel[3],
   5279 					   msg.oob_go_neg_channel[4]);
   5280 	if (freq < 0) {
   5281 		p2p_dbg(p2p, "Unknown peer OOB GO Neg channel");
   5282 		p2p_parse_free(&msg);
   5283 		return -1;
   5284 	}
   5285 	role = msg.oob_go_neg_channel[5];
   5286 
   5287 	if (role == P2P_GO_IN_A_GROUP) {
   5288 		p2p_dbg(p2p, "Peer OOB GO operating channel: %u MHz", freq);
   5289 		params->go_freq = freq;
   5290 	} else if (role == P2P_CLIENT_IN_A_GROUP) {
   5291 		p2p_dbg(p2p, "Peer (client) OOB GO operating channel: %u MHz",
   5292 			freq);
   5293 		params->go_freq = freq;
   5294 	} else
   5295 		p2p_dbg(p2p, "Peer OOB GO Neg channel: %u MHz", freq);
   5296 	dev->oob_go_neg_freq = freq;
   5297 
   5298 	if (!params->sel && role != P2P_GO_IN_A_GROUP) {
   5299 		freq = p2p_channel_to_freq(p2p->cfg->reg_class,
   5300 					   p2p->cfg->channel);
   5301 		if (freq < 0) {
   5302 			p2p_dbg(p2p, "Own listen channel not known");
   5303 			p2p_parse_free(&msg);
   5304 			return -1;
   5305 		}
   5306 		p2p_dbg(p2p, "Use own Listen channel as OOB GO Neg channel: %u MHz", freq);
   5307 		dev->oob_go_neg_freq = freq;
   5308 	}
   5309 
   5310 	if (msg.group_id) {
   5311 		os_memcpy(params->go_dev_addr, msg.group_id, ETH_ALEN);
   5312 		params->go_ssid_len = msg.group_id_len - ETH_ALEN;
   5313 		os_memcpy(params->go_ssid, msg.group_id + ETH_ALEN,
   5314 			  params->go_ssid_len);
   5315 	}
   5316 
   5317 	if (dev->flags & P2P_DEV_USER_REJECTED) {
   5318 		p2p_dbg(p2p, "Do not report rejected device");
   5319 		p2p_parse_free(&msg);
   5320 		return 0;
   5321 	}
   5322 
   5323 	if (!(dev->flags & P2P_DEV_REPORTED)) {
   5324 		p2p->cfg->dev_found(p2p->cfg->cb_ctx, p2p_dev_addr, &dev->info,
   5325 				    !(dev->flags & P2P_DEV_REPORTED_ONCE));
   5326 		dev->flags |= P2P_DEV_REPORTED | P2P_DEV_REPORTED_ONCE;
   5327 	}
   5328 	p2p_parse_free(&msg);
   5329 
   5330 	if (role == P2P_GO_IN_A_GROUP && p2p->num_groups > 0)
   5331 		params->next_step = BOTH_GO;
   5332 	else if (role == P2P_GO_IN_A_GROUP)
   5333 		params->next_step = JOIN_GROUP;
   5334 	else if (role == P2P_CLIENT_IN_A_GROUP) {
   5335 		dev->flags |= P2P_DEV_GROUP_CLIENT_ONLY;
   5336 		params->next_step = PEER_CLIENT;
   5337 	} else if (p2p->num_groups > 0)
   5338 		params->next_step = AUTH_JOIN;
   5339 	else if (params->sel)
   5340 		params->next_step = INIT_GO_NEG;
   5341 	else
   5342 		params->next_step = RESP_GO_NEG;
   5343 
   5344 	return 0;
   5345 }
   5346 
   5347 
   5348 void p2p_set_authorized_oob_dev_pw_id(struct p2p_data *p2p, u16 dev_pw_id,
   5349 				      int go_intent,
   5350 				      const u8 *own_interface_addr)
   5351 {
   5352 
   5353 	p2p->authorized_oob_dev_pw_id = dev_pw_id;
   5354 	if (dev_pw_id == 0) {
   5355 		p2p_dbg(p2p, "NFC OOB Password unauthorized for static handover");
   5356 		return;
   5357 	}
   5358 
   5359 	p2p_dbg(p2p, "NFC OOB Password (id=%u) authorized for static handover",
   5360 		dev_pw_id);
   5361 
   5362 	p2p->go_intent = go_intent;
   5363 	os_memcpy(p2p->intended_addr, own_interface_addr, ETH_ALEN);
   5364 }
   5365 
   5366 #endif /* CONFIG_WPS_NFC */
   5367 
   5368 
   5369 int p2p_set_passphrase_len(struct p2p_data *p2p, unsigned int len)
   5370 {
   5371 	if (len < 8 || len > 63)
   5372 		return -1;
   5373 	p2p->cfg->passphrase_len = len;
   5374 	return 0;
   5375 }
   5376 
   5377 
   5378 void p2p_set_vendor_elems(struct p2p_data *p2p, struct wpabuf **vendor_elem)
   5379 {
   5380 	p2p->vendor_elem = vendor_elem;
   5381 }
   5382 
   5383 
   5384 void p2p_go_neg_wait_timeout(void *eloop_ctx, void *timeout_ctx)
   5385 {
   5386 	struct p2p_data *p2p = eloop_ctx;
   5387 
   5388 	p2p_dbg(p2p,
   5389 		"Timeout on waiting peer to become ready for GO Negotiation");
   5390 	p2p_go_neg_failed(p2p, -1);
   5391 }
   5392