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