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