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