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