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