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