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