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