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