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