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