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