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