P2P: Add p2p_client_list support for FullMAC Persistent GO
[mech_eap.git] / src / p2p / p2p.c
1 /*
2  * Wi-Fi Direct - P2P module
3  * Copyright (c) 2009-2010, Atheros Communications
4  *
5  * This 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_in_p2p_ie(struct wpabuf *p2p_ie, u8 *dev_addr)
2171 {
2172         struct p2p_message msg;
2173
2174         os_memset(&msg, 0, sizeof(msg));
2175         if (p2p_parse_p2p_ie(p2p_ie, &msg))
2176                 return -1;
2177
2178         if (msg.p2p_device_addr) {
2179                 os_memcpy(dev_addr, msg.p2p_device_addr, ETH_ALEN);
2180                 return 0;
2181         } else if (msg.device_id) {
2182                 os_memcpy(dev_addr, msg.device_id, ETH_ALEN);
2183                 return 0;
2184         }
2185         return -1;
2186 }
2187
2188
2189 int p2p_parse_dev_addr(const u8 *ies, size_t ies_len, u8 *dev_addr)
2190 {
2191         struct wpabuf *p2p_ie;
2192         int ret;
2193
2194         p2p_ie = ieee802_11_vendor_ie_concat(ies, ies_len,
2195                                              P2P_IE_VENDOR_TYPE);
2196         if (p2p_ie == NULL)
2197                 return -1;
2198         ret = p2p_parse_dev_addr_in_p2p_ie(p2p_ie, dev_addr);
2199         wpabuf_free(p2p_ie);
2200         return ret;
2201 }
2202
2203
2204 static void p2p_clear_go_neg(struct p2p_data *p2p)
2205 {
2206         p2p->go_neg_peer = NULL;
2207         p2p_clear_timeout(p2p);
2208         p2p_set_state(p2p, P2P_IDLE);
2209 }
2210
2211
2212 void p2p_wps_success_cb(struct p2p_data *p2p, const u8 *mac_addr)
2213 {
2214         if (p2p->go_neg_peer == NULL) {
2215                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2216                         "P2P: No pending Group Formation - "
2217                         "ignore WPS registration success notification");
2218                 return; /* No pending Group Formation */
2219         }
2220
2221         if (os_memcmp(mac_addr, p2p->go_neg_peer->intended_addr, ETH_ALEN) !=
2222             0) {
2223                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2224                         "P2P: Ignore WPS registration success notification "
2225                         "for " MACSTR " (GO Negotiation peer " MACSTR ")",
2226                         MAC2STR(mac_addr),
2227                         MAC2STR(p2p->go_neg_peer->intended_addr));
2228                 return; /* Ignore unexpected peer address */
2229         }
2230
2231         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2232                 "P2P: Group Formation completed successfully with " MACSTR,
2233                 MAC2STR(mac_addr));
2234
2235         p2p_clear_go_neg(p2p);
2236 }
2237
2238
2239 void p2p_group_formation_failed(struct p2p_data *p2p)
2240 {
2241         if (p2p->go_neg_peer == NULL) {
2242                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2243                         "P2P: No pending Group Formation - "
2244                         "ignore group formation failure notification");
2245                 return; /* No pending Group Formation */
2246         }
2247
2248         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2249                 "P2P: Group Formation failed with " MACSTR,
2250                 MAC2STR(p2p->go_neg_peer->intended_addr));
2251
2252         p2p_clear_go_neg(p2p);
2253 }
2254
2255
2256 struct p2p_data * p2p_init(const struct p2p_config *cfg)
2257 {
2258         struct p2p_data *p2p;
2259
2260         if (cfg->max_peers < 1)
2261                 return NULL;
2262
2263         p2p = os_zalloc(sizeof(*p2p) + sizeof(*cfg));
2264         if (p2p == NULL)
2265                 return NULL;
2266         p2p->cfg = (struct p2p_config *) (p2p + 1);
2267         os_memcpy(p2p->cfg, cfg, sizeof(*cfg));
2268         if (cfg->dev_name)
2269                 p2p->cfg->dev_name = os_strdup(cfg->dev_name);
2270         if (cfg->manufacturer)
2271                 p2p->cfg->manufacturer = os_strdup(cfg->manufacturer);
2272         if (cfg->model_name)
2273                 p2p->cfg->model_name = os_strdup(cfg->model_name);
2274         if (cfg->model_number)
2275                 p2p->cfg->model_number = os_strdup(cfg->model_number);
2276         if (cfg->serial_number)
2277                 p2p->cfg->serial_number = os_strdup(cfg->serial_number);
2278         if (cfg->pref_chan) {
2279                 p2p->cfg->pref_chan = os_malloc(cfg->num_pref_chan *
2280                                                 sizeof(struct p2p_channel));
2281                 if (p2p->cfg->pref_chan) {
2282                         os_memcpy(p2p->cfg->pref_chan, cfg->pref_chan,
2283                                   cfg->num_pref_chan *
2284                                   sizeof(struct p2p_channel));
2285                 } else
2286                         p2p->cfg->num_pref_chan = 0;
2287         }
2288
2289         p2p->min_disc_int = 1;
2290         p2p->max_disc_int = 3;
2291
2292         os_get_random(&p2p->next_tie_breaker, 1);
2293         p2p->next_tie_breaker &= 0x01;
2294         if (cfg->sd_request)
2295                 p2p->dev_capab |= P2P_DEV_CAPAB_SERVICE_DISCOVERY;
2296         p2p->dev_capab |= P2P_DEV_CAPAB_INVITATION_PROCEDURE;
2297         if (cfg->concurrent_operations)
2298                 p2p->dev_capab |= P2P_DEV_CAPAB_CONCURRENT_OPER;
2299         p2p->dev_capab |= P2P_DEV_CAPAB_CLIENT_DISCOVERABILITY;
2300
2301         dl_list_init(&p2p->devices);
2302
2303         eloop_register_timeout(P2P_PEER_EXPIRATION_INTERVAL, 0,
2304                                p2p_expiration_timeout, p2p, NULL);
2305
2306         return p2p;
2307 }
2308
2309
2310 void p2p_deinit(struct p2p_data *p2p)
2311 {
2312         eloop_cancel_timeout(p2p_expiration_timeout, p2p, NULL);
2313         eloop_cancel_timeout(p2p_ext_listen_timeout, p2p, NULL);
2314         eloop_cancel_timeout(p2p_scan_timeout, p2p, NULL);
2315         p2p_flush(p2p);
2316         p2p_free_req_dev_types(p2p);
2317         os_free(p2p->cfg->dev_name);
2318         os_free(p2p->cfg->manufacturer);
2319         os_free(p2p->cfg->model_name);
2320         os_free(p2p->cfg->model_number);
2321         os_free(p2p->cfg->serial_number);
2322         os_free(p2p->cfg->pref_chan);
2323         os_free(p2p->groups);
2324         wpabuf_free(p2p->sd_resp);
2325         os_free(p2p->after_scan_tx);
2326         p2p_remove_wps_vendor_extensions(p2p);
2327         os_free(p2p);
2328 }
2329
2330
2331 void p2p_flush(struct p2p_data *p2p)
2332 {
2333         struct p2p_device *dev, *prev;
2334         p2p_stop_find(p2p);
2335         dl_list_for_each_safe(dev, prev, &p2p->devices, struct p2p_device,
2336                               list) {
2337                 dl_list_del(&dev->list);
2338                 p2p_device_free(p2p, dev);
2339         }
2340         p2p_free_sd_queries(p2p);
2341         os_free(p2p->after_scan_tx);
2342         p2p->after_scan_tx = NULL;
2343 }
2344
2345
2346 int p2p_unauthorize(struct p2p_data *p2p, const u8 *addr)
2347 {
2348         struct p2p_device *dev;
2349
2350         dev = p2p_get_device(p2p, addr);
2351         if (dev == NULL)
2352                 return -1;
2353
2354         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Unauthorizing " MACSTR,
2355                 MAC2STR(addr));
2356
2357         if (p2p->go_neg_peer == dev)
2358                 p2p->go_neg_peer = NULL;
2359
2360         dev->wps_method = WPS_NOT_READY;
2361         dev->flags &= ~P2P_DEV_WAIT_GO_NEG_RESPONSE;
2362         dev->flags &= ~P2P_DEV_WAIT_GO_NEG_CONFIRM;
2363
2364         /* Check if after_scan_tx is for this peer. If so free it */
2365         if (p2p->after_scan_tx &&
2366             os_memcmp(addr, p2p->after_scan_tx->dst, ETH_ALEN) == 0) {
2367                 os_free(p2p->after_scan_tx);
2368                 p2p->after_scan_tx = NULL;
2369         }
2370
2371         return 0;
2372 }
2373
2374
2375 int p2p_set_dev_name(struct p2p_data *p2p, const char *dev_name)
2376 {
2377         os_free(p2p->cfg->dev_name);
2378         if (dev_name) {
2379                 p2p->cfg->dev_name = os_strdup(dev_name);
2380                 if (p2p->cfg->dev_name == NULL)
2381                         return -1;
2382         } else
2383                 p2p->cfg->dev_name = NULL;
2384         return 0;
2385 }
2386
2387
2388 int p2p_set_manufacturer(struct p2p_data *p2p, const char *manufacturer)
2389 {
2390         os_free(p2p->cfg->manufacturer);
2391         p2p->cfg->manufacturer = NULL;
2392         if (manufacturer) {
2393                 p2p->cfg->manufacturer = os_strdup(manufacturer);
2394                 if (p2p->cfg->manufacturer == NULL)
2395                         return -1;
2396         }
2397
2398         return 0;
2399 }
2400
2401
2402 int p2p_set_model_name(struct p2p_data *p2p, const char *model_name)
2403 {
2404         os_free(p2p->cfg->model_name);
2405         p2p->cfg->model_name = NULL;
2406         if (model_name) {
2407                 p2p->cfg->model_name = os_strdup(model_name);
2408                 if (p2p->cfg->model_name == NULL)
2409                         return -1;
2410         }
2411
2412         return 0;
2413 }
2414
2415
2416 int p2p_set_model_number(struct p2p_data *p2p, const char *model_number)
2417 {
2418         os_free(p2p->cfg->model_number);
2419         p2p->cfg->model_number = NULL;
2420         if (model_number) {
2421                 p2p->cfg->model_number = os_strdup(model_number);
2422                 if (p2p->cfg->model_number == NULL)
2423                         return -1;
2424         }
2425
2426         return 0;
2427 }
2428
2429
2430 int p2p_set_serial_number(struct p2p_data *p2p, const char *serial_number)
2431 {
2432         os_free(p2p->cfg->serial_number);
2433         p2p->cfg->serial_number = NULL;
2434         if (serial_number) {
2435                 p2p->cfg->serial_number = os_strdup(serial_number);
2436                 if (p2p->cfg->serial_number == NULL)
2437                         return -1;
2438         }
2439
2440         return 0;
2441 }
2442
2443
2444 void p2p_set_config_methods(struct p2p_data *p2p, u16 config_methods)
2445 {
2446         p2p->cfg->config_methods = config_methods;
2447 }
2448
2449
2450 void p2p_set_uuid(struct p2p_data *p2p, const u8 *uuid)
2451 {
2452         os_memcpy(p2p->cfg->uuid, uuid, 16);
2453 }
2454
2455
2456 int p2p_set_pri_dev_type(struct p2p_data *p2p, const u8 *pri_dev_type)
2457 {
2458         os_memcpy(p2p->cfg->pri_dev_type, pri_dev_type, 8);
2459         return 0;
2460 }
2461
2462
2463 int p2p_set_sec_dev_types(struct p2p_data *p2p, const u8 dev_types[][8],
2464                           size_t num_dev_types)
2465 {
2466         if (num_dev_types > P2P_SEC_DEVICE_TYPES)
2467                 num_dev_types = P2P_SEC_DEVICE_TYPES;
2468         p2p->cfg->num_sec_dev_types = num_dev_types;
2469         os_memcpy(p2p->cfg->sec_dev_type, dev_types, num_dev_types * 8);
2470         return 0;
2471 }
2472
2473
2474 void p2p_remove_wps_vendor_extensions(struct p2p_data *p2p)
2475 {
2476         int i;
2477
2478         for (i = 0; i < P2P_MAX_WPS_VENDOR_EXT; i++) {
2479                 wpabuf_free(p2p->wps_vendor_ext[i]);
2480                 p2p->wps_vendor_ext[i] = NULL;
2481         }
2482 }
2483
2484
2485 int p2p_add_wps_vendor_extension(struct p2p_data *p2p,
2486                                  const struct wpabuf *vendor_ext)
2487 {
2488         int i;
2489
2490         if (vendor_ext == NULL)
2491                 return -1;
2492
2493         for (i = 0; i < P2P_MAX_WPS_VENDOR_EXT; i++) {
2494                 if (p2p->wps_vendor_ext[i] == NULL)
2495                         break;
2496         }
2497         if (i >= P2P_MAX_WPS_VENDOR_EXT)
2498                 return -1;
2499
2500         p2p->wps_vendor_ext[i] = wpabuf_dup(vendor_ext);
2501         if (p2p->wps_vendor_ext[i] == NULL)
2502                 return -1;
2503
2504         return 0;
2505 }
2506
2507
2508 int p2p_set_country(struct p2p_data *p2p, const char *country)
2509 {
2510         os_memcpy(p2p->cfg->country, country, 3);
2511         return 0;
2512 }
2513
2514
2515 void p2p_continue_find(struct p2p_data *p2p)
2516 {
2517         struct p2p_device *dev;
2518         p2p_set_state(p2p, P2P_SEARCH);
2519         dl_list_for_each(dev, &p2p->devices, struct p2p_device, list) {
2520                 if (dev->flags & P2P_DEV_SD_SCHEDULE) {
2521                         if (p2p_start_sd(p2p, dev) == 0)
2522                                 return;
2523                         else
2524                                 break;
2525                 } else if (dev->req_config_methods &&
2526                            !(dev->flags & P2P_DEV_PD_FOR_JOIN)) {
2527                         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Send "
2528                                 "pending Provision Discovery Request to "
2529                                 MACSTR " (config methods 0x%x)",
2530                                 MAC2STR(dev->info.p2p_device_addr),
2531                                 dev->req_config_methods);
2532                         if (p2p_send_prov_disc_req(p2p, dev, 0, 0) == 0)
2533                                 return;
2534                 }
2535         }
2536
2537         p2p_listen_in_find(p2p);
2538 }
2539
2540
2541 static void p2p_sd_cb(struct p2p_data *p2p, int success)
2542 {
2543         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2544                 "P2P: Service Discovery Query TX callback: success=%d",
2545                 success);
2546         p2p->pending_action_state = P2P_NO_PENDING_ACTION;
2547
2548         if (!success) {
2549                 if (p2p->sd_peer) {
2550                         p2p->sd_peer->flags &= ~P2P_DEV_SD_SCHEDULE;
2551                         p2p->sd_peer = NULL;
2552                 }
2553                 p2p_continue_find(p2p);
2554                 return;
2555         }
2556
2557         if (p2p->sd_peer == NULL) {
2558                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2559                         "P2P: No SD peer entry known");
2560                 p2p_continue_find(p2p);
2561                 return;
2562         }
2563
2564         /* Wait for response from the peer */
2565         p2p_set_state(p2p, P2P_SD_DURING_FIND);
2566         p2p_set_timeout(p2p, 0, 200000);
2567 }
2568
2569
2570 /**
2571  * p2p_retry_pd - Retry any pending provision disc requests in IDLE state
2572  * @p2p: P2P module context from p2p_init()
2573  */
2574 static void p2p_retry_pd(struct p2p_data *p2p)
2575 {
2576         struct p2p_device *dev;
2577
2578         if (p2p->state != P2P_IDLE)
2579                 return;
2580
2581         /*
2582          * Retry the prov disc req attempt only for the peer that the user had
2583          * requested for and provided a join has not been initiated on it
2584          * in the meantime.
2585          */
2586
2587         dl_list_for_each(dev, &p2p->devices, struct p2p_device, list) {
2588                 if (os_memcmp(p2p->pending_pd_devaddr,
2589                               dev->info.p2p_device_addr, ETH_ALEN) != 0)
2590                         continue;
2591                 if (!dev->req_config_methods)
2592                         continue;
2593                 if (dev->flags & P2P_DEV_PD_FOR_JOIN)
2594                         continue;
2595
2596                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Send "
2597                         "pending Provision Discovery Request to "
2598                         MACSTR " (config methods 0x%x)",
2599                         MAC2STR(dev->info.p2p_device_addr),
2600                         dev->req_config_methods);
2601                 p2p_send_prov_disc_req(p2p, dev, 0, 0);
2602                 return;
2603         }
2604 }
2605
2606
2607 static void p2p_prov_disc_cb(struct p2p_data *p2p, int success)
2608 {
2609         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2610                 "P2P: Provision Discovery Request TX callback: success=%d",
2611                 success);
2612
2613         /*
2614          * Postpone resetting the pending action state till after we actually
2615          * time out. This allows us to take some action like notifying any
2616          * interested parties about no response to the request.
2617          *
2618          * When the timer (below) goes off we check in IDLE, SEARCH, or
2619          * LISTEN_ONLY state, which are the only allowed states to issue a PD
2620          * requests in, if this was still pending and then raise notification.
2621          */
2622
2623         if (!success) {
2624                 p2p->pending_action_state = P2P_NO_PENDING_ACTION;
2625
2626                 if (p2p->state != P2P_IDLE)
2627                         p2p_continue_find(p2p);
2628                 else if (p2p->user_initiated_pd) {
2629                         p2p->pending_action_state = P2P_PENDING_PD;
2630                         p2p_set_timeout(p2p, 0, 300000);
2631                 }
2632                 return;
2633         }
2634
2635         /*
2636          * This postponing, of resetting pending_action_state, needs to be
2637          * done only for user initiated PD requests and not internal ones.
2638          */
2639         if (p2p->user_initiated_pd)
2640                 p2p->pending_action_state = P2P_PENDING_PD;
2641         else
2642                 p2p->pending_action_state = P2P_NO_PENDING_ACTION;
2643
2644         /* Wait for response from the peer */
2645         if (p2p->state == P2P_SEARCH)
2646                 p2p_set_state(p2p, P2P_PD_DURING_FIND);
2647         p2p_set_timeout(p2p, 0, 200000);
2648 }
2649
2650
2651 int p2p_scan_res_handler(struct p2p_data *p2p, const u8 *bssid, int freq,
2652                          int level, const u8 *ies, size_t ies_len)
2653 {
2654         p2p_add_device(p2p, bssid, freq, level, ies, ies_len, 1);
2655
2656         if (p2p->go_neg_peer && p2p->state == P2P_SEARCH &&
2657             os_memcmp(p2p->go_neg_peer->info.p2p_device_addr, bssid, ETH_ALEN)
2658             == 0) {
2659                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2660                         "P2P: Found GO Negotiation peer - try to start GO "
2661                         "negotiation");
2662                 p2p_connect_send(p2p, p2p->go_neg_peer);
2663                 return 1;
2664         }
2665
2666         return 0;
2667 }
2668
2669
2670 void p2p_scan_res_handled(struct p2p_data *p2p)
2671 {
2672         if (!p2p->p2p_scan_running) {
2673                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: p2p_scan was not "
2674                         "running, but scan results received");
2675         }
2676         p2p->p2p_scan_running = 0;
2677         eloop_cancel_timeout(p2p_scan_timeout, p2p, NULL);
2678
2679         if (p2p_run_after_scan(p2p))
2680                 return;
2681         if (p2p->state == P2P_SEARCH)
2682                 p2p_continue_find(p2p);
2683 }
2684
2685
2686 void p2p_scan_ie(struct p2p_data *p2p, struct wpabuf *ies, const u8 *dev_id)
2687 {
2688         u8 *len = p2p_buf_add_ie_hdr(ies);
2689         p2p_buf_add_capability(ies, p2p->dev_capab &
2690                                ~P2P_DEV_CAPAB_CLIENT_DISCOVERABILITY, 0);
2691         if (dev_id)
2692                 p2p_buf_add_device_id(ies, dev_id);
2693         if (p2p->cfg->reg_class && p2p->cfg->channel)
2694                 p2p_buf_add_listen_channel(ies, p2p->cfg->country,
2695                                            p2p->cfg->reg_class,
2696                                            p2p->cfg->channel);
2697         if (p2p->ext_listen_interval)
2698                 p2p_buf_add_ext_listen_timing(ies, p2p->ext_listen_period,
2699                                               p2p->ext_listen_interval);
2700         /* TODO: p2p_buf_add_operating_channel() if GO */
2701         p2p_buf_update_ie_hdr(ies, len);
2702 }
2703
2704
2705 size_t p2p_scan_ie_buf_len(struct p2p_data *p2p)
2706 {
2707         return 100;
2708 }
2709
2710
2711 int p2p_ie_text(struct wpabuf *p2p_ie, char *buf, char *end)
2712 {
2713         return p2p_attr_text(p2p_ie, buf, end);
2714 }
2715
2716
2717 static void p2p_go_neg_req_cb(struct p2p_data *p2p, int success)
2718 {
2719         struct p2p_device *dev = p2p->go_neg_peer;
2720
2721         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2722                 "P2P: GO Negotiation Request TX callback: success=%d",
2723                 success);
2724
2725         if (dev == NULL) {
2726                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2727                         "P2P: No pending GO Negotiation");
2728                 return;
2729         }
2730
2731         if (success) {
2732                 if (dev->flags & P2P_DEV_USER_REJECTED) {
2733                         p2p_set_state(p2p, P2P_IDLE);
2734                         return;
2735                 }
2736         } else if (dev->go_neg_req_sent) {
2737                 /* Cancel the increment from p2p_connect_send() on failure */
2738                 dev->go_neg_req_sent--;
2739         }
2740
2741         if (!success &&
2742             (dev->info.dev_capab & P2P_DEV_CAPAB_CLIENT_DISCOVERABILITY) &&
2743             !is_zero_ether_addr(dev->member_in_go_dev)) {
2744                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2745                         "P2P: Peer " MACSTR " did not acknowledge request - "
2746                         "try to use device discoverability through its GO",
2747                         MAC2STR(dev->info.p2p_device_addr));
2748                 p2p->cfg->send_action_done(p2p->cfg->cb_ctx);
2749                 p2p_send_dev_disc_req(p2p, dev);
2750                 return;
2751         }
2752
2753         /*
2754          * Use P2P find, if needed, to find the other device from its listen
2755          * channel.
2756          */
2757         p2p_set_state(p2p, P2P_CONNECT);
2758         p2p_set_timeout(p2p, 0, 100000);
2759 }
2760
2761
2762 static void p2p_go_neg_resp_cb(struct p2p_data *p2p, int success)
2763 {
2764         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2765                 "P2P: GO Negotiation Response TX callback: success=%d",
2766                 success);
2767         if (!p2p->go_neg_peer && p2p->state == P2P_PROVISIONING) {
2768                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2769                         "P2P: Ignore TX callback event - GO Negotiation is "
2770                         "not running anymore");
2771                 return;
2772         }
2773         p2p_set_state(p2p, P2P_CONNECT);
2774         p2p_set_timeout(p2p, 0, 100000);
2775 }
2776
2777
2778 static void p2p_go_neg_resp_failure_cb(struct p2p_data *p2p, int success)
2779 {
2780         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2781                 "P2P: GO Negotiation Response (failure) TX callback: "
2782                 "success=%d", success);
2783         if (p2p->go_neg_peer && p2p->go_neg_peer->status != P2P_SC_SUCCESS) {
2784                 p2p_go_neg_failed(p2p, p2p->go_neg_peer,
2785                                   p2p->go_neg_peer->status);
2786         }
2787 }
2788
2789
2790 static void p2p_go_neg_conf_cb(struct p2p_data *p2p,
2791                                enum p2p_send_action_result result)
2792 {
2793         struct p2p_device *dev;
2794
2795         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2796                 "P2P: GO Negotiation Confirm TX callback: result=%d",
2797                 result);
2798         p2p->cfg->send_action_done(p2p->cfg->cb_ctx);
2799         if (result == P2P_SEND_ACTION_FAILED) {
2800                 p2p_go_neg_failed(p2p, p2p->go_neg_peer, -1);
2801                 return;
2802         }
2803         if (result == P2P_SEND_ACTION_NO_ACK) {
2804                 /*
2805                  * It looks like the TX status for GO Negotiation Confirm is
2806                  * often showing failure even when the peer has actually
2807                  * received the frame. Since the peer may change channels
2808                  * immediately after having received the frame, we may not see
2809                  * an Ack for retries, so just dropping a single frame may
2810                  * trigger this. To allow the group formation to succeed if the
2811                  * peer did indeed receive the frame, continue regardless of
2812                  * the TX status.
2813                  */
2814                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2815                         "P2P: Assume GO Negotiation Confirm TX was actually "
2816                         "received by the peer even though Ack was not "
2817                         "reported");
2818         }
2819
2820         dev = p2p->go_neg_peer;
2821         if (dev == NULL)
2822                 return;
2823
2824         p2p_go_complete(p2p, dev);
2825 }
2826
2827
2828 void p2p_send_action_cb(struct p2p_data *p2p, unsigned int freq, const u8 *dst,
2829                         const u8 *src, const u8 *bssid,
2830                         enum p2p_send_action_result result)
2831 {
2832         enum p2p_pending_action_state state;
2833         int success;
2834
2835         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2836                 "P2P: Action frame TX callback (state=%d freq=%u dst=" MACSTR
2837                 " src=" MACSTR " bssid=" MACSTR " result=%d",
2838                 p2p->pending_action_state, freq, MAC2STR(dst), MAC2STR(src),
2839                 MAC2STR(bssid), result);
2840         success = result == P2P_SEND_ACTION_SUCCESS;
2841         state = p2p->pending_action_state;
2842         p2p->pending_action_state = P2P_NO_PENDING_ACTION;
2843         switch (state) {
2844         case P2P_NO_PENDING_ACTION:
2845                 break;
2846         case P2P_PENDING_GO_NEG_REQUEST:
2847                 p2p_go_neg_req_cb(p2p, success);
2848                 break;
2849         case P2P_PENDING_GO_NEG_RESPONSE:
2850                 p2p_go_neg_resp_cb(p2p, success);
2851                 break;
2852         case P2P_PENDING_GO_NEG_RESPONSE_FAILURE:
2853                 p2p_go_neg_resp_failure_cb(p2p, success);
2854                 break;
2855         case P2P_PENDING_GO_NEG_CONFIRM:
2856                 p2p_go_neg_conf_cb(p2p, result);
2857                 break;
2858         case P2P_PENDING_SD:
2859                 p2p_sd_cb(p2p, success);
2860                 break;
2861         case P2P_PENDING_PD:
2862                 p2p_prov_disc_cb(p2p, success);
2863                 break;
2864         case P2P_PENDING_INVITATION_REQUEST:
2865                 p2p_invitation_req_cb(p2p, success);
2866                 break;
2867         case P2P_PENDING_INVITATION_RESPONSE:
2868                 p2p_invitation_resp_cb(p2p, success);
2869                 break;
2870         case P2P_PENDING_DEV_DISC_REQUEST:
2871                 p2p_dev_disc_req_cb(p2p, success);
2872                 break;
2873         case P2P_PENDING_DEV_DISC_RESPONSE:
2874                 p2p_dev_disc_resp_cb(p2p, success);
2875                 break;
2876         case P2P_PENDING_GO_DISC_REQ:
2877                 p2p_go_disc_req_cb(p2p, success);
2878                 break;
2879         }
2880 }
2881
2882
2883 void p2p_listen_cb(struct p2p_data *p2p, unsigned int freq,
2884                    unsigned int duration)
2885 {
2886         if (freq == p2p->pending_client_disc_freq) {
2887                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2888                         "P2P: Client discoverability remain-awake completed");
2889                 p2p->pending_client_disc_freq = 0;
2890                 return;
2891         }
2892
2893         if (freq != p2p->pending_listen_freq) {
2894                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2895                         "P2P: Unexpected listen callback for freq=%u "
2896                         "duration=%u (pending_listen_freq=%u)",
2897                         freq, duration, p2p->pending_listen_freq);
2898                 return;
2899         }
2900
2901         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2902                 "P2P: Starting Listen timeout(%u,%u) on freq=%u based on "
2903                 "callback",
2904                 p2p->pending_listen_sec, p2p->pending_listen_usec,
2905                 p2p->pending_listen_freq);
2906         p2p->in_listen = 1;
2907         p2p->drv_in_listen = freq;
2908         if (p2p->pending_listen_sec || p2p->pending_listen_usec) {
2909                 /*
2910                  * Add 20 msec extra wait to avoid race condition with driver
2911                  * remain-on-channel end event, i.e., give driver more time to
2912                  * complete the operation before our timeout expires.
2913                  */
2914                 p2p_set_timeout(p2p, p2p->pending_listen_sec,
2915                                 p2p->pending_listen_usec + 20000);
2916         }
2917
2918         p2p->pending_listen_freq = 0;
2919 }
2920
2921
2922 int p2p_listen_end(struct p2p_data *p2p, unsigned int freq)
2923 {
2924         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Driver ended Listen "
2925                 "state (freq=%u)", freq);
2926         p2p->drv_in_listen = 0;
2927         if (p2p->in_listen)
2928                 return 0; /* Internal timeout will trigger the next step */
2929
2930         if (p2p->state == P2P_CONNECT_LISTEN && p2p->go_neg_peer) {
2931                 if (p2p->go_neg_peer->connect_reqs >= 120) {
2932                         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
2933                                 "P2P: Timeout on sending GO Negotiation "
2934                                 "Request without getting response");
2935                         p2p_go_neg_failed(p2p, p2p->go_neg_peer, -1);
2936                         return 0;
2937                 }
2938
2939                 p2p_set_state(p2p, P2P_CONNECT);
2940                 p2p_connect_send(p2p, p2p->go_neg_peer);
2941                 return 1;
2942         } else if (p2p->state == P2P_SEARCH) {
2943                 if (p2p->p2p_scan_running) {
2944                          /*
2945                           * Search is already in progress. This can happen if
2946                           * an Action frame RX is reported immediately after
2947                           * the end of a remain-on-channel operation and the
2948                           * response frame to that is sent using an offchannel
2949                           * operation while in p2p_find. Avoid an attempt to
2950                           * restart a scan here.
2951                           */
2952                         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: p2p_scan "
2953                                 "already in progress - do not try to start a "
2954                                 "new one");
2955                         return 1;
2956                 }
2957                 if (p2p->pending_listen_freq) {
2958                         /*
2959                          * Better wait a bit if the driver is unable to start
2960                          * offchannel operation for some reason. p2p_search()
2961                          * will be started from internal timeout.
2962                          */
2963                         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Listen "
2964                                 "operation did not seem to start - delay "
2965                                 "search phase to avoid busy loop");
2966                         p2p_set_timeout(p2p, 0, 100000);
2967                         return 1;
2968                 }
2969                 p2p_search(p2p);
2970                 return 1;
2971         }
2972
2973         return 0;
2974 }
2975
2976
2977 static void p2p_timeout_connect(struct p2p_data *p2p)
2978 {
2979         p2p->cfg->send_action_done(p2p->cfg->cb_ctx);
2980         if (p2p->go_neg_peer &&
2981             (p2p->go_neg_peer->flags & P2P_DEV_WAIT_GO_NEG_CONFIRM)) {
2982                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Wait for GO "
2983                         "Negotiation Confirm timed out - assume GO "
2984                         "Negotiation failed");
2985                 p2p_go_neg_failed(p2p, p2p->go_neg_peer, -1);
2986                 return;
2987         }
2988         p2p_set_state(p2p, P2P_CONNECT_LISTEN);
2989         p2p_listen_in_find(p2p);
2990 }
2991
2992
2993 static void p2p_timeout_connect_listen(struct p2p_data *p2p)
2994 {
2995         if (p2p->go_neg_peer) {
2996                 if (p2p->drv_in_listen) {
2997                         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Driver is "
2998                                 "still in Listen state; wait for it to "
2999                                 "complete");
3000                         return;
3001                 }
3002
3003                 if (p2p->go_neg_peer->connect_reqs >= 120) {
3004                         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
3005                                 "P2P: Timeout on sending GO Negotiation "
3006                                 "Request without getting response");
3007                         p2p_go_neg_failed(p2p, p2p->go_neg_peer, -1);
3008                         return;
3009                 }
3010
3011                 p2p_set_state(p2p, P2P_CONNECT);
3012                 p2p_connect_send(p2p, p2p->go_neg_peer);
3013         } else
3014                 p2p_set_state(p2p, P2P_IDLE);
3015 }
3016
3017
3018 static void p2p_timeout_wait_peer_connect(struct p2p_data *p2p)
3019 {
3020         /*
3021          * TODO: could remain constantly in Listen state for some time if there
3022          * are no other concurrent uses for the radio. For now, go to listen
3023          * state once per second to give other uses a chance to use the radio.
3024          */
3025         p2p_set_state(p2p, P2P_WAIT_PEER_IDLE);
3026         p2p_set_timeout(p2p, 0, 500000);
3027 }
3028
3029
3030 static void p2p_timeout_wait_peer_idle(struct p2p_data *p2p)
3031 {
3032         struct p2p_device *dev = p2p->go_neg_peer;
3033
3034         if (dev == NULL) {
3035                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
3036                         "P2P: Unknown GO Neg peer - stop GO Neg wait");
3037                 return;
3038         }
3039
3040         dev->wait_count++;
3041         if (dev->wait_count >= 120) {
3042                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
3043                         "P2P: Timeout on waiting peer to become ready for GO "
3044                         "Negotiation");
3045                 p2p_go_neg_failed(p2p, dev, -1);
3046                 return;
3047         }
3048
3049         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
3050                 "P2P: Go to Listen state while waiting for the peer to become "
3051                 "ready for GO Negotiation");
3052         p2p_set_state(p2p, P2P_WAIT_PEER_CONNECT);
3053         p2p_listen_in_find(p2p);
3054 }
3055
3056
3057 static void p2p_timeout_sd_during_find(struct p2p_data *p2p)
3058 {
3059         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
3060                 "P2P: Service Discovery Query timeout");
3061         if (p2p->sd_peer) {
3062                 p2p->cfg->send_action_done(p2p->cfg->cb_ctx);
3063                 p2p->sd_peer->flags &= ~P2P_DEV_SD_SCHEDULE;
3064                 p2p->sd_peer = NULL;
3065         }
3066         p2p_continue_find(p2p);
3067 }
3068
3069
3070 static void p2p_timeout_prov_disc_during_find(struct p2p_data *p2p)
3071 {
3072         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
3073                 "P2P: Provision Discovery Request timeout");
3074         p2p->cfg->send_action_done(p2p->cfg->cb_ctx);
3075         p2p_continue_find(p2p);
3076 }
3077
3078
3079 static void p2p_timeout_prov_disc_req(struct p2p_data *p2p)
3080 {
3081         p2p->pending_action_state = P2P_NO_PENDING_ACTION;
3082
3083         /*
3084          * For user initiated PD requests that we have not gotten any responses
3085          * for while in IDLE state, we retry them a couple of times before
3086          * giving up.
3087          */
3088         if (!p2p->user_initiated_pd)
3089                 return;
3090
3091         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
3092                 "P2P: User initiated Provision Discovery Request timeout");
3093
3094         if (p2p->pd_retries) {
3095                 p2p->pd_retries--;
3096                 p2p_retry_pd(p2p);
3097         } else {
3098                 if (p2p->cfg->prov_disc_fail)
3099                         p2p->cfg->prov_disc_fail(p2p->cfg->cb_ctx,
3100                                                  p2p->pending_pd_devaddr,
3101                                                  P2P_PROV_DISC_TIMEOUT);
3102                 p2p_reset_pending_pd(p2p);
3103         }
3104 }
3105
3106
3107 static void p2p_timeout_invite(struct p2p_data *p2p)
3108 {
3109         p2p->cfg->send_action_done(p2p->cfg->cb_ctx);
3110         p2p_set_state(p2p, P2P_INVITE_LISTEN);
3111         if (p2p->inv_role == P2P_INVITE_ROLE_ACTIVE_GO) {
3112                 /*
3113                  * Better remain on operating channel instead of listen channel
3114                  * when running a group.
3115                  */
3116                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Inviting in "
3117                         "active GO role - wait on operating channel");
3118                 p2p_set_timeout(p2p, 0, 100000);
3119                 return;
3120         }
3121         p2p_listen_in_find(p2p);
3122 }
3123
3124
3125 static void p2p_timeout_invite_listen(struct p2p_data *p2p)
3126 {
3127         if (p2p->invite_peer && p2p->invite_peer->invitation_reqs < 100) {
3128                 p2p_set_state(p2p, P2P_INVITE);
3129                 p2p_invite_send(p2p, p2p->invite_peer,
3130                                 p2p->invite_go_dev_addr);
3131         } else {
3132                 if (p2p->invite_peer) {
3133                         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
3134                                 "P2P: Invitation Request retry limit reached");
3135                         if (p2p->cfg->invitation_result)
3136                                 p2p->cfg->invitation_result(
3137                                         p2p->cfg->cb_ctx, -1, NULL);
3138                 }
3139                 p2p_set_state(p2p, P2P_IDLE);
3140         }
3141 }
3142
3143
3144 static void p2p_state_timeout(void *eloop_ctx, void *timeout_ctx)
3145 {
3146         struct p2p_data *p2p = eloop_ctx;
3147
3148         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Timeout (state=%s)",
3149                 p2p_state_txt(p2p->state));
3150
3151         p2p->in_listen = 0;
3152
3153         switch (p2p->state) {
3154         case P2P_IDLE:
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                 break;
3159         case P2P_SEARCH:
3160                 /* Check if we timed out waiting for PD req */
3161                 if (p2p->pending_action_state == P2P_PENDING_PD)
3162                         p2p_timeout_prov_disc_req(p2p);
3163                 p2p_search(p2p);
3164                 break;
3165         case P2P_CONNECT:
3166                 p2p_timeout_connect(p2p);
3167                 break;
3168         case P2P_CONNECT_LISTEN:
3169                 p2p_timeout_connect_listen(p2p);
3170                 break;
3171         case P2P_GO_NEG:
3172                 break;
3173         case P2P_LISTEN_ONLY:
3174                 /* Check if we timed out waiting for PD req */
3175                 if (p2p->pending_action_state == P2P_PENDING_PD)
3176                         p2p_timeout_prov_disc_req(p2p);
3177
3178                 if (p2p->ext_listen_only) {
3179                         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
3180                                 "P2P: Extended Listen Timing - Listen State "
3181                                 "completed");
3182                         p2p->ext_listen_only = 0;
3183                         p2p_set_state(p2p, P2P_IDLE);
3184                 }
3185                 break;
3186         case P2P_WAIT_PEER_CONNECT:
3187                 p2p_timeout_wait_peer_connect(p2p);
3188                 break;
3189         case P2P_WAIT_PEER_IDLE:
3190                 p2p_timeout_wait_peer_idle(p2p);
3191                 break;
3192         case P2P_SD_DURING_FIND:
3193                 p2p_timeout_sd_during_find(p2p);
3194                 break;
3195         case P2P_PROVISIONING:
3196                 break;
3197         case P2P_PD_DURING_FIND:
3198                 p2p_timeout_prov_disc_during_find(p2p);
3199                 break;
3200         case P2P_INVITE:
3201                 p2p_timeout_invite(p2p);
3202                 break;
3203         case P2P_INVITE_LISTEN:
3204                 p2p_timeout_invite_listen(p2p);
3205                 break;
3206         case P2P_SEARCH_WHEN_READY:
3207                 break;
3208         }
3209 }
3210
3211
3212 int p2p_reject(struct p2p_data *p2p, const u8 *peer_addr)
3213 {
3214         struct p2p_device *dev;
3215
3216         dev = p2p_get_device(p2p, peer_addr);
3217         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Local request to reject "
3218                 "connection attempts by peer " MACSTR, MAC2STR(peer_addr));
3219         if (dev == NULL) {
3220                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Peer " MACSTR
3221                         " unknown", MAC2STR(peer_addr));
3222                 return -1;
3223         }
3224         dev->status = P2P_SC_FAIL_REJECTED_BY_USER;
3225         dev->flags |= P2P_DEV_USER_REJECTED;
3226         return 0;
3227 }
3228
3229
3230 const char * p2p_wps_method_text(enum p2p_wps_method method)
3231 {
3232         switch (method) {
3233         case WPS_NOT_READY:
3234                 return "not-ready";
3235         case WPS_PIN_DISPLAY:
3236                 return "Display";
3237         case WPS_PIN_KEYPAD:
3238                 return "Keypad";
3239         case WPS_PBC:
3240                 return "PBC";
3241         }
3242
3243         return "??";
3244 }
3245
3246
3247 static const char * p2p_go_state_text(enum p2p_go_state go_state)
3248 {
3249         switch (go_state) {
3250         case UNKNOWN_GO:
3251                 return "unknown";
3252         case LOCAL_GO:
3253                 return "local";
3254         case  REMOTE_GO:
3255                 return "remote";
3256         }
3257
3258         return "??";
3259 }
3260
3261
3262 const struct p2p_peer_info * p2p_get_peer_info(struct p2p_data *p2p,
3263                                                const u8 *addr, int next)
3264 {
3265         struct p2p_device *dev;
3266
3267         if (addr)
3268                 dev = p2p_get_device(p2p, addr);
3269         else
3270                 dev = dl_list_first(&p2p->devices, struct p2p_device, list);
3271
3272         if (dev && next) {
3273                 dev = dl_list_first(&dev->list, struct p2p_device, list);
3274                 if (&dev->list == &p2p->devices)
3275                         dev = NULL;
3276         }
3277
3278         if (dev == NULL)
3279                 return NULL;
3280
3281         return &dev->info;
3282 }
3283
3284
3285 int p2p_get_peer_info_txt(const struct p2p_peer_info *info,
3286                           char *buf, size_t buflen)
3287 {
3288         struct p2p_device *dev;
3289         int res;
3290         char *pos, *end;
3291         struct os_time now;
3292
3293         if (info == NULL)
3294                 return -1;
3295
3296         dev = (struct p2p_device *) (((u8 *) info) -
3297                                      offsetof(struct p2p_device, info));
3298
3299         pos = buf;
3300         end = buf + buflen;
3301
3302         os_get_time(&now);
3303         res = os_snprintf(pos, end - pos,
3304                           "age=%d\n"
3305                           "listen_freq=%d\n"
3306                           "wps_method=%s\n"
3307                           "interface_addr=" MACSTR "\n"
3308                           "member_in_go_dev=" MACSTR "\n"
3309                           "member_in_go_iface=" MACSTR "\n"
3310                           "go_neg_req_sent=%d\n"
3311                           "go_state=%s\n"
3312                           "dialog_token=%u\n"
3313                           "intended_addr=" MACSTR "\n"
3314                           "country=%c%c\n"
3315                           "oper_freq=%d\n"
3316                           "req_config_methods=0x%x\n"
3317                           "flags=%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n"
3318                           "status=%d\n"
3319                           "wait_count=%u\n"
3320                           "invitation_reqs=%u\n",
3321                           (int) (now.sec - dev->last_seen.sec),
3322                           dev->listen_freq,
3323                           p2p_wps_method_text(dev->wps_method),
3324                           MAC2STR(dev->interface_addr),
3325                           MAC2STR(dev->member_in_go_dev),
3326                           MAC2STR(dev->member_in_go_iface),
3327                           dev->go_neg_req_sent,
3328                           p2p_go_state_text(dev->go_state),
3329                           dev->dialog_token,
3330                           MAC2STR(dev->intended_addr),
3331                           dev->country[0] ? dev->country[0] : '_',
3332                           dev->country[1] ? dev->country[1] : '_',
3333                           dev->oper_freq,
3334                           dev->req_config_methods,
3335                           dev->flags & P2P_DEV_PROBE_REQ_ONLY ?
3336                           "[PROBE_REQ_ONLY]" : "",
3337                           dev->flags & P2P_DEV_REPORTED ? "[REPORTED]" : "",
3338                           dev->flags & P2P_DEV_NOT_YET_READY ?
3339                           "[NOT_YET_READY]" : "",
3340                           dev->flags & P2P_DEV_SD_INFO ? "[SD_INFO]" : "",
3341                           dev->flags & P2P_DEV_SD_SCHEDULE ? "[SD_SCHEDULE]" :
3342                           "",
3343                           dev->flags & P2P_DEV_PD_PEER_DISPLAY ?
3344                           "[PD_PEER_DISPLAY]" : "",
3345                           dev->flags & P2P_DEV_PD_PEER_KEYPAD ?
3346                           "[PD_PEER_KEYPAD]" : "",
3347                           dev->flags & P2P_DEV_USER_REJECTED ?
3348                           "[USER_REJECTED]" : "",
3349                           dev->flags & P2P_DEV_PEER_WAITING_RESPONSE ?
3350                           "[PEER_WAITING_RESPONSE]" : "",
3351                           dev->flags & P2P_DEV_PREFER_PERSISTENT_GROUP ?
3352                           "[PREFER_PERSISTENT_GROUP]" : "",
3353                           dev->flags & P2P_DEV_WAIT_GO_NEG_RESPONSE ?
3354                           "[WAIT_GO_NEG_RESPONSE]" : "",
3355                           dev->flags & P2P_DEV_WAIT_GO_NEG_CONFIRM ?
3356                           "[WAIT_GO_NEG_CONFIRM]" : "",
3357                           dev->flags & P2P_DEV_GROUP_CLIENT_ONLY ?
3358                           "[GROUP_CLIENT_ONLY]" : "",
3359                           dev->flags & P2P_DEV_FORCE_FREQ ?
3360                           "[FORCE_FREQ]" : "",
3361                           dev->flags & P2P_DEV_PD_FOR_JOIN ?
3362                           "[PD_FOR_JOIN]" : "",
3363                           dev->status,
3364                           dev->wait_count,
3365                           dev->invitation_reqs);
3366         if (res < 0 || res >= end - pos)
3367                 return pos - buf;
3368         pos += res;
3369
3370         if (dev->ext_listen_period) {
3371                 res = os_snprintf(pos, end - pos,
3372                                   "ext_listen_period=%u\n"
3373                                   "ext_listen_interval=%u\n",
3374                                   dev->ext_listen_period,
3375                                   dev->ext_listen_interval);
3376                 if (res < 0 || res >= end - pos)
3377                         return pos - buf;
3378                 pos += res;
3379         }
3380
3381         if (dev->oper_ssid_len) {
3382                 res = os_snprintf(pos, end - pos,
3383                                   "oper_ssid=%s\n",
3384                                   wpa_ssid_txt(dev->oper_ssid,
3385                                                dev->oper_ssid_len));
3386                 if (res < 0 || res >= end - pos)
3387                         return pos - buf;
3388                 pos += res;
3389         }
3390
3391         return pos - buf;
3392 }
3393
3394
3395 int p2p_peer_known(struct p2p_data *p2p, const u8 *addr)
3396 {
3397         return p2p_get_device(p2p, addr) != NULL;
3398 }
3399
3400
3401 void p2p_set_client_discoverability(struct p2p_data *p2p, int enabled)
3402 {
3403         if (enabled) {
3404                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Client "
3405                         "discoverability enabled");
3406                 p2p->dev_capab |= P2P_DEV_CAPAB_CLIENT_DISCOVERABILITY;
3407         } else {
3408                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Client "
3409                         "discoverability disabled");
3410                 p2p->dev_capab &= ~P2P_DEV_CAPAB_CLIENT_DISCOVERABILITY;
3411         }
3412 }
3413
3414
3415 static struct wpabuf * p2p_build_presence_req(u32 duration1, u32 interval1,
3416                                               u32 duration2, u32 interval2)
3417 {
3418         struct wpabuf *req;
3419         struct p2p_noa_desc desc1, desc2, *ptr1 = NULL, *ptr2 = NULL;
3420         u8 *len;
3421
3422         req = wpabuf_alloc(100);
3423         if (req == NULL)
3424                 return NULL;
3425
3426         if (duration1 || interval1) {
3427                 os_memset(&desc1, 0, sizeof(desc1));
3428                 desc1.count_type = 1;
3429                 desc1.duration = duration1;
3430                 desc1.interval = interval1;
3431                 ptr1 = &desc1;
3432
3433                 if (duration2 || interval2) {
3434                         os_memset(&desc2, 0, sizeof(desc2));
3435                         desc2.count_type = 2;
3436                         desc2.duration = duration2;
3437                         desc2.interval = interval2;
3438                         ptr2 = &desc2;
3439                 }
3440         }
3441
3442         p2p_buf_add_action_hdr(req, P2P_PRESENCE_REQ, 1);
3443         len = p2p_buf_add_ie_hdr(req);
3444         p2p_buf_add_noa(req, 0, 0, 0, ptr1, ptr2);
3445         p2p_buf_update_ie_hdr(req, len);
3446
3447         return req;
3448 }
3449
3450
3451 int p2p_presence_req(struct p2p_data *p2p, const u8 *go_interface_addr,
3452                      const u8 *own_interface_addr, unsigned int freq,
3453                      u32 duration1, u32 interval1, u32 duration2,
3454                      u32 interval2)
3455 {
3456         struct wpabuf *req;
3457
3458         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Send Presence Request to "
3459                 "GO " MACSTR " (own interface " MACSTR ") freq=%u dur1=%u "
3460                 "int1=%u dur2=%u int2=%u",
3461                 MAC2STR(go_interface_addr), MAC2STR(own_interface_addr),
3462                 freq, duration1, interval1, duration2, interval2);
3463
3464         req = p2p_build_presence_req(duration1, interval1, duration2,
3465                                      interval2);
3466         if (req == NULL)
3467                 return -1;
3468
3469         p2p->pending_action_state = P2P_NO_PENDING_ACTION;
3470         if (p2p_send_action(p2p, freq, go_interface_addr, own_interface_addr,
3471                             go_interface_addr,
3472                             wpabuf_head(req), wpabuf_len(req), 200) < 0) {
3473                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
3474                         "P2P: Failed to send Action frame");
3475         }
3476         wpabuf_free(req);
3477
3478         return 0;
3479 }
3480
3481
3482 static struct wpabuf * p2p_build_presence_resp(u8 status, const u8 *noa,
3483                                                size_t noa_len, u8 dialog_token)
3484 {
3485         struct wpabuf *resp;
3486         u8 *len;
3487
3488         resp = wpabuf_alloc(100 + noa_len);
3489         if (resp == NULL)
3490                 return NULL;
3491
3492         p2p_buf_add_action_hdr(resp, P2P_PRESENCE_RESP, dialog_token);
3493         len = p2p_buf_add_ie_hdr(resp);
3494         p2p_buf_add_status(resp, status);
3495         if (noa) {
3496                 wpabuf_put_u8(resp, P2P_ATTR_NOTICE_OF_ABSENCE);
3497                 wpabuf_put_le16(resp, noa_len);
3498                 wpabuf_put_data(resp, noa, noa_len);
3499         } else
3500                 p2p_buf_add_noa(resp, 0, 0, 0, NULL, NULL);
3501         p2p_buf_update_ie_hdr(resp, len);
3502
3503         return resp;
3504 }
3505
3506
3507 static void p2p_process_presence_req(struct p2p_data *p2p, const u8 *da,
3508                                      const u8 *sa, const u8 *data, size_t len,
3509                                      int rx_freq)
3510 {
3511         struct p2p_message msg;
3512         u8 status;
3513         struct wpabuf *resp;
3514         size_t g;
3515         struct p2p_group *group = NULL;
3516         int parsed = 0;
3517         u8 noa[50];
3518         int noa_len;
3519
3520         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
3521                 "P2P: Received P2P Action - P2P Presence Request");
3522
3523         for (g = 0; g < p2p->num_groups; g++) {
3524                 if (os_memcmp(da, p2p_group_get_interface_addr(p2p->groups[g]),
3525                               ETH_ALEN) == 0) {
3526                         group = p2p->groups[g];
3527                         break;
3528                 }
3529         }
3530         if (group == NULL) {
3531                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
3532                         "P2P: Ignore P2P Presence Request for unknown group "
3533                         MACSTR, MAC2STR(da));
3534                 return;
3535         }
3536
3537         if (p2p_parse(data, len, &msg) < 0) {
3538                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
3539                         "P2P: Failed to parse P2P Presence Request");
3540                 status = P2P_SC_FAIL_INVALID_PARAMS;
3541                 goto fail;
3542         }
3543         parsed = 1;
3544
3545         if (msg.noa == NULL) {
3546                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
3547                         "P2P: No NoA attribute in P2P Presence Request");
3548                 status = P2P_SC_FAIL_INVALID_PARAMS;
3549                 goto fail;
3550         }
3551
3552         status = p2p_group_presence_req(group, sa, msg.noa, msg.noa_len);
3553
3554 fail:
3555         if (p2p->cfg->get_noa)
3556                 noa_len = p2p->cfg->get_noa(p2p->cfg->cb_ctx, da, noa,
3557                                             sizeof(noa));
3558         else
3559                 noa_len = -1;
3560         resp = p2p_build_presence_resp(status, noa_len > 0 ? noa : NULL,
3561                                        noa_len > 0 ? noa_len : 0,
3562                                        msg.dialog_token);
3563         if (parsed)
3564                 p2p_parse_free(&msg);
3565         if (resp == NULL)
3566                 return;
3567
3568         p2p->pending_action_state = P2P_NO_PENDING_ACTION;
3569         if (p2p_send_action(p2p, rx_freq, sa, da, da,
3570                             wpabuf_head(resp), wpabuf_len(resp), 200) < 0) {
3571                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
3572                         "P2P: Failed to send Action frame");
3573         }
3574         wpabuf_free(resp);
3575 }
3576
3577
3578 static void p2p_process_presence_resp(struct p2p_data *p2p, const u8 *da,
3579                                       const u8 *sa, const u8 *data, size_t len)
3580 {
3581         struct p2p_message msg;
3582
3583         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
3584                 "P2P: Received P2P Action - P2P Presence Response");
3585
3586         if (p2p_parse(data, len, &msg) < 0) {
3587                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
3588                         "P2P: Failed to parse P2P Presence Response");
3589                 return;
3590         }
3591
3592         if (msg.status == NULL || msg.noa == NULL) {
3593                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
3594                         "P2P: No Status or NoA attribute in P2P Presence "
3595                         "Response");
3596                 p2p_parse_free(&msg);
3597                 return;
3598         }
3599
3600         if (*msg.status) {
3601                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
3602                         "P2P: P2P Presence Request was rejected: status %u",
3603                         *msg.status);
3604                 p2p_parse_free(&msg);
3605                 return;
3606         }
3607
3608         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
3609                 "P2P: P2P Presence Request was accepted");
3610         wpa_hexdump(MSG_DEBUG, "P2P: P2P Presence Response - NoA",
3611                     msg.noa, msg.noa_len);
3612         /* TODO: process NoA */
3613         p2p_parse_free(&msg);
3614 }
3615
3616
3617 static void p2p_ext_listen_timeout(void *eloop_ctx, void *timeout_ctx)
3618 {
3619         struct p2p_data *p2p = eloop_ctx;
3620
3621         if (p2p->ext_listen_interval) {
3622                 /* Schedule next extended listen timeout */
3623                 eloop_register_timeout(p2p->ext_listen_interval_sec,
3624                                        p2p->ext_listen_interval_usec,
3625                                        p2p_ext_listen_timeout, p2p, NULL);
3626         }
3627
3628         if (p2p->state == P2P_LISTEN_ONLY && p2p->ext_listen_only) {
3629                 /*
3630                  * This should not really happen, but it looks like the Listen
3631                  * command may fail is something else (e.g., a scan) was
3632                  * running at an inconvenient time. As a workaround, allow new
3633                  * Extended Listen operation to be started.
3634                  */
3635                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Previous "
3636                         "Extended Listen operation had not been completed - "
3637                         "try again");
3638                 p2p->ext_listen_only = 0;
3639                 p2p_set_state(p2p, P2P_IDLE);
3640         }
3641
3642         if (p2p->state != P2P_IDLE) {
3643                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Skip Extended "
3644                         "Listen timeout in active state (%s)",
3645                         p2p_state_txt(p2p->state));
3646                 return;
3647         }
3648
3649         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Extended Listen timeout");
3650         p2p->ext_listen_only = 1;
3651         if (p2p_listen(p2p, p2p->ext_listen_period) < 0) {
3652                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Failed to start "
3653                         "Listen state for Extended Listen Timing");
3654                 p2p->ext_listen_only = 0;
3655         }
3656 }
3657
3658
3659 int p2p_ext_listen(struct p2p_data *p2p, unsigned int period,
3660                    unsigned int interval)
3661 {
3662         if (period > 65535 || interval > 65535 || period > interval ||
3663             (period == 0 && interval > 0) || (period > 0 && interval == 0)) {
3664                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
3665                         "P2P: Invalid Extended Listen Timing request: "
3666                         "period=%u interval=%u", period, interval);
3667                 return -1;
3668         }
3669
3670         eloop_cancel_timeout(p2p_ext_listen_timeout, p2p, NULL);
3671
3672         if (interval == 0) {
3673                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
3674                         "P2P: Disabling Extended Listen Timing");
3675                 p2p->ext_listen_period = 0;
3676                 p2p->ext_listen_interval = 0;
3677                 return 0;
3678         }
3679
3680         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG,
3681                 "P2P: Enabling Extended Listen Timing: period %u msec, "
3682                 "interval %u msec", period, interval);
3683         p2p->ext_listen_period = period;
3684         p2p->ext_listen_interval = interval;
3685         p2p->ext_listen_interval_sec = interval / 1000;
3686         p2p->ext_listen_interval_usec = (interval % 1000) * 1000;
3687
3688         eloop_register_timeout(p2p->ext_listen_interval_sec,
3689                                p2p->ext_listen_interval_usec,
3690                                p2p_ext_listen_timeout, p2p, NULL);
3691
3692         return 0;
3693 }
3694
3695
3696 void p2p_deauth_notif(struct p2p_data *p2p, const u8 *bssid, u16 reason_code,
3697                       const u8 *ie, size_t ie_len)
3698 {
3699         struct p2p_message msg;
3700
3701         if (bssid == NULL || ie == NULL)
3702                 return;
3703
3704         os_memset(&msg, 0, sizeof(msg));
3705         if (p2p_parse_ies(ie, ie_len, &msg))
3706                 return;
3707         if (msg.minor_reason_code == NULL)
3708                 return;
3709
3710         wpa_msg(p2p->cfg->msg_ctx, MSG_INFO,
3711                 "P2P: Deauthentication notification BSSID " MACSTR
3712                 " reason_code=%u minor_reason_code=%u",
3713                 MAC2STR(bssid), reason_code, *msg.minor_reason_code);
3714
3715         p2p_parse_free(&msg);
3716 }
3717
3718
3719 void p2p_disassoc_notif(struct p2p_data *p2p, const u8 *bssid, u16 reason_code,
3720                         const u8 *ie, size_t ie_len)
3721 {
3722         struct p2p_message msg;
3723
3724         if (bssid == NULL || ie == NULL)
3725                 return;
3726
3727         os_memset(&msg, 0, sizeof(msg));
3728         if (p2p_parse_ies(ie, ie_len, &msg))
3729                 return;
3730         if (msg.minor_reason_code == NULL)
3731                 return;
3732
3733         wpa_msg(p2p->cfg->msg_ctx, MSG_INFO,
3734                 "P2P: Disassociation notification BSSID " MACSTR
3735                 " reason_code=%u minor_reason_code=%u",
3736                 MAC2STR(bssid), reason_code, *msg.minor_reason_code);
3737
3738         p2p_parse_free(&msg);
3739 }
3740
3741
3742 void p2p_set_managed_oper(struct p2p_data *p2p, int enabled)
3743 {
3744         if (enabled) {
3745                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Managed P2P "
3746                         "Device operations enabled");
3747                 p2p->dev_capab |= P2P_DEV_CAPAB_INFRA_MANAGED;
3748         } else {
3749                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Managed P2P "
3750                         "Device operations disabled");
3751                 p2p->dev_capab &= ~P2P_DEV_CAPAB_INFRA_MANAGED;
3752         }
3753 }
3754
3755
3756 int p2p_set_listen_channel(struct p2p_data *p2p, u8 reg_class, u8 channel)
3757 {
3758         if (p2p_channel_to_freq(p2p->cfg->country, reg_class, channel) < 0)
3759                 return -1;
3760
3761         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Set Listen channel: "
3762                 "reg_class %u channel %u", reg_class, channel);
3763         p2p->cfg->reg_class = reg_class;
3764         p2p->cfg->channel = channel;
3765
3766         return 0;
3767 }
3768
3769
3770 int p2p_set_ssid_postfix(struct p2p_data *p2p, const u8 *postfix, size_t len)
3771 {
3772         wpa_hexdump_ascii(MSG_DEBUG, "P2P: New SSID postfix", postfix, len);
3773         if (postfix == NULL) {
3774                 p2p->cfg->ssid_postfix_len = 0;
3775                 return 0;
3776         }
3777         if (len > sizeof(p2p->cfg->ssid_postfix))
3778                 return -1;
3779         os_memcpy(p2p->cfg->ssid_postfix, postfix, len);
3780         p2p->cfg->ssid_postfix_len = len;
3781         return 0;
3782 }
3783
3784
3785 int p2p_set_oper_channel(struct p2p_data *p2p, u8 op_reg_class, u8 op_channel,
3786                          int cfg_op_channel)
3787 {
3788         if (p2p_channel_to_freq(p2p->cfg->country, op_reg_class, op_channel)
3789             < 0)
3790                 return -1;
3791
3792         wpa_msg(p2p->cfg->msg_ctx, MSG_INFO, "P2P: Set Operating channel: "
3793                 "reg_class %u channel %u", op_reg_class, op_channel);
3794         p2p->cfg->op_reg_class = op_reg_class;
3795         p2p->cfg->op_channel = op_channel;
3796         p2p->cfg->cfg_op_channel = cfg_op_channel;
3797         return 0;
3798 }
3799
3800
3801 int p2p_set_pref_chan(struct p2p_data *p2p, unsigned int num_pref_chan,
3802                       const struct p2p_channel *pref_chan)
3803 {
3804         struct p2p_channel *n;
3805
3806         if (pref_chan) {
3807                 n = os_malloc(num_pref_chan * sizeof(struct p2p_channel));
3808                 if (n == NULL)
3809                         return -1;
3810                 os_memcpy(n, pref_chan,
3811                           num_pref_chan * sizeof(struct p2p_channel));
3812         } else
3813                 n = NULL;
3814
3815         os_free(p2p->cfg->pref_chan);
3816         p2p->cfg->pref_chan = n;
3817         p2p->cfg->num_pref_chan = num_pref_chan;
3818
3819         return 0;
3820 }
3821
3822
3823 int p2p_get_interface_addr(struct p2p_data *p2p, const u8 *dev_addr,
3824                            u8 *iface_addr)
3825 {
3826         struct p2p_device *dev = p2p_get_device(p2p, dev_addr);
3827         if (dev == NULL || is_zero_ether_addr(dev->interface_addr))
3828                 return -1;
3829         os_memcpy(iface_addr, dev->interface_addr, ETH_ALEN);
3830         return 0;
3831 }
3832
3833
3834 int p2p_get_dev_addr(struct p2p_data *p2p, const u8 *iface_addr,
3835                            u8 *dev_addr)
3836 {
3837         struct p2p_device *dev = p2p_get_device_interface(p2p, iface_addr);
3838         if (dev == NULL)
3839                 return -1;
3840         os_memcpy(dev_addr, dev->info.p2p_device_addr, ETH_ALEN);
3841         return 0;
3842 }
3843
3844
3845 void p2p_set_peer_filter(struct p2p_data *p2p, const u8 *addr)
3846 {
3847         os_memcpy(p2p->peer_filter, addr, ETH_ALEN);
3848         if (is_zero_ether_addr(p2p->peer_filter))
3849                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Disable peer "
3850                         "filter");
3851         else
3852                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Enable peer "
3853                         "filter for " MACSTR, MAC2STR(p2p->peer_filter));
3854 }
3855
3856
3857 void p2p_set_cross_connect(struct p2p_data *p2p, int enabled)
3858 {
3859         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Cross connection %s",
3860                 enabled ? "enabled" : "disabled");
3861         if (p2p->cross_connect == enabled)
3862                 return;
3863         p2p->cross_connect = enabled;
3864         /* TODO: may need to tear down any action group where we are GO(?) */
3865 }
3866
3867
3868 int p2p_get_oper_freq(struct p2p_data *p2p, const u8 *iface_addr)
3869 {
3870         struct p2p_device *dev = p2p_get_device_interface(p2p, iface_addr);
3871         if (dev == NULL)
3872                 return -1;
3873         if (dev->oper_freq <= 0)
3874                 return -1;
3875         return dev->oper_freq;
3876 }
3877
3878
3879 void p2p_set_intra_bss_dist(struct p2p_data *p2p, int enabled)
3880 {
3881         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Intra BSS distribution %s",
3882                 enabled ? "enabled" : "disabled");
3883         p2p->cfg->p2p_intra_bss = enabled;
3884 }
3885
3886
3887 void p2p_update_channel_list(struct p2p_data *p2p, struct p2p_channels *chan)
3888 {
3889         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Update channel list");
3890         os_memcpy(&p2p->cfg->channels, chan, sizeof(struct p2p_channels));
3891 }
3892
3893
3894 int p2p_send_action(struct p2p_data *p2p, unsigned int freq, const u8 *dst,
3895                     const u8 *src, const u8 *bssid, const u8 *buf,
3896                     size_t len, unsigned int wait_time)
3897 {
3898         if (p2p->p2p_scan_running) {
3899                 wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Delay Action "
3900                         "frame TX until p2p_scan completes");
3901                 if (p2p->after_scan_tx) {
3902                         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Dropped "
3903                                 "previous pending Action frame TX");
3904                         os_free(p2p->after_scan_tx);
3905                 }
3906                 p2p->after_scan_tx = os_malloc(sizeof(*p2p->after_scan_tx) +
3907                                                len);
3908                 if (p2p->after_scan_tx == NULL)
3909                         return -1;
3910                 p2p->after_scan_tx->freq = freq;
3911                 os_memcpy(p2p->after_scan_tx->dst, dst, ETH_ALEN);
3912                 os_memcpy(p2p->after_scan_tx->src, src, ETH_ALEN);
3913                 os_memcpy(p2p->after_scan_tx->bssid, bssid, ETH_ALEN);
3914                 p2p->after_scan_tx->len = len;
3915                 p2p->after_scan_tx->wait_time = wait_time;
3916                 os_memcpy(p2p->after_scan_tx + 1, buf, len);
3917                 return 0;
3918         }
3919
3920         return p2p->cfg->send_action(p2p->cfg->cb_ctx, freq, dst, src, bssid,
3921                                      buf, len, wait_time);
3922 }
3923
3924
3925 void p2p_set_best_channels(struct p2p_data *p2p, int freq_24, int freq_5,
3926                            int freq_overall)
3927 {
3928         wpa_msg(p2p->cfg->msg_ctx, MSG_DEBUG, "P2P: Best channel: 2.4 GHz: %d,"
3929                 "  5 GHz: %d,  overall: %d", freq_24, freq_5, freq_overall);
3930         p2p->best_freq_24 = freq_24;
3931         p2p->best_freq_5 = freq_5;
3932         p2p->best_freq_overall = freq_overall;
3933 }
3934
3935
3936 const u8 * p2p_get_go_neg_peer(struct p2p_data *p2p)
3937 {
3938         if (p2p == NULL || p2p->go_neg_peer == NULL)
3939                 return NULL;
3940         return p2p->go_neg_peer->info.p2p_device_addr;
3941 }
3942
3943
3944 const struct p2p_peer_info *
3945 p2p_get_peer_found(struct p2p_data *p2p, const u8 *addr, int next)
3946 {
3947         struct p2p_device *dev;
3948
3949         if (addr) {
3950                 dev = p2p_get_device(p2p, addr);
3951                 if (!dev)
3952                         return NULL;
3953
3954                 if (!next) {
3955                         if (dev->flags & P2P_DEV_PROBE_REQ_ONLY)
3956                                 return NULL;
3957
3958                         return &dev->info;
3959                 } else {
3960                         do {
3961                                 dev = dl_list_first(&dev->list,
3962                                                     struct p2p_device,
3963                                                     list);
3964                                 if (&dev->list == &p2p->devices)
3965                                         return NULL;
3966                         } while (dev->flags & P2P_DEV_PROBE_REQ_ONLY);
3967                 }
3968         } else {
3969                 dev = dl_list_first(&p2p->devices, struct p2p_device, list);
3970                 if (!dev)
3971                         return NULL;
3972                 while (dev->flags & P2P_DEV_PROBE_REQ_ONLY) {
3973                         dev = dl_list_first(&dev->list,
3974                                             struct p2p_device,
3975                                             list);
3976                         if (&dev->list == &p2p->devices)
3977                                 return NULL;
3978                 }
3979         }
3980
3981         return &dev->info;
3982 }
3983
3984
3985 int p2p_in_progress(struct p2p_data *p2p)
3986 {
3987         if (p2p == NULL)
3988                 return 0;
3989         return p2p->state != P2P_IDLE && p2p->state != P2P_PROVISIONING;
3990 }