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