OSDN Git Service

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