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