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