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