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