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