P2P: Initial support for SD fragmentation (GAS Comeback Request/Response)
[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, freq);
1184                 break;
1185         case WLAN_PA_GAS_COMEBACK_REQ:
1186                 p2p_rx_gas_comeback_req(p2p, sa, data + 1, len - 1, freq);
1187                 break;
1188         case WLAN_PA_GAS_COMEBACK_RESP:
1189                 p2p_rx_gas_comeback_resp(p2p, sa, data + 1, len - 1, freq);
1190                 break;
1191         }
1192 }
1193
1194
1195 void p2p_rx_action(struct p2p_data *p2p, const u8 *da, const u8 *sa,
1196                    const u8 *bssid, u8 category,
1197                    const u8 *data, size_t len, int freq)
1198 {
1199         if (category == WLAN_ACTION_PUBLIC) {
1200                 p2p_rx_action_public(p2p, da, sa, bssid, data, len, freq);
1201                 return;
1202         }
1203
1204         if (category != WLAN_ACTION_VENDOR_SPECIFIC)
1205                 return;
1206
1207         if (len < 4)
1208                 return;
1209
1210         if (WPA_GET_BE24(data) != OUI_WFA)
1211                 return;
1212         data += 3;
1213         len -= 3;
1214
1215         if (*data != P2P_OUI_TYPE)
1216                 return;
1217         data++;
1218         len--;
1219
1220         /* P2P action frame */
1221         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
1222                 "P2P: RX P2P Action from " MACSTR, MAC2STR(sa));
1223         wpa_hexdump(MSG_MSGDUMP, "P2P: P2P Action contents", data, len);
1224
1225         if (len < 1)
1226                 return;
1227         switch (data[0]) {
1228         case P2P_NOA:
1229                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
1230                         "P2P: Received P2P Action - Notice of Absence");
1231                 /* TODO */
1232                 break;
1233         case P2P_PRESENCE_REQ:
1234                 p2p_process_presence_req(p2p, da, sa, data + 1, len - 1, freq);
1235                 break;
1236         case P2P_PRESENCE_RESP:
1237                 p2p_process_presence_resp(p2p, da, sa, data + 1, len - 1);
1238                 break;
1239         case P2P_GO_DISC_REQ:
1240                 p2p_process_go_disc_req(p2p, da, sa, data + 1, len - 1, freq);
1241                 break;
1242         default:
1243                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
1244                         "P2P: Received P2P Action - unknown type %u", data[0]);
1245                 break;
1246         }
1247 }
1248
1249
1250 static void p2p_go_neg_start(void *eloop_ctx, void *timeout_ctx)
1251 {
1252         struct p2p_data *p2p = eloop_ctx;
1253         if (p2p->go_neg_peer == NULL)
1254                 return;
1255         p2p->cfg->stop_listen(p2p->cfg->cb_ctx);
1256         p2p->go_neg_peer->status = P2P_SC_SUCCESS;
1257         p2p_connect_send(p2p, p2p->go_neg_peer);
1258 }
1259
1260
1261 static void p2p_invite_start(void *eloop_ctx, void *timeout_ctx)
1262 {
1263         struct p2p_data *p2p = eloop_ctx;
1264         if (p2p->invite_peer == NULL)
1265                 return;
1266         p2p->cfg->stop_listen(p2p->cfg->cb_ctx);
1267         p2p_invite_send(p2p, p2p->invite_peer, p2p->invite_go_dev_addr);
1268 }
1269
1270
1271 static void p2p_add_dev_from_probe_req(struct p2p_data *p2p, const u8 *addr,
1272                                        const u8 *ie, size_t ie_len)
1273 {
1274         struct p2p_message msg;
1275         struct p2p_device *dev;
1276
1277         os_memset(&msg, 0, sizeof(msg));
1278         if (p2p_parse_ies(ie, ie_len, &msg) < 0 || msg.p2p_attributes == NULL)
1279         {
1280                 p2p_parse_free(&msg);
1281                 return; /* not a P2P probe */
1282         }
1283
1284         if (msg.ssid == NULL || msg.ssid[1] != P2P_WILDCARD_SSID_LEN ||
1285             os_memcmp(msg.ssid + 2, P2P_WILDCARD_SSID, P2P_WILDCARD_SSID_LEN)
1286             != 0) {
1287                 /* The Probe Request is not part of P2P Device Discovery. It is
1288                  * not known whether the source address of the frame is the P2P
1289                  * Device Address or P2P Interface Address. Do not add a new
1290                  * peer entry based on this frames.
1291                  */
1292                 p2p_parse_free(&msg);
1293                 return;
1294         }
1295
1296         dev = p2p_get_device(p2p, addr);
1297         if (dev) {
1298                 if (dev->country[0] == 0 && msg.listen_channel)
1299                         os_memcpy(dev->country, msg.listen_channel, 3);
1300                 p2p_parse_free(&msg);
1301                 return; /* already known */
1302         }
1303
1304         dev = p2p_create_device(p2p, addr);
1305         if (dev == NULL) {
1306                 p2p_parse_free(&msg);
1307                 return;
1308         }
1309
1310         os_get_time(&dev->last_seen);
1311         dev->flags |= P2P_DEV_PROBE_REQ_ONLY;
1312
1313         if (msg.capability) {
1314                 dev->dev_capab = msg.capability[0];
1315                 dev->group_capab = msg.capability[1];
1316         }
1317
1318         if (msg.listen_channel) {
1319                 os_memcpy(dev->country, msg.listen_channel, 3);
1320                 dev->listen_freq = p2p_channel_to_freq(dev->country,
1321                                                        msg.listen_channel[3],
1322                                                        msg.listen_channel[4]);
1323         }
1324
1325         os_memcpy(dev->device_name, msg.device_name, sizeof(dev->device_name));
1326
1327         if (msg.wps_pri_dev_type)
1328                 os_memcpy(dev->pri_dev_type, msg.wps_pri_dev_type,
1329                           sizeof(dev->pri_dev_type));
1330
1331         p2p_parse_free(&msg);
1332
1333         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
1334                 "P2P: Created device entry based on Probe Req: " MACSTR
1335                 " dev_capab=0x%x group_capab=0x%x name='%s' listen_freq=%d",
1336                 MAC2STR(dev->p2p_device_addr), dev->dev_capab,
1337                 dev->group_capab, dev->device_name, dev->listen_freq);
1338 }
1339
1340
1341 struct p2p_device * p2p_add_dev_from_go_neg_req(struct p2p_data *p2p,
1342                                                 const u8 *addr,
1343                                                 struct p2p_message *msg)
1344 {
1345         struct p2p_device *dev;
1346
1347         dev = p2p_get_device(p2p, addr);
1348         if (dev) {
1349                 os_get_time(&dev->last_seen);
1350                 return dev; /* already known */
1351         }
1352
1353         dev = p2p_create_device(p2p, addr);
1354         if (dev == NULL)
1355                 return NULL;
1356
1357         p2p_add_dev_info(p2p, addr, dev, msg);
1358
1359         return dev;
1360 }
1361
1362
1363 static int dev_type_match(const u8 *dev_type, const u8 *req_dev_type)
1364 {
1365         if (os_memcmp(dev_type, req_dev_type, WPS_DEV_TYPE_LEN) == 0)
1366                 return 1;
1367         if (os_memcmp(dev_type, req_dev_type, 2) == 0 &&
1368             WPA_GET_BE32(&req_dev_type[2]) == 0 &&
1369             WPA_GET_BE16(&req_dev_type[6]) == 0)
1370                 return 1; /* Category match with wildcard OUI/sub-category */
1371         return 0;
1372 }
1373
1374
1375 int dev_type_list_match(const u8 *dev_type, const u8 *req_dev_type[],
1376                         size_t num_req_dev_type)
1377 {
1378         size_t i;
1379         for (i = 0; i < num_req_dev_type; i++) {
1380                 if (dev_type_match(dev_type, req_dev_type[i]))
1381                         return 1;
1382         }
1383         return 0;
1384 }
1385
1386
1387 /**
1388  * p2p_match_dev_type - Match local device type with requested type
1389  * @p2p: P2P module context from p2p_init()
1390  * @wps: WPS TLVs from Probe Request frame (concatenated WPS IEs)
1391  * Returns: 1 on match, 0 on mismatch
1392  *
1393  * This function can be used to match the Requested Device Type attribute in
1394  * WPS IE with the local device types for deciding whether to reply to a Probe
1395  * Request frame.
1396  */
1397 int p2p_match_dev_type(struct p2p_data *p2p, struct wpabuf *wps)
1398 {
1399         struct wps_parse_attr attr;
1400         size_t i;
1401
1402         if (wps_parse_msg(wps, &attr))
1403                 return 1; /* assume no Requested Device Type attributes */
1404
1405         if (attr.num_req_dev_type == 0)
1406                 return 1; /* no Requested Device Type attributes -> match */
1407
1408         if (dev_type_list_match(p2p->cfg->pri_dev_type, attr.req_dev_type,
1409                                 attr.num_req_dev_type))
1410                 return 1; /* Own Primary Device Type matches */
1411
1412         for (i = 0; i < p2p->cfg->num_sec_dev_types; i++)
1413                 if (dev_type_list_match(p2p->cfg->sec_dev_type[i],
1414                                         attr.req_dev_type,
1415                                         attr.num_req_dev_type))
1416                 return 1; /* Own Secondary Device Type matches */
1417
1418         /* No matching device type found */
1419         return 0;
1420 }
1421
1422
1423 struct wpabuf * p2p_build_probe_resp_ies(struct p2p_data *p2p)
1424 {
1425         struct wpabuf *buf;
1426         u8 *len;
1427
1428         buf = wpabuf_alloc(1000);
1429         if (buf == NULL)
1430                 return NULL;
1431
1432         /* TODO: add more info into WPS IE; maybe get from WPS module? */
1433         p2p_build_wps_ie(p2p, buf, DEV_PW_DEFAULT, 1);
1434
1435         /* P2P IE */
1436         len = p2p_buf_add_ie_hdr(buf);
1437         p2p_buf_add_capability(buf, p2p->dev_capab, 0);
1438         if (p2p->ext_listen_interval)
1439                 p2p_buf_add_ext_listen_timing(buf, p2p->ext_listen_period,
1440                                               p2p->ext_listen_interval);
1441         p2p_buf_add_device_info(buf, p2p, NULL);
1442         p2p_buf_update_ie_hdr(buf, len);
1443
1444         return buf;
1445 }
1446
1447
1448 static void p2p_reply_probe(struct p2p_data *p2p, const u8 *addr, const u8 *ie,
1449                             size_t ie_len)
1450 {
1451         struct ieee802_11_elems elems;
1452         struct wpabuf *buf;
1453         struct ieee80211_mgmt *resp;
1454         struct wpabuf *wps;
1455         struct wpabuf *ies;
1456
1457         if (!p2p->in_listen || !p2p->drv_in_listen) {
1458                 /* not in Listen state - ignore Probe Request */
1459                 return;
1460         }
1461
1462         if (ieee802_11_parse_elems((u8 *) ie, ie_len, &elems, 0) ==
1463             ParseFailed) {
1464                 /* Ignore invalid Probe Request frames */
1465                 return;
1466         }
1467
1468         if (elems.p2p == NULL) {
1469                 /* not a P2P probe - ignore it */
1470                 return;
1471         }
1472
1473         if (elems.ssid == NULL || elems.ssid_len != P2P_WILDCARD_SSID_LEN ||
1474             os_memcmp(elems.ssid, P2P_WILDCARD_SSID, P2P_WILDCARD_SSID_LEN) !=
1475             0) {
1476                 /* not using P2P Wildcard SSID - ignore */
1477                 return;
1478         }
1479
1480         /* Check Requested Device Type match */
1481         wps = ieee802_11_vendor_ie_concat(ie, ie_len, WPS_DEV_OUI_WFA);
1482         if (wps && !p2p_match_dev_type(p2p, wps)) {
1483                 wpabuf_free(wps);
1484                 /* No match with Requested Device Type */
1485                 return;
1486         }
1487         wpabuf_free(wps);
1488
1489         if (!p2p->cfg->send_probe_resp)
1490                 return; /* Response generated elsewhere */
1491
1492         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
1493                 "P2P: Reply to P2P Probe Request in Listen state");
1494
1495         /*
1496          * We do not really have a specific BSS that this frame is advertising,
1497          * so build a frame that has some information in valid format. This is
1498          * really only used for discovery purposes, not to learn exact BSS
1499          * parameters.
1500          */
1501         ies = p2p_build_probe_resp_ies(p2p);
1502         if (ies == NULL)
1503                 return;
1504
1505         buf = wpabuf_alloc(200 + wpabuf_len(ies));
1506         if (buf == NULL) {
1507                 wpabuf_free(ies);
1508                 return;
1509         }
1510
1511         resp = NULL;
1512         resp = wpabuf_put(buf, resp->u.probe_resp.variable - (u8 *) resp);
1513
1514         resp->frame_control = host_to_le16((WLAN_FC_TYPE_MGMT << 2) |
1515                                            (WLAN_FC_STYPE_PROBE_RESP << 4));
1516         os_memcpy(resp->da, addr, ETH_ALEN);
1517         os_memcpy(resp->sa, p2p->cfg->dev_addr, ETH_ALEN);
1518         os_memcpy(resp->bssid, p2p->cfg->dev_addr, ETH_ALEN);
1519         resp->u.probe_resp.beacon_int = host_to_le16(100);
1520         /* hardware or low-level driver will setup seq_ctrl and timestamp */
1521         resp->u.probe_resp.capab_info =
1522                 host_to_le16(WLAN_CAPABILITY_SHORT_PREAMBLE |
1523                              WLAN_CAPABILITY_PRIVACY |
1524                              WLAN_CAPABILITY_SHORT_SLOT_TIME);
1525
1526         wpabuf_put_u8(buf, WLAN_EID_SSID);
1527         wpabuf_put_u8(buf, P2P_WILDCARD_SSID_LEN);
1528         wpabuf_put_data(buf, P2P_WILDCARD_SSID, P2P_WILDCARD_SSID_LEN);
1529
1530         wpabuf_put_u8(buf, WLAN_EID_SUPP_RATES);
1531         wpabuf_put_u8(buf, 8);
1532         wpabuf_put_u8(buf, (60 / 5) | 0x80);
1533         wpabuf_put_u8(buf, 90 / 5);
1534         wpabuf_put_u8(buf, (120 / 5) | 0x80);
1535         wpabuf_put_u8(buf, 180 / 5);
1536         wpabuf_put_u8(buf, (240 / 5) | 0x80);
1537         wpabuf_put_u8(buf, 360 / 5);
1538         wpabuf_put_u8(buf, 480 / 5);
1539         wpabuf_put_u8(buf, 540 / 5);
1540
1541         wpabuf_put_u8(buf, WLAN_EID_DS_PARAMS);
1542         wpabuf_put_u8(buf, 1);
1543         wpabuf_put_u8(buf, p2p->cfg->channel);
1544
1545         wpabuf_put_buf(buf, ies);
1546         wpabuf_free(ies);
1547
1548         p2p->cfg->send_probe_resp(p2p->cfg->cb_ctx, buf);
1549
1550         wpabuf_free(buf);
1551 }
1552
1553
1554 int p2p_probe_req_rx(struct p2p_data *p2p, const u8 *addr, const u8 *ie,
1555                      size_t ie_len)
1556 {
1557         p2p_add_dev_from_probe_req(p2p, addr, ie, ie_len);
1558
1559         p2p_reply_probe(p2p, addr, ie, ie_len);
1560
1561         if ((p2p->state == P2P_CONNECT || p2p->state == P2P_CONNECT_LISTEN) &&
1562             p2p->go_neg_peer &&
1563             os_memcmp(addr, p2p->go_neg_peer->p2p_device_addr, ETH_ALEN) == 0)
1564         {
1565                 /* Received a Probe Request from GO Negotiation peer */
1566                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
1567                         "P2P: Found GO Negotiation peer - try to start GO "
1568                         "negotiation from timeout");
1569                 eloop_register_timeout(0, 0, p2p_go_neg_start, p2p, NULL);
1570                 return 1;
1571         }
1572
1573         if ((p2p->state == P2P_INVITE || p2p->state == P2P_INVITE_LISTEN) &&
1574             p2p->invite_peer &&
1575             os_memcmp(addr, p2p->invite_peer->p2p_device_addr, ETH_ALEN) == 0)
1576         {
1577                 /* Received a Probe Request from Invite peer */
1578                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
1579                         "P2P: Found Invite peer - try to start Invite from "
1580                         "timeout");
1581                 eloop_register_timeout(0, 0, p2p_invite_start, p2p, NULL);
1582                 return 1;
1583         }
1584
1585         return 0;
1586 }
1587
1588
1589 static int p2p_assoc_req_ie_wlan_ap(struct p2p_data *p2p, const u8 *bssid,
1590                                     u8 *buf, size_t len)
1591 {
1592         struct wpabuf *tmp;
1593         u8 *lpos;
1594         size_t tmplen;
1595         int res;
1596
1597         if (!(p2p->dev_capab & P2P_DEV_CAPAB_INFRA_MANAGED))
1598                 return 0;
1599
1600         /*
1601          * (Re)Association Request - P2P IE
1602          * P2P Capability attribute (shall be present)
1603          * P2P Interface attribute (present if concurrent device)
1604          */
1605         tmp = wpabuf_alloc(200);
1606         if (tmp == NULL)
1607                 return -1;
1608
1609         lpos = p2p_buf_add_ie_hdr(tmp);
1610         p2p_buf_add_capability(tmp, p2p->dev_capab, 0);
1611         if (p2p->dev_capab & P2P_DEV_CAPAB_CONCURRENT_OPER)
1612                 p2p_buf_add_p2p_interface(tmp, p2p);
1613         p2p_buf_update_ie_hdr(tmp, lpos);
1614
1615         tmplen = wpabuf_len(tmp);
1616         if (tmplen > len)
1617                 res = -1;
1618         else {
1619                 os_memcpy(buf, wpabuf_head(tmp), tmplen);
1620                 res = tmplen;
1621         }
1622         wpabuf_free(tmp);
1623
1624         return res;
1625 }
1626
1627
1628 int p2p_assoc_req_ie(struct p2p_data *p2p, const u8 *bssid, u8 *buf,
1629                      size_t len, int p2p_group)
1630 {
1631         struct wpabuf *tmp;
1632         u8 *lpos;
1633         struct p2p_device *peer;
1634         size_t tmplen;
1635         int res;
1636
1637         if (!p2p_group)
1638                 return p2p_assoc_req_ie_wlan_ap(p2p, bssid, buf, len);
1639
1640         /*
1641          * (Re)Association Request - P2P IE
1642          * P2P Capability attribute (shall be present)
1643          * Extended Listen Timing (may be present)
1644          * P2P Device Info attribute (shall be present)
1645          */
1646         tmp = wpabuf_alloc(200);
1647         if (tmp == NULL)
1648                 return -1;
1649
1650         peer = bssid ? p2p_get_device(p2p, bssid) : NULL;
1651
1652         lpos = p2p_buf_add_ie_hdr(tmp);
1653         p2p_buf_add_capability(tmp, p2p->dev_capab, 0);
1654         p2p_buf_add_device_info(tmp, p2p, peer);
1655         p2p_buf_update_ie_hdr(tmp, lpos);
1656
1657         tmplen = wpabuf_len(tmp);
1658         if (tmplen > len)
1659                 res = -1;
1660         else {
1661                 os_memcpy(buf, wpabuf_head(tmp), tmplen);
1662                 res = tmplen;
1663         }
1664         wpabuf_free(tmp);
1665
1666         return res;
1667 }
1668
1669
1670 int p2p_scan_result_text(const u8 *ies, size_t ies_len, char *buf, char *end)
1671 {
1672         struct wpabuf *p2p_ie;
1673         int ret;
1674
1675         p2p_ie = ieee802_11_vendor_ie_concat(ies, ies_len, P2P_IE_VENDOR_TYPE);
1676         if (p2p_ie == NULL)
1677                 return 0;
1678
1679         ret = p2p_attr_text(p2p_ie, buf, end);
1680         wpabuf_free(p2p_ie);
1681         return ret;
1682 }
1683
1684
1685 static void p2p_clear_go_neg(struct p2p_data *p2p)
1686 {
1687         p2p->go_neg_peer = NULL;
1688         p2p_clear_timeout(p2p);
1689         p2p_set_state(p2p, P2P_IDLE);
1690 }
1691
1692
1693 void p2p_wps_success_cb(struct p2p_data *p2p, const u8 *mac_addr)
1694 {
1695         if (p2p->go_neg_peer == NULL) {
1696                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
1697                         "P2P: No pending Group Formation - "
1698                         "ignore WPS registration success notification");
1699                 return; /* No pending Group Formation */
1700         }
1701
1702         if (os_memcmp(mac_addr, p2p->go_neg_peer->intended_addr, ETH_ALEN) !=
1703             0) {
1704                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
1705                         "P2P: Ignore WPS registration success notification "
1706                         "for " MACSTR " (GO Negotiation peer " MACSTR ")",
1707                         MAC2STR(mac_addr),
1708                         MAC2STR(p2p->go_neg_peer->intended_addr));
1709                 return; /* Ignore unexpected peer address */
1710         }
1711
1712         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
1713                 "P2P: Group Formation completed successfully with " MACSTR,
1714                 MAC2STR(mac_addr));
1715
1716         p2p_clear_go_neg(p2p);
1717 }
1718
1719
1720 void p2p_group_formation_failed(struct p2p_data *p2p)
1721 {
1722         if (p2p->go_neg_peer == NULL) {
1723                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
1724                         "P2P: No pending Group Formation - "
1725                         "ignore group formation failure notification");
1726                 return; /* No pending Group Formation */
1727         }
1728
1729         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
1730                 "P2P: Group Formation failed with " MACSTR,
1731                 MAC2STR(p2p->go_neg_peer->intended_addr));
1732
1733         p2p_clear_go_neg(p2p);
1734 }
1735
1736
1737 struct p2p_data * p2p_init(const struct p2p_config *cfg)
1738 {
1739         struct p2p_data *p2p;
1740
1741         if (cfg->max_peers < 1)
1742                 return NULL;
1743
1744         p2p = os_zalloc(sizeof(*p2p) + sizeof(*cfg));
1745         if (p2p == NULL)
1746                 return NULL;
1747         p2p->cfg = (struct p2p_config *) (p2p + 1);
1748         os_memcpy(p2p->cfg, cfg, sizeof(*cfg));
1749         if (cfg->dev_name)
1750                 p2p->cfg->dev_name = os_strdup(cfg->dev_name);
1751
1752         p2p->min_disc_int = 1;
1753         p2p->max_disc_int = 3;
1754
1755         os_get_random(&p2p->next_tie_breaker, 1);
1756         p2p->next_tie_breaker &= 0x01;
1757         if (cfg->sd_request)
1758                 p2p->dev_capab |= P2P_DEV_CAPAB_SERVICE_DISCOVERY;
1759         p2p->dev_capab |= P2P_DEV_CAPAB_INVITATION_PROCEDURE;
1760         if (cfg->concurrent_operations)
1761                 p2p->dev_capab |= P2P_DEV_CAPAB_CONCURRENT_OPER;
1762         p2p->dev_capab |= P2P_DEV_CAPAB_CLIENT_DISCOVERABILITY;
1763
1764         dl_list_init(&p2p->devices);
1765
1766         eloop_register_timeout(P2P_PEER_EXPIRATION_INTERVAL, 0,
1767                                p2p_expiration_timeout, p2p, NULL);
1768
1769         return p2p;
1770 }
1771
1772
1773 void p2p_deinit(struct p2p_data *p2p)
1774 {
1775         eloop_cancel_timeout(p2p_expiration_timeout, p2p, NULL);
1776         eloop_cancel_timeout(p2p_ext_listen_timeout, p2p, NULL);
1777         eloop_cancel_timeout(p2p_scan_timeout, p2p, NULL);
1778         p2p_flush(p2p);
1779         os_free(p2p->cfg->dev_name);
1780         os_free(p2p->groups);
1781         wpabuf_free(p2p->sd_resp);
1782         os_free(p2p);
1783 }
1784
1785
1786 void p2p_flush(struct p2p_data *p2p)
1787 {
1788         struct p2p_device *dev, *prev;
1789         p2p_clear_timeout(p2p);
1790         p2p_set_state(p2p, P2P_IDLE);
1791         p2p->start_after_scan = P2P_AFTER_SCAN_NOTHING;
1792         p2p->go_neg_peer = NULL;
1793         eloop_cancel_timeout(p2p_find_timeout, p2p, NULL);
1794         dl_list_for_each_safe(dev, prev, &p2p->devices, struct p2p_device,
1795                               list) {
1796                 dl_list_del(&dev->list);
1797                 p2p_device_free(p2p, dev);
1798         }
1799         p2p_free_sd_queries(p2p);
1800 }
1801
1802
1803 int p2p_set_dev_name(struct p2p_data *p2p, const char *dev_name)
1804 {
1805         os_free(p2p->cfg->dev_name);
1806         if (dev_name) {
1807                 p2p->cfg->dev_name = os_strdup(dev_name);
1808                 if (p2p->cfg->dev_name == NULL)
1809                         return -1;
1810         } else
1811                 p2p->cfg->dev_name = NULL;
1812         return 0;
1813 }
1814
1815
1816 int p2p_set_pri_dev_type(struct p2p_data *p2p, const u8 *pri_dev_type)
1817 {
1818         os_memcpy(p2p->cfg->pri_dev_type, pri_dev_type, 8);
1819         return 0;
1820 }
1821
1822
1823 int p2p_set_sec_dev_types(struct p2p_data *p2p, const u8 dev_types[][8],
1824                           size_t num_dev_types)
1825 {
1826         if (num_dev_types > P2P_SEC_DEVICE_TYPES)
1827                 num_dev_types = P2P_SEC_DEVICE_TYPES;
1828         p2p->cfg->num_sec_dev_types = num_dev_types;
1829         os_memcpy(p2p->cfg->sec_dev_type, dev_types, num_dev_types * 8);
1830         return 0;
1831 }
1832
1833
1834 int p2p_set_country(struct p2p_data *p2p, const char *country)
1835 {
1836         os_memcpy(p2p->cfg->country, country, 3);
1837         return 0;
1838 }
1839
1840
1841 void p2p_continue_find(struct p2p_data *p2p)
1842 {
1843         struct p2p_device *dev;
1844         p2p_set_state(p2p, P2P_SEARCH);
1845         dl_list_for_each(dev, &p2p->devices, struct p2p_device, list) {
1846                 if (dev->flags & P2P_DEV_SD_SCHEDULE) {
1847                         if (p2p_start_sd(p2p, dev) == 0)
1848                                 return;
1849                         else
1850                                 break;
1851                 } else if (dev->req_config_methods) {
1852                         if (p2p_send_prov_disc_req(p2p, dev, 0) == 0)
1853                                 return;
1854                 }
1855         }
1856
1857         p2p_listen_in_find(p2p);
1858 }
1859
1860
1861 static void p2p_sd_cb(struct p2p_data *p2p, int success)
1862 {
1863         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
1864                 "P2P: Service Discovery Query TX callback: success=%d",
1865                 success);
1866         p2p->pending_action_state = P2P_NO_PENDING_ACTION;
1867
1868         if (!success) {
1869                 if (p2p->sd_peer) {
1870                         p2p->sd_peer->flags &= ~P2P_DEV_SD_SCHEDULE;
1871                         p2p->sd_peer = NULL;
1872                 }
1873                 p2p_continue_find(p2p);
1874                 return;
1875         }
1876
1877         if (p2p->sd_peer == NULL) {
1878                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
1879                         "P2P: No SD peer entry known");
1880                 p2p_continue_find(p2p);
1881                 return;
1882         }
1883
1884         /* Wait for response from the peer */
1885         p2p_set_state(p2p, P2P_SD_DURING_FIND);
1886         p2p_set_timeout(p2p, 0, 200000);
1887 }
1888
1889
1890 static void p2p_prov_disc_cb(struct p2p_data *p2p, int success)
1891 {
1892         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
1893                 "P2P: Provision Discovery Request TX callback: success=%d",
1894                 success);
1895         p2p->pending_action_state = P2P_NO_PENDING_ACTION;
1896
1897         if (!success) {
1898                 if (p2p->state != P2P_IDLE)
1899                         p2p_continue_find(p2p);
1900                 return;
1901         }
1902
1903         /* Wait for response from the peer */
1904         if (p2p->state == P2P_SEARCH)
1905                 p2p_set_state(p2p, P2P_PD_DURING_FIND);
1906         p2p_set_timeout(p2p, 0, 200000);
1907 }
1908
1909
1910 int p2p_scan_res_handler(struct p2p_data *p2p, const u8 *bssid, int freq,
1911                          int level, const u8 *ies, size_t ies_len)
1912 {
1913         p2p_add_device(p2p, bssid, freq, level, ies, ies_len);
1914
1915         if (p2p->go_neg_peer && p2p->state == P2P_SEARCH &&
1916             os_memcmp(p2p->go_neg_peer->p2p_device_addr, bssid, ETH_ALEN) == 0)
1917         {
1918                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
1919                         "P2P: Found GO Negotiation peer - try to start GO "
1920                         "negotiation");
1921                 p2p_connect_send(p2p, p2p->go_neg_peer);
1922                 return 1;
1923         }
1924
1925         return 0;
1926 }
1927
1928
1929 void p2p_scan_res_handled(struct p2p_data *p2p)
1930 {
1931         if (!p2p->p2p_scan_running) {
1932                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: p2p_scan was not "
1933                         "running, but scan results received");
1934         }
1935         p2p->p2p_scan_running = 0;
1936         eloop_cancel_timeout(p2p_scan_timeout, p2p, NULL);
1937
1938         if (p2p_run_after_scan(p2p))
1939                 return;
1940         if (p2p->state == P2P_SEARCH)
1941                 p2p_continue_find(p2p);
1942 }
1943
1944
1945 void p2p_scan_ie(struct p2p_data *p2p, struct wpabuf *ies)
1946 {
1947         u8 *len = p2p_buf_add_ie_hdr(ies);
1948         p2p_buf_add_capability(ies, p2p->dev_capab, 0);
1949         if (p2p->cfg->reg_class && p2p->cfg->channel)
1950                 p2p_buf_add_listen_channel(ies, p2p->cfg->country,
1951                                            p2p->cfg->reg_class,
1952                                            p2p->cfg->channel);
1953         if (p2p->ext_listen_interval)
1954                 p2p_buf_add_ext_listen_timing(ies, p2p->ext_listen_period,
1955                                               p2p->ext_listen_interval);
1956         /* TODO: p2p_buf_add_operating_channel() if GO */
1957         p2p_buf_update_ie_hdr(ies, len);
1958 }
1959
1960
1961 int p2p_ie_text(struct wpabuf *p2p_ie, char *buf, char *end)
1962 {
1963         return p2p_attr_text(p2p_ie, buf, end);
1964 }
1965
1966
1967 static void p2p_go_neg_req_cb(struct p2p_data *p2p, int success)
1968 {
1969         struct p2p_device *dev = p2p->go_neg_peer;
1970
1971         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
1972                 "P2P: GO Negotiation Request TX callback: success=%d",
1973                 success);
1974
1975         if (dev == NULL) {
1976                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
1977                         "P2P: No pending GO Negotiation");
1978                 return;
1979         }
1980
1981         if (success) {
1982                 dev->go_neg_req_sent++;
1983                 if (dev->flags & P2P_DEV_USER_REJECTED) {
1984                         p2p_set_state(p2p, P2P_IDLE);
1985                         return;
1986                 }
1987         }
1988
1989         if (!success &&
1990             (dev->dev_capab & P2P_DEV_CAPAB_CLIENT_DISCOVERABILITY) &&
1991             !is_zero_ether_addr(dev->member_in_go_dev)) {
1992                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
1993                         "P2P: Peer " MACSTR " did not acknowledge request - "
1994                         "try to use device discoverability through its GO",
1995                         MAC2STR(dev->p2p_device_addr));
1996                 p2p->cfg->send_action_done(p2p->cfg->cb_ctx);
1997                 p2p_send_dev_disc_req(p2p, dev);
1998                 return;
1999         }
2000
2001         /*
2002          * Use P2P find, if needed, to find the other device from its listen
2003          * channel.
2004          */
2005         p2p_set_state(p2p, P2P_CONNECT);
2006         p2p_set_timeout(p2p, 0, 100000);
2007 }
2008
2009
2010 static void p2p_go_neg_resp_cb(struct p2p_data *p2p, int success)
2011 {
2012         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2013                 "P2P: GO Negotiation Response TX callback: success=%d",
2014                 success);
2015         if (!p2p->go_neg_peer && p2p->state == P2P_PROVISIONING) {
2016                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2017                         "P2P: Ignore TX callback event - GO Negotiation is "
2018                         "not running anymore");
2019                 return;
2020         }
2021         p2p_set_state(p2p, P2P_CONNECT);
2022         p2p_set_timeout(p2p, 0, 100000);
2023 }
2024
2025
2026 static void p2p_go_neg_resp_failure_cb(struct p2p_data *p2p, int success)
2027 {
2028         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2029                 "P2P: GO Negotiation Response (failure) TX callback: "
2030                 "success=%d", success);
2031 }
2032
2033
2034 static void p2p_go_neg_conf_cb(struct p2p_data *p2p, int success)
2035 {
2036         struct p2p_device *dev;
2037
2038         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2039                 "P2P: GO Negotiation Confirm TX callback: success=%d",
2040                 success);
2041         p2p->cfg->send_action_done(p2p->cfg->cb_ctx);
2042         if (!success) {
2043                 /*
2044                  * It looks like the TX status for GO Negotiation Confirm is
2045                  * often showing failure even when the peer has actually
2046                  * received the frame. Since the peer may change channels
2047                  * immediately after having received the frame, we may not see
2048                  * an Ack for retries, so just dropping a single frame may
2049                  * trigger this. To allow the group formation to succeed if the
2050                  * peer did indeed receive the frame, continue regardless of
2051                  * the TX status.
2052                  */
2053                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2054                         "P2P: Assume GO Negotiation Confirm TX was actually "
2055                         "received by the peer even though Ack was not "
2056                         "reported");
2057         }
2058
2059         dev = p2p->go_neg_peer;
2060         if (dev == NULL)
2061                 return;
2062
2063         p2p_go_complete(p2p, dev);
2064 }
2065
2066
2067 void p2p_send_action_cb(struct p2p_data *p2p, unsigned int freq, const u8 *dst,
2068                         const u8 *src, const u8 *bssid, int success)
2069 {
2070         enum p2p_pending_action_state state;
2071
2072         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2073                 "P2P: Action frame TX callback (state=%d freq=%u dst=" MACSTR
2074                 " src=" MACSTR " bssid=" MACSTR " success=%d",
2075                 p2p->pending_action_state, freq, MAC2STR(dst), MAC2STR(src),
2076                 MAC2STR(bssid), success);
2077         state = p2p->pending_action_state;
2078         p2p->pending_action_state = P2P_NO_PENDING_ACTION;
2079         switch (state) {
2080         case P2P_NO_PENDING_ACTION:
2081                 break;
2082         case P2P_PENDING_GO_NEG_REQUEST:
2083                 p2p_go_neg_req_cb(p2p, success);
2084                 break;
2085         case P2P_PENDING_GO_NEG_RESPONSE:
2086                 p2p_go_neg_resp_cb(p2p, success);
2087                 break;
2088         case P2P_PENDING_GO_NEG_RESPONSE_FAILURE:
2089                 p2p_go_neg_resp_failure_cb(p2p, success);
2090                 break;
2091         case P2P_PENDING_GO_NEG_CONFIRM:
2092                 p2p_go_neg_conf_cb(p2p, success);
2093                 break;
2094         case P2P_PENDING_SD:
2095                 p2p_sd_cb(p2p, success);
2096                 break;
2097         case P2P_PENDING_PD:
2098                 p2p_prov_disc_cb(p2p, success);
2099                 break;
2100         case P2P_PENDING_INVITATION_REQUEST:
2101                 p2p_invitation_req_cb(p2p, success);
2102                 break;
2103         case P2P_PENDING_INVITATION_RESPONSE:
2104                 p2p_invitation_resp_cb(p2p, success);
2105                 break;
2106         case P2P_PENDING_DEV_DISC_REQUEST:
2107                 p2p_dev_disc_req_cb(p2p, success);
2108                 break;
2109         case P2P_PENDING_DEV_DISC_RESPONSE:
2110                 p2p_dev_disc_resp_cb(p2p, success);
2111                 break;
2112         case P2P_PENDING_GO_DISC_REQ:
2113                 p2p_go_disc_req_cb(p2p, success);
2114                 break;
2115         }
2116 }
2117
2118
2119 void p2p_listen_cb(struct p2p_data *p2p, unsigned int freq,
2120                    unsigned int duration)
2121 {
2122         if (freq == p2p->pending_client_disc_freq) {
2123                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2124                         "P2P: Client discoverability remain-awake completed");
2125                 p2p->pending_client_disc_freq = 0;
2126                 return;
2127         }
2128
2129         if (freq != p2p->pending_listen_freq) {
2130                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2131                         "P2P: Unexpected listen callback for freq=%u "
2132                         "duration=%u (pending_listen_freq=%u)",
2133                         freq, duration, p2p->pending_listen_freq);
2134                 return;
2135         }
2136
2137         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2138                 "P2P: Starting Listen timeout(%u,%u) on freq=%u based on "
2139                 "callback",
2140                 p2p->pending_listen_sec, p2p->pending_listen_usec,
2141                 p2p->pending_listen_freq);
2142         p2p->in_listen = 1;
2143         p2p->drv_in_listen = 1;
2144         if (p2p->pending_listen_sec || p2p->pending_listen_usec) {
2145                 /*
2146                  * Add 20 msec extra wait to avoid race condition with driver
2147                  * remain-on-channel end event, i.e., give driver more time to
2148                  * complete the operation before our timeout expires.
2149                  */
2150                 p2p_set_timeout(p2p, p2p->pending_listen_sec,
2151                                 p2p->pending_listen_usec + 20000);
2152         }
2153
2154         p2p->pending_listen_freq = 0;
2155 }
2156
2157
2158 int p2p_listen_end(struct p2p_data *p2p, unsigned int freq)
2159 {
2160         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Driver ended Listen "
2161                 "state (freq=%u)", freq);
2162         p2p->drv_in_listen = 0;
2163         if (p2p->in_listen)
2164                 return 0; /* Internal timeout will trigger the next step */
2165
2166         if (p2p->state == P2P_CONNECT_LISTEN && p2p->go_neg_peer) {
2167                 p2p_set_state(p2p, P2P_CONNECT);
2168                 p2p_connect_send(p2p, p2p->go_neg_peer);
2169                 return 1;
2170         } else if (p2p->state == P2P_SEARCH) {
2171                 p2p_search(p2p);
2172                 return 1;
2173         }
2174
2175         return 0;
2176 }
2177
2178
2179 static void p2p_timeout_connect(struct p2p_data *p2p)
2180 {
2181         p2p->cfg->send_action_done(p2p->cfg->cb_ctx);
2182         p2p_set_state(p2p, P2P_CONNECT_LISTEN);
2183         p2p_listen_in_find(p2p);
2184 }
2185
2186
2187 static void p2p_timeout_connect_listen(struct p2p_data *p2p)
2188 {
2189         if (p2p->go_neg_peer) {
2190                 if (p2p->drv_in_listen) {
2191                         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Driver is "
2192                                 "still in Listen state; wait for it to "
2193                                 "complete");
2194                         return;
2195                 }
2196                 p2p_set_state(p2p, P2P_CONNECT);
2197                 p2p_connect_send(p2p, p2p->go_neg_peer);
2198         } else
2199                 p2p_set_state(p2p, P2P_IDLE);
2200 }
2201
2202
2203 static void p2p_timeout_wait_peer_connect(struct p2p_data *p2p)
2204 {
2205         /*
2206          * TODO: could remain constantly in Listen state for some time if there
2207          * are no other concurrent uses for the radio. For now, go to listen
2208          * state once per second to give other uses a chance to use the radio.
2209          */
2210         p2p_set_state(p2p, P2P_WAIT_PEER_IDLE);
2211         p2p_set_timeout(p2p, 1, 0);
2212 }
2213
2214
2215 static void p2p_timeout_wait_peer_idle(struct p2p_data *p2p)
2216 {
2217         struct p2p_device *dev = p2p->go_neg_peer;
2218
2219         if (dev == NULL) {
2220                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2221                         "P2P: Unknown GO Neg peer - stop GO Neg wait");
2222                 return;
2223         }
2224
2225         dev->wait_count++;
2226         if (dev->wait_count >= 120) {
2227                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2228                         "P2P: Timeout on waiting peer to become ready for GO "
2229                         "Negotiation");
2230                 p2p_go_neg_failed(p2p, dev, -1);
2231                 return;
2232         }
2233
2234         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2235                 "P2P: Go to Listen state while waiting for the peer to become "
2236                 "ready for GO Negotiation");
2237         p2p_set_state(p2p, P2P_WAIT_PEER_CONNECT);
2238         p2p_listen_in_find(p2p);
2239 }
2240
2241
2242 static void p2p_timeout_sd_during_find(struct p2p_data *p2p)
2243 {
2244         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2245                 "P2P: Service Discovery Query timeout");
2246         if (p2p->sd_peer) {
2247                 p2p->cfg->send_action_done(p2p->cfg->cb_ctx);
2248                 p2p->sd_peer->flags &= ~P2P_DEV_SD_SCHEDULE;
2249                 p2p->sd_peer = NULL;
2250         }
2251         p2p_continue_find(p2p);
2252 }
2253
2254
2255 static void p2p_timeout_prov_disc_during_find(struct p2p_data *p2p)
2256 {
2257         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2258                 "P2P: Provision Discovery Request timeout");
2259         p2p->cfg->send_action_done(p2p->cfg->cb_ctx);
2260         p2p_continue_find(p2p);
2261 }
2262
2263
2264 static void p2p_timeout_invite(struct p2p_data *p2p)
2265 {
2266         p2p->cfg->send_action_done(p2p->cfg->cb_ctx);
2267         p2p_set_state(p2p, P2P_INVITE_LISTEN);
2268         p2p_listen_in_find(p2p);
2269 }
2270
2271
2272 static void p2p_timeout_invite_listen(struct p2p_data *p2p)
2273 {
2274         if (p2p->invite_peer && p2p->invite_peer->invitation_reqs < 100) {
2275                 p2p_set_state(p2p, P2P_INVITE);
2276                 p2p_invite_send(p2p, p2p->invite_peer,
2277                                 p2p->invite_go_dev_addr);
2278         } else {
2279                 if (p2p->invite_peer) {
2280                         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2281                                 "P2P: Invitation Request retry limit reached");
2282                         if (p2p->cfg->invitation_result)
2283                                 p2p->cfg->invitation_result(
2284                                         p2p->cfg->cb_ctx, -1, NULL);
2285                 }
2286                 p2p_set_state(p2p, P2P_IDLE);
2287         }
2288 }
2289
2290
2291 static void p2p_state_timeout(void *eloop_ctx, void *timeout_ctx)
2292 {
2293         struct p2p_data *p2p = eloop_ctx;
2294
2295         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Timeout (state=%s)",
2296                 p2p_state_txt(p2p->state));
2297
2298         p2p->in_listen = 0;
2299
2300         switch (p2p->state) {
2301         case P2P_IDLE:
2302                 break;
2303         case P2P_SEARCH:
2304                 p2p_search(p2p);
2305                 break;
2306         case P2P_CONNECT:
2307                 p2p_timeout_connect(p2p);
2308                 break;
2309         case P2P_CONNECT_LISTEN:
2310                 p2p_timeout_connect_listen(p2p);
2311                 break;
2312         case P2P_GO_NEG:
2313                 break;
2314         case P2P_LISTEN_ONLY:
2315                 if (p2p->ext_listen_only) {
2316                         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2317                                 "P2P: Extended Listen Timing - Listen State "
2318                                 "completed");
2319                         p2p->ext_listen_only = 0;
2320                         p2p_set_state(p2p, P2P_IDLE);
2321                 }
2322                 break;
2323         case P2P_WAIT_PEER_CONNECT:
2324                 p2p_timeout_wait_peer_connect(p2p);
2325                 break;
2326         case P2P_WAIT_PEER_IDLE:
2327                 p2p_timeout_wait_peer_idle(p2p);
2328                 break;
2329         case P2P_SD_DURING_FIND:
2330                 p2p_timeout_sd_during_find(p2p);
2331                 break;
2332         case P2P_PROVISIONING:
2333                 break;
2334         case P2P_PD_DURING_FIND:
2335                 p2p_timeout_prov_disc_during_find(p2p);
2336                 break;
2337         case P2P_INVITE:
2338                 p2p_timeout_invite(p2p);
2339                 break;
2340         case P2P_INVITE_LISTEN:
2341                 p2p_timeout_invite_listen(p2p);
2342                 break;
2343         }
2344 }
2345
2346
2347 int p2p_reject(struct p2p_data *p2p, const u8 *peer_addr)
2348 {
2349         struct p2p_device *dev;
2350
2351         dev = p2p_get_device(p2p, peer_addr);
2352         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Local request to reject "
2353                 "connection attempts by peer " MACSTR, MAC2STR(peer_addr));
2354         if (dev == NULL) {
2355                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Peer " MACSTR
2356                         " unknown", MAC2STR(peer_addr));
2357                 return -1;
2358         }
2359         dev->status = P2P_SC_FAIL_REJECTED_BY_USER;
2360         dev->flags |= P2P_DEV_USER_REJECTED;
2361         return 0;
2362 }
2363
2364
2365 static const char * p2p_wps_method_text(enum p2p_wps_method method)
2366 {
2367         switch (method) {
2368         case WPS_NOT_READY:
2369                 return "not-ready";
2370         case WPS_PIN_LABEL:
2371                 return "Label";
2372         case WPS_PIN_DISPLAY:
2373                 return "Display";
2374         case WPS_PIN_KEYPAD:
2375                 return "Keypad";
2376         case WPS_PBC:
2377                 return "PBC";
2378         }
2379
2380         return "??";
2381 }
2382
2383
2384 static const char * p2p_go_state_text(enum p2p_go_state go_state)
2385 {
2386         switch (go_state) {
2387         case UNKNOWN_GO:
2388                 return "unknown";
2389         case LOCAL_GO:
2390                 return "local";
2391         case  REMOTE_GO:
2392                 return "remote";
2393         }
2394
2395         return "??";
2396 }
2397
2398
2399 int p2p_get_peer_info(struct p2p_data *p2p, const u8 *addr, int next,
2400                       char *buf, size_t buflen)
2401 {
2402         struct p2p_device *dev;
2403         int res;
2404         char *pos, *end;
2405         struct os_time now;
2406         char devtype[WPS_DEV_TYPE_BUFSIZE];
2407
2408         if (addr)
2409                 dev = p2p_get_device(p2p, addr);
2410         else
2411                 dev = dl_list_first(&p2p->devices, struct p2p_device, list);
2412
2413         if (dev && next) {
2414                 dev = dl_list_first(&dev->list, struct p2p_device, list);
2415                 if (&dev->list == &p2p->devices)
2416                         dev = NULL;
2417         }
2418
2419         if (dev == NULL)
2420                 return -1;
2421
2422         pos = buf;
2423         end = buf + buflen;
2424
2425         res = os_snprintf(pos, end - pos, MACSTR "\n",
2426                           MAC2STR(dev->p2p_device_addr));
2427         if (res < 0 || res >= end - pos)
2428                 return pos - buf;
2429         pos += res;
2430
2431         os_get_time(&now);
2432         res = os_snprintf(pos, end - pos,
2433                           "age=%d\n"
2434                           "listen_freq=%d\n"
2435                           "level=%d\n"
2436                           "wps_method=%s\n"
2437                           "interface_addr=" MACSTR "\n"
2438                           "member_in_go_dev=" MACSTR "\n"
2439                           "member_in_go_iface=" MACSTR "\n"
2440                           "pri_dev_type=%s\n"
2441                           "device_name=%s\n"
2442                           "config_methods=0x%x\n"
2443                           "dev_capab=0x%x\n"
2444                           "group_capab=0x%x\n"
2445                           "go_neg_req_sent=%d\n"
2446                           "go_state=%s\n"
2447                           "dialog_token=%u\n"
2448                           "intended_addr=" MACSTR "\n"
2449                           "country=%c%c\n"
2450                           "oper_freq=%d\n"
2451                           "req_config_methods=0x%x\n"
2452                           "flags=%s%s%s%s%s%s%s%s%s%s%s%s%s\n"
2453                           "status=%d\n"
2454                           "wait_count=%u\n"
2455                           "invitation_reqs=%u\n",
2456                           (int) (now.sec - dev->last_seen.sec),
2457                           dev->listen_freq,
2458                           dev->level,
2459                           p2p_wps_method_text(dev->wps_method),
2460                           MAC2STR(dev->interface_addr),
2461                           MAC2STR(dev->member_in_go_dev),
2462                           MAC2STR(dev->member_in_go_iface),
2463                           wps_dev_type_bin2str(dev->pri_dev_type,
2464                                                devtype, sizeof(devtype)),
2465                           dev->device_name,
2466                           dev->config_methods,
2467                           dev->dev_capab,
2468                           dev->group_capab,
2469                           dev->go_neg_req_sent,
2470                           p2p_go_state_text(dev->go_state),
2471                           dev->dialog_token,
2472                           MAC2STR(dev->intended_addr),
2473                           dev->country[0] ? dev->country[0] : '_',
2474                           dev->country[1] ? dev->country[1] : '_',
2475                           dev->oper_freq,
2476                           dev->req_config_methods,
2477                           dev->flags & P2P_DEV_PROBE_REQ_ONLY ?
2478                           "[PROBE_REQ_ONLY]" : "",
2479                           dev->flags & P2P_DEV_REPORTED ? "[REPORTED]" : "",
2480                           dev->flags & P2P_DEV_NOT_YET_READY ?
2481                           "[NOT_YET_READY]" : "",
2482                           dev->flags & P2P_DEV_SD_INFO ? "[SD_INFO]" : "",
2483                           dev->flags & P2P_DEV_SD_SCHEDULE ? "[SD_SCHEDULE]" :
2484                           "",
2485                           dev->flags & P2P_DEV_PD_PEER_DISPLAY ?
2486                           "[PD_PEER_DISPLAY]" : "",
2487                           dev->flags & P2P_DEV_PD_PEER_KEYPAD ?
2488                           "[PD_PEER_KEYPAD]" : "",
2489                           dev->flags & P2P_DEV_USER_REJECTED ?
2490                           "[USER_REJECTED]" : "",
2491                           dev->flags & P2P_DEV_PEER_WAITING_RESPONSE ?
2492                           "[PEER_WAITING_RESPONSE]" : "",
2493                           dev->flags & P2P_DEV_PREFER_PERSISTENT_GROUP ?
2494                           "[PREFER_PERSISTENT_GROUP]" : "",
2495                           dev->flags & P2P_DEV_WAIT_GO_NEG_RESPONSE ?
2496                           "[WAIT_GO_NEG_RESPONSE]" : "",
2497                           dev->flags & P2P_DEV_WAIT_GO_NEG_CONFIRM ?
2498                           "[WAIT_GO_NEG_CONFIRM]" : "",
2499                           dev->flags & P2P_DEV_GROUP_CLIENT_ONLY ?
2500                           "[GROUP_CLIENT_ONLY]" : "",
2501                           dev->status,
2502                           dev->wait_count,
2503                           dev->invitation_reqs);
2504         if (res < 0 || res >= end - pos)
2505                 return pos - buf;
2506         pos += res;
2507
2508         if (dev->ext_listen_period) {
2509                 res = os_snprintf(pos, end - pos,
2510                                   "ext_listen_period=%u\n"
2511                                   "ext_listen_interval=%u\n",
2512                                   dev->ext_listen_period,
2513                                   dev->ext_listen_interval);
2514                 if (res < 0 || res >= end - pos)
2515                         return pos - buf;
2516                 pos += res;
2517         }
2518
2519         if (dev->oper_ssid_len) {
2520                 res = os_snprintf(pos, end - pos,
2521                                   "oper_ssid=%s\n",
2522                                   wpa_ssid_txt(dev->oper_ssid,
2523                                                dev->oper_ssid_len));
2524                 if (res < 0 || res >= end - pos)
2525                         return pos - buf;
2526                 pos += res;
2527         }
2528
2529         return pos - buf;
2530 }
2531
2532
2533 void p2p_set_client_discoverability(struct p2p_data *p2p, int enabled)
2534 {
2535         if (enabled) {
2536                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Client "
2537                         "discoverability enabled");
2538                 p2p->dev_capab |= P2P_DEV_CAPAB_CLIENT_DISCOVERABILITY;
2539         } else {
2540                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Client "
2541                         "discoverability disabled");
2542                 p2p->dev_capab &= ~P2P_DEV_CAPAB_CLIENT_DISCOVERABILITY;
2543         }
2544 }
2545
2546
2547 static struct wpabuf * p2p_build_presence_req(u32 duration1, u32 interval1,
2548                                               u32 duration2, u32 interval2)
2549 {
2550         struct wpabuf *req;
2551         struct p2p_noa_desc desc1, desc2, *ptr1 = NULL, *ptr2 = NULL;
2552         u8 *len;
2553
2554         req = wpabuf_alloc(100);
2555         if (req == NULL)
2556                 return NULL;
2557
2558         if (duration1 || interval1) {
2559                 os_memset(&desc1, 0, sizeof(desc1));
2560                 desc1.count_type = 1;
2561                 desc1.duration = duration1;
2562                 desc1.interval = interval1;
2563                 ptr1 = &desc1;
2564
2565                 if (duration2 || interval2) {
2566                         os_memset(&desc2, 0, sizeof(desc2));
2567                         desc2.count_type = 2;
2568                         desc2.duration = duration2;
2569                         desc2.interval = interval2;
2570                         ptr2 = &desc2;
2571                 }
2572         }
2573
2574         p2p_buf_add_action_hdr(req, P2P_PRESENCE_REQ, 1);
2575         len = p2p_buf_add_ie_hdr(req);
2576         p2p_buf_add_noa(req, 0, 0, 0, ptr1, ptr2);
2577         p2p_buf_update_ie_hdr(req, len);
2578
2579         return req;
2580 }
2581
2582
2583 int p2p_presence_req(struct p2p_data *p2p, const u8 *go_interface_addr,
2584                      const u8 *own_interface_addr, unsigned int freq,
2585                      u32 duration1, u32 interval1, u32 duration2,
2586                      u32 interval2)
2587 {
2588         struct wpabuf *req;
2589
2590         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Send Presence Request to "
2591                 "GO " MACSTR " (own interface " MACSTR ") freq=%u dur1=%u "
2592                 "int1=%u dur2=%u int2=%u",
2593                 MAC2STR(go_interface_addr), MAC2STR(own_interface_addr),
2594                 freq, duration1, interval1, duration2, interval2);
2595
2596         req = p2p_build_presence_req(duration1, interval1, duration2,
2597                                      interval2);
2598         if (req == NULL)
2599                 return -1;
2600
2601         p2p->pending_action_state = P2P_NO_PENDING_ACTION;
2602         if (p2p->cfg->send_action(p2p->cfg->cb_ctx, freq, go_interface_addr,
2603                                   own_interface_addr,
2604                                   go_interface_addr,
2605                                   wpabuf_head(req), wpabuf_len(req), 200) < 0)
2606         {
2607                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2608                         "P2P: Failed to send Action frame");
2609         }
2610         wpabuf_free(req);
2611
2612         return 0;
2613 }
2614
2615
2616 static struct wpabuf * p2p_build_presence_resp(u8 status, const u8 *noa,
2617                                                size_t noa_len, u8 dialog_token)
2618 {
2619         struct wpabuf *resp;
2620         u8 *len;
2621
2622         resp = wpabuf_alloc(100 + noa_len);
2623         if (resp == NULL)
2624                 return NULL;
2625
2626         p2p_buf_add_action_hdr(resp, P2P_PRESENCE_RESP, dialog_token);
2627         len = p2p_buf_add_ie_hdr(resp);
2628         p2p_buf_add_status(resp, status);
2629         if (noa) {
2630                 wpabuf_put_u8(resp, P2P_ATTR_NOTICE_OF_ABSENCE);
2631                 wpabuf_put_le16(resp, noa_len);
2632                 wpabuf_put_data(resp, noa, noa_len);
2633         } else
2634                 p2p_buf_add_noa(resp, 0, 0, 0, NULL, NULL);
2635         p2p_buf_update_ie_hdr(resp, len);
2636
2637         return resp;
2638 }
2639
2640
2641 static void p2p_process_presence_req(struct p2p_data *p2p, const u8 *da,
2642                                      const u8 *sa, const u8 *data, size_t len,
2643                                      int rx_freq)
2644 {
2645         struct p2p_message msg;
2646         u8 status;
2647         struct wpabuf *resp;
2648         size_t g;
2649         struct p2p_group *group = NULL;
2650         int parsed = 0;
2651         u8 noa[50];
2652         int noa_len;
2653
2654         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2655                 "P2P: Received P2P Action - P2P Presence Request");
2656
2657         for (g = 0; g < p2p->num_groups; g++) {
2658                 if (os_memcmp(da, p2p_group_get_interface_addr(p2p->groups[g]),
2659                               ETH_ALEN) == 0) {
2660                         group = p2p->groups[g];
2661                         break;
2662                 }
2663         }
2664         if (group == NULL) {
2665                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2666                         "P2P: Ignore P2P Presence Request for unknown group "
2667                         MACSTR, MAC2STR(da));
2668                 return;
2669         }
2670
2671         if (p2p_parse(data, len, &msg) < 0) {
2672                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2673                         "P2P: Failed to parse P2P Presence Request");
2674                 status = P2P_SC_FAIL_INVALID_PARAMS;
2675                 goto fail;
2676         }
2677         parsed = 1;
2678
2679         if (msg.noa == NULL) {
2680                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2681                         "P2P: No NoA attribute in P2P Presence Request");
2682                 status = P2P_SC_FAIL_INVALID_PARAMS;
2683                 goto fail;
2684         }
2685
2686         status = p2p_group_presence_req(group, sa, msg.noa, msg.noa_len);
2687
2688 fail:
2689         if (p2p->cfg->get_noa)
2690                 noa_len = p2p->cfg->get_noa(p2p->cfg->cb_ctx, da, noa,
2691                                             sizeof(noa));
2692         else
2693                 noa_len = -1;
2694         resp = p2p_build_presence_resp(status, noa_len > 0 ? noa : NULL,
2695                                        noa_len > 0 ? noa_len : 0,
2696                                        msg.dialog_token);
2697         if (parsed)
2698                 p2p_parse_free(&msg);
2699         if (resp == NULL)
2700                 return;
2701
2702         p2p->pending_action_state = P2P_NO_PENDING_ACTION;
2703         if (p2p->cfg->send_action(p2p->cfg->cb_ctx, rx_freq, sa, da, da,
2704                                   wpabuf_head(resp), wpabuf_len(resp), 200) <
2705             0) {
2706                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2707                         "P2P: Failed to send Action frame");
2708         }
2709         wpabuf_free(resp);
2710 }
2711
2712
2713 static void p2p_process_presence_resp(struct p2p_data *p2p, const u8 *da,
2714                                       const u8 *sa, const u8 *data, size_t len)
2715 {
2716         struct p2p_message msg;
2717
2718         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2719                 "P2P: Received P2P Action - P2P Presence Response");
2720
2721         if (p2p_parse(data, len, &msg) < 0) {
2722                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2723                         "P2P: Failed to parse P2P Presence Response");
2724                 return;
2725         }
2726
2727         if (msg.status == NULL || msg.noa == NULL) {
2728                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2729                         "P2P: No Status or NoA attribute in P2P Presence "
2730                         "Response");
2731                 p2p_parse_free(&msg);
2732                 return;
2733         }
2734
2735         if (*msg.status) {
2736                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2737                         "P2P: P2P Presence Request was rejected: status %u",
2738                         *msg.status);
2739                 p2p_parse_free(&msg);
2740                 return;
2741         }
2742
2743         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2744                 "P2P: P2P Presence Request was accepted");
2745         wpa_hexdump(MSG_DEBUG, "P2P: P2P Presence Response - NoA",
2746                     msg.noa, msg.noa_len);
2747         /* TODO: process NoA */
2748         p2p_parse_free(&msg);
2749 }
2750
2751
2752 static void p2p_ext_listen_timeout(void *eloop_ctx, void *timeout_ctx)
2753 {
2754         struct p2p_data *p2p = eloop_ctx;
2755
2756         if (p2p->ext_listen_interval) {
2757                 /* Schedule next extended listen timeout */
2758                 eloop_register_timeout(p2p->ext_listen_interval_sec,
2759                                        p2p->ext_listen_interval_usec,
2760                                        p2p_ext_listen_timeout, p2p, NULL);
2761         }
2762
2763         if (p2p->state != P2P_IDLE) {
2764                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Skip Extended "
2765                         "Listen timeout in active state (%s)",
2766                         p2p_state_txt(p2p->state));
2767                 return;
2768         }
2769
2770         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Extended Listen timeout");
2771         p2p->ext_listen_only = 1;
2772         if (p2p_listen(p2p, p2p->ext_listen_period) < 0) {
2773                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Failed to start "
2774                         "Listen state for Extended Listen Timing");
2775                 p2p->ext_listen_only = 0;
2776         }
2777 }
2778
2779
2780 int p2p_ext_listen(struct p2p_data *p2p, unsigned int period,
2781                    unsigned int interval)
2782 {
2783         if (period > 65535 || interval > 65535 || period > interval ||
2784             (period == 0 && interval > 0) || (period > 0 && interval == 0)) {
2785                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2786                         "P2P: Invalid Extended Listen Timing request: "
2787                         "period=%u interval=%u", period, interval);
2788                 return -1;
2789         }
2790
2791         eloop_cancel_timeout(p2p_ext_listen_timeout, p2p, NULL);
2792
2793         if (interval == 0) {
2794                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2795                         "P2P: Disabling Extended Listen Timing");
2796                 p2p->ext_listen_period = 0;
2797                 p2p->ext_listen_interval = 0;
2798                 return 0;
2799         }
2800
2801         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2802                 "P2P: Enabling Extended Listen Timing: period %u msec, "
2803                 "interval %u msec", period, interval);
2804         p2p->ext_listen_period = period;
2805         p2p->ext_listen_interval = interval;
2806         p2p->ext_listen_interval_sec = interval / 1000;
2807         p2p->ext_listen_interval_usec = (interval % 1000) * 1000;
2808
2809         eloop_register_timeout(p2p->ext_listen_interval_sec,
2810                                p2p->ext_listen_interval_usec,
2811                                p2p_ext_listen_timeout, p2p, NULL);
2812
2813         return 0;
2814 }
2815
2816
2817 void p2p_deauth_notif(struct p2p_data *p2p, const u8 *bssid, u16 reason_code,
2818                       const u8 *ie, size_t ie_len)
2819 {
2820         struct p2p_message msg;
2821
2822         if (bssid == NULL || ie == NULL)
2823                 return;
2824
2825         os_memset(&msg, 0, sizeof(msg));
2826         if (p2p_parse_ies(ie, ie_len, &msg))
2827                 return;
2828         if (msg.minor_reason_code == NULL)
2829                 return;
2830
2831         wpa_msg(p2p->cfg->msg_ctx, MSG_INFO,
2832                 "P2P: Deauthentication notification BSSID " MACSTR
2833                 " reason_code=%u minor_reason_code=%u",
2834                 MAC2STR(bssid), reason_code, *msg.minor_reason_code);
2835
2836         p2p_parse_free(&msg);
2837 }
2838
2839
2840 void p2p_disassoc_notif(struct p2p_data *p2p, const u8 *bssid, u16 reason_code,
2841                         const u8 *ie, size_t ie_len)
2842 {
2843         struct p2p_message msg;
2844
2845         if (bssid == NULL || ie == NULL)
2846                 return;
2847
2848         os_memset(&msg, 0, sizeof(msg));
2849         if (p2p_parse_ies(ie, ie_len, &msg))
2850                 return;
2851         if (msg.minor_reason_code == NULL)
2852                 return;
2853
2854         wpa_msg(p2p->cfg->msg_ctx, MSG_INFO,
2855                 "P2P: Disassociation notification BSSID " MACSTR
2856                 " reason_code=%u minor_reason_code=%u",
2857                 MAC2STR(bssid), reason_code, *msg.minor_reason_code);
2858
2859         p2p_parse_free(&msg);
2860 }
2861
2862
2863 void p2p_set_managed_oper(struct p2p_data *p2p, int enabled)
2864 {
2865         if (enabled) {
2866                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Managed P2P "
2867                         "Device operations enabled");
2868                 p2p->dev_capab |= P2P_DEV_CAPAB_INFRA_MANAGED;
2869         } else {
2870                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Managed P2P "
2871                         "Device operations disabled");
2872                 p2p->dev_capab &= ~P2P_DEV_CAPAB_INFRA_MANAGED;
2873         }
2874 }
2875
2876
2877 int p2p_set_listen_channel(struct p2p_data *p2p, u8 reg_class, u8 channel)
2878 {
2879         if (p2p_channel_to_freq(p2p->cfg->country, reg_class, channel) < 0)
2880                 return -1;
2881
2882         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Set Listen channel: "
2883                 "reg_class %u channel %u", reg_class, channel);
2884         p2p->cfg->reg_class = reg_class;
2885         p2p->cfg->channel = channel;
2886
2887         return 0;
2888 }
2889
2890
2891 int p2p_set_ssid_postfix(struct p2p_data *p2p, const u8 *postfix, size_t len)
2892 {
2893         wpa_hexdump_ascii(MSG_DEBUG, "P2P: New SSID postfix", postfix, len);
2894         if (postfix == NULL) {
2895                 p2p->cfg->ssid_postfix_len = 0;
2896                 return 0;
2897         }
2898         if (len > sizeof(p2p->cfg->ssid_postfix))
2899                 return -1;
2900         os_memcpy(p2p->cfg->ssid_postfix, postfix, len);
2901         p2p->cfg->ssid_postfix_len = len;
2902         return 0;
2903 }
2904
2905
2906 int p2p_get_interface_addr(struct p2p_data *p2p, const u8 *dev_addr,
2907                            u8 *iface_addr)
2908 {
2909         struct p2p_device *dev = p2p_get_device(p2p, dev_addr);
2910         if (dev == NULL || is_zero_ether_addr(dev->interface_addr))
2911                 return -1;
2912         os_memcpy(iface_addr, dev->interface_addr, ETH_ALEN);
2913         return 0;
2914 }