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