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