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