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