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