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