P2P: Avoid extra group interface creation on GO reinvocation
[mech_eap.git] / wpa_supplicant / p2p_supplicant.c
1 /*
2  * wpa_supplicant - P2P
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_common.h"
14 #include "common/ieee802_11_defs.h"
15 #include "common/wpa_ctrl.h"
16 #include "wps/wps_i.h"
17 #include "p2p/p2p.h"
18 #include "ap/hostapd.h"
19 #include "ap/ap_config.h"
20 #include "ap/p2p_hostapd.h"
21 #include "eapol_supp/eapol_supp_sm.h"
22 #include "rsn_supp/wpa.h"
23 #include "wpa_supplicant_i.h"
24 #include "driver_i.h"
25 #include "ap.h"
26 #include "config_ssid.h"
27 #include "config.h"
28 #include "notify.h"
29 #include "scan.h"
30 #include "bss.h"
31 #include "offchannel.h"
32 #include "wps_supplicant.h"
33 #include "p2p_supplicant.h"
34
35
36 /*
37  * How many times to try to scan to find the GO before giving up on join
38  * request.
39  */
40 #define P2P_MAX_JOIN_SCAN_ATTEMPTS 10
41
42 #define P2P_AUTO_PD_SCAN_ATTEMPTS 5
43
44 #ifndef P2P_MAX_CLIENT_IDLE
45 /*
46  * How many seconds to try to reconnect to the GO when connection in P2P client
47  * role has been lost.
48  */
49 #define P2P_MAX_CLIENT_IDLE 10
50 #endif /* P2P_MAX_CLIENT_IDLE */
51
52 #ifndef P2P_MAX_INITIAL_CONN_WAIT
53 /*
54  * How many seconds to wait for initial 4-way handshake to get completed after
55  * WPS provisioning step.
56  */
57 #define P2P_MAX_INITIAL_CONN_WAIT 10
58 #endif /* P2P_MAX_INITIAL_CONN_WAIT */
59
60 #ifndef P2P_CONCURRENT_SEARCH_DELAY
61 #define P2P_CONCURRENT_SEARCH_DELAY 500
62 #endif /* P2P_CONCURRENT_SEARCH_DELAY */
63
64 enum p2p_group_removal_reason {
65         P2P_GROUP_REMOVAL_UNKNOWN,
66         P2P_GROUP_REMOVAL_SILENT,
67         P2P_GROUP_REMOVAL_FORMATION_FAILED,
68         P2P_GROUP_REMOVAL_REQUESTED,
69         P2P_GROUP_REMOVAL_IDLE_TIMEOUT,
70         P2P_GROUP_REMOVAL_UNAVAILABLE,
71         P2P_GROUP_REMOVAL_GO_ENDING_SESSION
72 };
73
74
75 static void wpas_p2p_long_listen_timeout(void *eloop_ctx, void *timeout_ctx);
76 static struct wpa_supplicant *
77 wpas_p2p_get_group_iface(struct wpa_supplicant *wpa_s, int addr_allocated,
78                          int go);
79 static int wpas_p2p_join_start(struct wpa_supplicant *wpa_s);
80 static void wpas_p2p_join_scan_req(struct wpa_supplicant *wpa_s, int freq);
81 static void wpas_p2p_join_scan(void *eloop_ctx, void *timeout_ctx);
82 static int wpas_p2p_join(struct wpa_supplicant *wpa_s, const u8 *iface_addr,
83                          const u8 *dev_addr, enum p2p_wps_method wps_method,
84                          int auto_join);
85 static void wpas_p2p_pd_before_join_timeout(void *eloop_ctx,
86                                             void *timeout_ctx);
87 static int wpas_p2p_create_iface(struct wpa_supplicant *wpa_s);
88 static void wpas_p2p_cross_connect_setup(struct wpa_supplicant *wpa_s);
89 static void wpas_p2p_group_idle_timeout(void *eloop_ctx, void *timeout_ctx);
90 static void wpas_p2p_set_group_idle_timeout(struct wpa_supplicant *wpa_s);
91 static void wpas_p2p_fallback_to_go_neg(struct wpa_supplicant *wpa_s,
92                                         int group_added);
93 static int wpas_p2p_stop_find_oper(struct wpa_supplicant *wpa_s);
94
95
96 static void wpas_p2p_scan_res_handler(struct wpa_supplicant *wpa_s,
97                                       struct wpa_scan_results *scan_res)
98 {
99         size_t i;
100
101         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
102                 return;
103
104         wpa_printf(MSG_DEBUG, "P2P: Scan results received (%d BSS)",
105                    (int) scan_res->num);
106
107         for (i = 0; i < scan_res->num; i++) {
108                 struct wpa_scan_res *bss = scan_res->res[i];
109                 if (p2p_scan_res_handler(wpa_s->global->p2p, bss->bssid,
110                                          bss->freq, bss->level,
111                                          (const u8 *) (bss + 1),
112                                          bss->ie_len) > 0)
113                         break;
114         }
115
116         p2p_scan_res_handled(wpa_s->global->p2p);
117 }
118
119
120 static int wpas_p2p_scan(void *ctx, enum p2p_scan_type type, int freq,
121                          unsigned int num_req_dev_types,
122                          const u8 *req_dev_types, const u8 *dev_id, u16 pw_id)
123 {
124         struct wpa_supplicant *wpa_s = ctx;
125         struct wpa_supplicant *ifs;
126         struct wpa_driver_scan_params params;
127         int ret;
128         struct wpabuf *wps_ie, *ies;
129         int social_channels[] = { 2412, 2437, 2462, 0, 0 };
130         size_t ielen;
131
132         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
133                 return -1;
134
135         for (ifs = wpa_s->global->ifaces; ifs; ifs = ifs->next) {
136                 if (ifs->sta_scan_pending &&
137                     wpas_p2p_in_progress(wpa_s) == 2) {
138                         wpa_printf(MSG_DEBUG, "Delaying P2P scan to allow "
139                                    "pending station mode scan to be "
140                                    "completed on interface %s", ifs->ifname);
141                         wpa_s->global->p2p_cb_on_scan_complete = 1;
142                         wpa_supplicant_req_scan(ifs, 0, 0);
143                         return 1;
144                 }
145         }
146
147         os_memset(&params, 0, sizeof(params));
148
149         /* P2P Wildcard SSID */
150         params.num_ssids = 1;
151         params.ssids[0].ssid = (u8 *) P2P_WILDCARD_SSID;
152         params.ssids[0].ssid_len = P2P_WILDCARD_SSID_LEN;
153
154         wpa_s->wps->dev.p2p = 1;
155         wps_ie = wps_build_probe_req_ie(pw_id, &wpa_s->wps->dev,
156                                         wpa_s->wps->uuid, WPS_REQ_ENROLLEE,
157                                         num_req_dev_types, req_dev_types);
158         if (wps_ie == NULL)
159                 return -1;
160
161         ielen = p2p_scan_ie_buf_len(wpa_s->global->p2p);
162         ies = wpabuf_alloc(wpabuf_len(wps_ie) + ielen);
163         if (ies == NULL) {
164                 wpabuf_free(wps_ie);
165                 return -1;
166         }
167         wpabuf_put_buf(ies, wps_ie);
168         wpabuf_free(wps_ie);
169
170         p2p_scan_ie(wpa_s->global->p2p, ies, dev_id);
171
172         params.p2p_probe = 1;
173         params.extra_ies = wpabuf_head(ies);
174         params.extra_ies_len = wpabuf_len(ies);
175
176         switch (type) {
177         case P2P_SCAN_SOCIAL:
178                 params.freqs = social_channels;
179                 break;
180         case P2P_SCAN_FULL:
181                 break;
182         case P2P_SCAN_SOCIAL_PLUS_ONE:
183                 social_channels[3] = freq;
184                 params.freqs = social_channels;
185                 break;
186         }
187
188         ret = wpa_drv_scan(wpa_s, &params);
189
190         wpabuf_free(ies);
191
192         if (ret) {
193                 for (ifs = wpa_s->global->ifaces; ifs; ifs = ifs->next) {
194                         if (ifs->scanning ||
195                             ifs->scan_res_handler == wpas_p2p_scan_res_handler) {
196                                 wpa_s->global->p2p_cb_on_scan_complete = 1;
197                                 ret = 1;
198                                 break;
199                         }
200                 }
201         } else
202                 wpa_s->scan_res_handler = wpas_p2p_scan_res_handler;
203
204         return ret;
205 }
206
207
208 static enum wpa_driver_if_type wpas_p2p_if_type(int p2p_group_interface)
209 {
210         switch (p2p_group_interface) {
211         case P2P_GROUP_INTERFACE_PENDING:
212                 return WPA_IF_P2P_GROUP;
213         case P2P_GROUP_INTERFACE_GO:
214                 return WPA_IF_P2P_GO;
215         case P2P_GROUP_INTERFACE_CLIENT:
216                 return WPA_IF_P2P_CLIENT;
217         }
218
219         return WPA_IF_P2P_GROUP;
220 }
221
222
223 static struct wpa_supplicant * wpas_get_p2p_group(struct wpa_supplicant *wpa_s,
224                                                   const u8 *ssid,
225                                                   size_t ssid_len, int *go)
226 {
227         struct wpa_ssid *s;
228
229         for (wpa_s = wpa_s->global->ifaces; wpa_s; wpa_s = wpa_s->next) {
230                 for (s = wpa_s->conf->ssid; s; s = s->next) {
231                         if (s->disabled != 0 || !s->p2p_group ||
232                             s->ssid_len != ssid_len ||
233                             os_memcmp(ssid, s->ssid, ssid_len) != 0)
234                                 continue;
235                         if (s->mode == WPAS_MODE_P2P_GO &&
236                             s != wpa_s->current_ssid)
237                                 continue;
238                         if (go)
239                                 *go = s->mode == WPAS_MODE_P2P_GO;
240                         return wpa_s;
241                 }
242         }
243
244         return NULL;
245 }
246
247
248 static int wpas_p2p_group_delete(struct wpa_supplicant *wpa_s,
249                                  enum p2p_group_removal_reason removal_reason)
250 {
251         struct wpa_ssid *ssid;
252         char *gtype;
253         const char *reason;
254
255         ssid = wpa_s->current_ssid;
256         if (ssid == NULL) {
257                 /*
258                  * The current SSID was not known, but there may still be a
259                  * pending P2P group interface waiting for provisioning or a
260                  * P2P group that is trying to reconnect.
261                  */
262                 ssid = wpa_s->conf->ssid;
263                 while (ssid) {
264                         if (ssid->p2p_group && ssid->disabled != 2)
265                                 break;
266                         ssid = ssid->next;
267                 }
268                 if (ssid == NULL &&
269                         wpa_s->p2p_group_interface == NOT_P2P_GROUP_INTERFACE)
270                 {
271                         wpa_printf(MSG_ERROR, "P2P: P2P group interface "
272                                    "not found");
273                         return -1;
274                 }
275         }
276         if (wpa_s->p2p_group_interface == P2P_GROUP_INTERFACE_GO)
277                 gtype = "GO";
278         else if (wpa_s->p2p_group_interface == P2P_GROUP_INTERFACE_CLIENT ||
279                  (ssid && ssid->mode == WPAS_MODE_INFRA)) {
280                 wpa_s->reassociate = 0;
281                 wpa_s->disconnected = 1;
282                 wpa_supplicant_deauthenticate(wpa_s,
283                                               WLAN_REASON_DEAUTH_LEAVING);
284                 gtype = "client";
285         } else
286                 gtype = "GO";
287         if (wpa_s->cross_connect_in_use) {
288                 wpa_s->cross_connect_in_use = 0;
289                 wpa_msg(wpa_s->parent, MSG_INFO,
290                         P2P_EVENT_CROSS_CONNECT_DISABLE "%s %s",
291                         wpa_s->ifname, wpa_s->cross_connect_uplink);
292         }
293         switch (removal_reason) {
294         case P2P_GROUP_REMOVAL_REQUESTED:
295                 reason = " reason=REQUESTED";
296                 break;
297         case P2P_GROUP_REMOVAL_FORMATION_FAILED:
298                 reason = " reason=FORMATION_FAILED";
299                 break;
300         case P2P_GROUP_REMOVAL_IDLE_TIMEOUT:
301                 reason = " reason=IDLE";
302                 break;
303         case P2P_GROUP_REMOVAL_UNAVAILABLE:
304                 reason = " reason=UNAVAILABLE";
305                 break;
306         case P2P_GROUP_REMOVAL_GO_ENDING_SESSION:
307                 reason = " reason=GO_ENDING_SESSION";
308                 break;
309         default:
310                 reason = "";
311                 break;
312         }
313         if (removal_reason != P2P_GROUP_REMOVAL_SILENT) {
314                 wpa_msg(wpa_s->parent, MSG_INFO,
315                         P2P_EVENT_GROUP_REMOVED "%s %s%s",
316                         wpa_s->ifname, gtype, reason);
317         }
318
319         if (eloop_cancel_timeout(wpas_p2p_group_idle_timeout, wpa_s, NULL) > 0)
320                 wpa_printf(MSG_DEBUG, "P2P: Cancelled P2P group idle timeout");
321
322         if (removal_reason != P2P_GROUP_REMOVAL_SILENT && ssid)
323                 wpas_notify_p2p_group_removed(wpa_s, ssid, gtype);
324
325         if (wpa_s->p2p_group_interface != NOT_P2P_GROUP_INTERFACE) {
326                 struct wpa_global *global;
327                 char *ifname;
328                 enum wpa_driver_if_type type;
329                 wpa_printf(MSG_DEBUG, "P2P: Remove group interface %s",
330                         wpa_s->ifname);
331                 global = wpa_s->global;
332                 ifname = os_strdup(wpa_s->ifname);
333                 type = wpas_p2p_if_type(wpa_s->p2p_group_interface);
334                 wpa_supplicant_remove_iface(wpa_s->global, wpa_s, 0);
335                 wpa_s = global->ifaces;
336                 if (wpa_s && ifname)
337                         wpa_drv_if_remove(wpa_s, type, ifname);
338                 os_free(ifname);
339                 return 1;
340         }
341
342         wpa_printf(MSG_DEBUG, "P2P: Remove temporary group network");
343         if (ssid && (ssid->p2p_group ||
344                      ssid->mode == WPAS_MODE_P2P_GROUP_FORMATION ||
345                      (ssid->key_mgmt & WPA_KEY_MGMT_WPS))) {
346                 int id = ssid->id;
347                 if (ssid == wpa_s->current_ssid) {
348                         wpa_sm_set_config(wpa_s->wpa, NULL);
349                         eapol_sm_notify_config(wpa_s->eapol, NULL, NULL);
350                         wpa_s->current_ssid = NULL;
351                 }
352                 /*
353                  * Networks objects created during any P2P activities are not
354                  * exposed out as they might/will confuse certain non-P2P aware
355                  * applications since these network objects won't behave like
356                  * regular ones.
357                  *
358                  * Likewise, we don't send out network removed signals for such
359                  * network objects.
360                  */
361                 wpa_config_remove_network(wpa_s->conf, id);
362                 wpa_supplicant_clear_status(wpa_s);
363                 wpa_supplicant_cancel_sched_scan(wpa_s);
364                 wpa_s->sta_scan_pending = 0;
365         } else {
366                 wpa_printf(MSG_DEBUG, "P2P: Temporary group network not "
367                            "found");
368         }
369         if (wpa_s->ap_iface)
370                 wpa_supplicant_ap_deinit(wpa_s);
371         else
372                 wpa_drv_deinit_p2p_cli(wpa_s);
373
374         return 0;
375 }
376
377
378 static int wpas_p2p_persistent_group(struct wpa_supplicant *wpa_s,
379                                      u8 *go_dev_addr,
380                                      const u8 *ssid, size_t ssid_len)
381 {
382         struct wpa_bss *bss;
383         const u8 *bssid;
384         struct wpabuf *p2p;
385         u8 group_capab;
386         const u8 *addr;
387
388         if (wpa_s->go_params)
389                 bssid = wpa_s->go_params->peer_interface_addr;
390         else
391                 bssid = wpa_s->bssid;
392
393         bss = wpa_bss_get(wpa_s, bssid, ssid, ssid_len);
394         if (bss == NULL) {
395                 u8 iface_addr[ETH_ALEN];
396                 if (p2p_get_interface_addr(wpa_s->global->p2p, bssid,
397                                            iface_addr) == 0)
398                         bss = wpa_bss_get(wpa_s, iface_addr, ssid, ssid_len);
399         }
400         if (bss == NULL) {
401                 wpa_printf(MSG_DEBUG, "P2P: Could not figure out whether "
402                            "group is persistent - BSS " MACSTR " not found",
403                            MAC2STR(bssid));
404                 return 0;
405         }
406
407         p2p = wpa_bss_get_vendor_ie_multi(bss, P2P_IE_VENDOR_TYPE);
408         if (p2p == NULL) {
409                 wpa_printf(MSG_DEBUG, "P2P: Could not figure out whether "
410                            "group is persistent - BSS " MACSTR
411                            " did not include P2P IE", MAC2STR(bssid));
412                 wpa_hexdump(MSG_DEBUG, "P2P: Probe Response IEs",
413                             (u8 *) (bss + 1), bss->ie_len);
414                 wpa_hexdump(MSG_DEBUG, "P2P: Beacon IEs",
415                             ((u8 *) bss + 1) + bss->ie_len,
416                             bss->beacon_ie_len);
417                 return 0;
418         }
419
420         group_capab = p2p_get_group_capab(p2p);
421         addr = p2p_get_go_dev_addr(p2p);
422         wpa_printf(MSG_DEBUG, "P2P: Checking whether group is persistent: "
423                    "group_capab=0x%x", group_capab);
424         if (addr) {
425                 os_memcpy(go_dev_addr, addr, ETH_ALEN);
426                 wpa_printf(MSG_DEBUG, "P2P: GO Device Address " MACSTR,
427                            MAC2STR(addr));
428         } else
429                 os_memset(go_dev_addr, 0, ETH_ALEN);
430         wpabuf_free(p2p);
431
432         wpa_printf(MSG_DEBUG, "P2P: BSS " MACSTR " group_capab=0x%x "
433                    "go_dev_addr=" MACSTR,
434                    MAC2STR(bssid), group_capab, MAC2STR(go_dev_addr));
435
436         return group_capab & P2P_GROUP_CAPAB_PERSISTENT_GROUP;
437 }
438
439
440 static int wpas_p2p_store_persistent_group(struct wpa_supplicant *wpa_s,
441                                            struct wpa_ssid *ssid,
442                                            const u8 *go_dev_addr)
443 {
444         struct wpa_ssid *s;
445         int changed = 0;
446
447         wpa_printf(MSG_DEBUG, "P2P: Storing credentials for a persistent "
448                    "group (GO Dev Addr " MACSTR ")", MAC2STR(go_dev_addr));
449         for (s = wpa_s->conf->ssid; s; s = s->next) {
450                 if (s->disabled == 2 &&
451                     os_memcmp(go_dev_addr, s->bssid, ETH_ALEN) == 0 &&
452                     s->ssid_len == ssid->ssid_len &&
453                     os_memcmp(ssid->ssid, s->ssid, ssid->ssid_len) == 0)
454                         break;
455         }
456
457         if (s) {
458                 wpa_printf(MSG_DEBUG, "P2P: Update existing persistent group "
459                            "entry");
460                 if (ssid->passphrase && !s->passphrase)
461                         changed = 1;
462                 else if (ssid->passphrase && s->passphrase &&
463                          os_strcmp(ssid->passphrase, s->passphrase) != 0)
464                         changed = 1;
465         } else {
466                 wpa_printf(MSG_DEBUG, "P2P: Create a new persistent group "
467                            "entry");
468                 changed = 1;
469                 s = wpa_config_add_network(wpa_s->conf);
470                 if (s == NULL)
471                         return -1;
472
473                 /*
474                  * Instead of network_added we emit persistent_group_added
475                  * notification. Also to keep the defense checks in
476                  * persistent_group obj registration method, we set the
477                  * relevant flags in s to designate it as a persistent group.
478                  */
479                 s->p2p_group = 1;
480                 s->p2p_persistent_group = 1;
481                 wpas_notify_persistent_group_added(wpa_s, s);
482                 wpa_config_set_network_defaults(s);
483         }
484
485         s->p2p_group = 1;
486         s->p2p_persistent_group = 1;
487         s->disabled = 2;
488         s->bssid_set = 1;
489         os_memcpy(s->bssid, go_dev_addr, ETH_ALEN);
490         s->mode = ssid->mode;
491         s->auth_alg = WPA_AUTH_ALG_OPEN;
492         s->key_mgmt = WPA_KEY_MGMT_PSK;
493         s->proto = WPA_PROTO_RSN;
494         s->pairwise_cipher = WPA_CIPHER_CCMP;
495         s->export_keys = 1;
496         if (ssid->passphrase) {
497                 os_free(s->passphrase);
498                 s->passphrase = os_strdup(ssid->passphrase);
499         }
500         if (ssid->psk_set) {
501                 s->psk_set = 1;
502                 os_memcpy(s->psk, ssid->psk, 32);
503         }
504         if (s->passphrase && !s->psk_set)
505                 wpa_config_update_psk(s);
506         if (s->ssid == NULL || s->ssid_len < ssid->ssid_len) {
507                 os_free(s->ssid);
508                 s->ssid = os_malloc(ssid->ssid_len);
509         }
510         if (s->ssid) {
511                 s->ssid_len = ssid->ssid_len;
512                 os_memcpy(s->ssid, ssid->ssid, s->ssid_len);
513         }
514
515 #ifndef CONFIG_NO_CONFIG_WRITE
516         if (changed && wpa_s->conf->update_config &&
517             wpa_config_write(wpa_s->confname, wpa_s->conf)) {
518                 wpa_printf(MSG_DEBUG, "P2P: Failed to update configuration");
519         }
520 #endif /* CONFIG_NO_CONFIG_WRITE */
521
522         return s->id;
523 }
524
525
526 static void wpas_p2p_add_persistent_group_client(struct wpa_supplicant *wpa_s,
527                                                  const u8 *addr)
528 {
529         struct wpa_ssid *ssid, *s;
530         u8 *n;
531         size_t i;
532         int found = 0;
533
534         ssid = wpa_s->current_ssid;
535         if (ssid == NULL || ssid->mode != WPAS_MODE_P2P_GO ||
536             !ssid->p2p_persistent_group)
537                 return;
538
539         for (s = wpa_s->parent->conf->ssid; s; s = s->next) {
540                 if (s->disabled != 2 || s->mode != WPAS_MODE_P2P_GO)
541                         continue;
542
543                 if (s->ssid_len == ssid->ssid_len &&
544                     os_memcmp(s->ssid, ssid->ssid, s->ssid_len) == 0)
545                         break;
546         }
547
548         if (s == NULL)
549                 return;
550
551         for (i = 0; s->p2p_client_list && i < s->num_p2p_clients; i++) {
552                 if (os_memcmp(s->p2p_client_list + i * ETH_ALEN, addr,
553                               ETH_ALEN) != 0)
554                         continue;
555
556                 if (i == s->num_p2p_clients - 1)
557                         return; /* already the most recent entry */
558
559                 /* move the entry to mark it most recent */
560                 os_memmove(s->p2p_client_list + i * ETH_ALEN,
561                            s->p2p_client_list + (i + 1) * ETH_ALEN,
562                            (s->num_p2p_clients - i - 1) * ETH_ALEN);
563                 os_memcpy(s->p2p_client_list +
564                           (s->num_p2p_clients - 1) * ETH_ALEN, addr, ETH_ALEN);
565                 found = 1;
566                 break;
567         }
568
569         if (!found && s->num_p2p_clients < P2P_MAX_STORED_CLIENTS) {
570                 n = os_realloc_array(s->p2p_client_list,
571                                      s->num_p2p_clients + 1, ETH_ALEN);
572                 if (n == NULL)
573                         return;
574                 os_memcpy(n + s->num_p2p_clients * ETH_ALEN, addr, ETH_ALEN);
575                 s->p2p_client_list = n;
576                 s->num_p2p_clients++;
577         } else if (!found) {
578                 /* Not enough room for an additional entry - drop the oldest
579                  * entry */
580                 os_memmove(s->p2p_client_list,
581                            s->p2p_client_list + ETH_ALEN,
582                            (s->num_p2p_clients - 1) * ETH_ALEN);
583                 os_memcpy(s->p2p_client_list +
584                           (s->num_p2p_clients - 1) * ETH_ALEN,
585                           addr, ETH_ALEN);
586         }
587
588 #ifndef CONFIG_NO_CONFIG_WRITE
589         if (wpa_s->parent->conf->update_config &&
590             wpa_config_write(wpa_s->parent->confname, wpa_s->parent->conf))
591                 wpa_printf(MSG_DEBUG, "P2P: Failed to update configuration");
592 #endif /* CONFIG_NO_CONFIG_WRITE */
593 }
594
595
596 static void wpas_group_formation_completed(struct wpa_supplicant *wpa_s,
597                                            int success)
598 {
599         struct wpa_ssid *ssid;
600         const char *ssid_txt;
601         int client;
602         int persistent;
603         u8 go_dev_addr[ETH_ALEN];
604         int network_id = -1;
605
606         /*
607          * This callback is likely called for the main interface. Update wpa_s
608          * to use the group interface if a new interface was created for the
609          * group.
610          */
611         if (wpa_s->global->p2p_group_formation)
612                 wpa_s = wpa_s->global->p2p_group_formation;
613         wpa_s->global->p2p_group_formation = NULL;
614         wpa_s->p2p_in_provisioning = 0;
615
616         if (!success) {
617                 wpa_msg(wpa_s->parent, MSG_INFO,
618                         P2P_EVENT_GROUP_FORMATION_FAILURE);
619                 wpas_p2p_group_delete(wpa_s,
620                                       P2P_GROUP_REMOVAL_FORMATION_FAILED);
621                 return;
622         }
623
624         wpa_msg(wpa_s->parent, MSG_INFO, P2P_EVENT_GROUP_FORMATION_SUCCESS);
625
626         ssid = wpa_s->current_ssid;
627         if (ssid && ssid->mode == WPAS_MODE_P2P_GROUP_FORMATION) {
628                 ssid->mode = WPAS_MODE_P2P_GO;
629                 p2p_group_notif_formation_done(wpa_s->p2p_group);
630                 wpa_supplicant_ap_mac_addr_filter(wpa_s, NULL);
631         }
632
633         persistent = 0;
634         if (ssid) {
635                 ssid_txt = wpa_ssid_txt(ssid->ssid, ssid->ssid_len);
636                 client = ssid->mode == WPAS_MODE_INFRA;
637                 if (ssid->mode == WPAS_MODE_P2P_GO) {
638                         persistent = ssid->p2p_persistent_group;
639                         os_memcpy(go_dev_addr, wpa_s->global->p2p_dev_addr,
640                                   ETH_ALEN);
641                 } else
642                         persistent = wpas_p2p_persistent_group(wpa_s,
643                                                                go_dev_addr,
644                                                                ssid->ssid,
645                                                                ssid->ssid_len);
646         } else {
647                 ssid_txt = "";
648                 client = wpa_s->p2p_group_interface ==
649                         P2P_GROUP_INTERFACE_CLIENT;
650                 os_memset(go_dev_addr, 0, ETH_ALEN);
651         }
652
653         wpa_s->show_group_started = 0;
654         if (client) {
655                 /*
656                  * Indicate event only after successfully completed 4-way
657                  * handshake, i.e., when the interface is ready for data
658                  * packets.
659                  */
660                 wpa_s->show_group_started = 1;
661         } else if (ssid && ssid->passphrase == NULL && ssid->psk_set) {
662                 char psk[65];
663                 wpa_snprintf_hex(psk, sizeof(psk), ssid->psk, 32);
664                 wpa_msg(wpa_s->parent, MSG_INFO, P2P_EVENT_GROUP_STARTED
665                         "%s GO ssid=\"%s\" freq=%d psk=%s go_dev_addr=" MACSTR
666                         "%s",
667                         wpa_s->ifname, ssid_txt, ssid->frequency, psk,
668                         MAC2STR(go_dev_addr),
669                         persistent ? " [PERSISTENT]" : "");
670                 wpas_p2p_cross_connect_setup(wpa_s);
671                 wpas_p2p_set_group_idle_timeout(wpa_s);
672         } else {
673                 wpa_msg(wpa_s->parent, MSG_INFO, P2P_EVENT_GROUP_STARTED
674                         "%s GO ssid=\"%s\" freq=%d passphrase=\"%s\" "
675                         "go_dev_addr=" MACSTR "%s",
676                         wpa_s->ifname, ssid_txt, ssid ? ssid->frequency : 0,
677                         ssid && ssid->passphrase ? ssid->passphrase : "",
678                         MAC2STR(go_dev_addr),
679                         persistent ? " [PERSISTENT]" : "");
680                 wpas_p2p_cross_connect_setup(wpa_s);
681                 wpas_p2p_set_group_idle_timeout(wpa_s);
682         }
683
684         if (persistent)
685                 network_id = wpas_p2p_store_persistent_group(wpa_s->parent,
686                                                              ssid, go_dev_addr);
687         if (network_id < 0 && ssid)
688                 network_id = ssid->id;
689         if (!client)
690                 wpas_notify_p2p_group_started(wpa_s, ssid, network_id, 0);
691 }
692
693
694 static void wpas_p2p_send_action_tx_status(struct wpa_supplicant *wpa_s,
695                                            unsigned int freq,
696                                            const u8 *dst, const u8 *src,
697                                            const u8 *bssid,
698                                            const u8 *data, size_t data_len,
699                                            enum offchannel_send_action_result
700                                            result)
701 {
702         enum p2p_send_action_result res = P2P_SEND_ACTION_SUCCESS;
703
704         if (wpa_s->global->p2p == NULL || wpa_s->global->p2p_disabled)
705                 return;
706         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
707                 return;
708
709         switch (result) {
710         case OFFCHANNEL_SEND_ACTION_SUCCESS:
711                 res = P2P_SEND_ACTION_SUCCESS;
712                 break;
713         case OFFCHANNEL_SEND_ACTION_NO_ACK:
714                 res = P2P_SEND_ACTION_NO_ACK;
715                 break;
716         case OFFCHANNEL_SEND_ACTION_FAILED:
717                 res = P2P_SEND_ACTION_FAILED;
718                 break;
719         }
720
721         p2p_send_action_cb(wpa_s->global->p2p, freq, dst, src, bssid, res);
722
723         if (result != OFFCHANNEL_SEND_ACTION_SUCCESS &&
724             wpa_s->pending_pd_before_join &&
725             (os_memcmp(dst, wpa_s->pending_join_dev_addr, ETH_ALEN) == 0 ||
726              os_memcmp(dst, wpa_s->pending_join_iface_addr, ETH_ALEN) == 0)) {
727                 wpa_s->pending_pd_before_join = 0;
728                 if (wpa_s->p2p_fallback_to_go_neg) {
729                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: No ACK for PD Req "
730                                 "during p2p_connect-auto");
731                         wpas_p2p_fallback_to_go_neg(wpa_s, 0);
732                         return;
733                 }
734
735                 wpa_printf(MSG_DEBUG, "P2P: Starting pending "
736                            "join-existing-group operation (no ACK for PD "
737                            "Req)");
738                 wpas_p2p_join_start(wpa_s);
739         }
740 }
741
742
743 static int wpas_send_action(void *ctx, unsigned int freq, const u8 *dst,
744                             const u8 *src, const u8 *bssid, const u8 *buf,
745                             size_t len, unsigned int wait_time)
746 {
747         struct wpa_supplicant *wpa_s = ctx;
748         return offchannel_send_action(wpa_s, freq, dst, src, bssid, buf, len,
749                                       wait_time,
750                                       wpas_p2p_send_action_tx_status, 1);
751 }
752
753
754 static void wpas_send_action_done(void *ctx)
755 {
756         struct wpa_supplicant *wpa_s = ctx;
757         offchannel_send_action_done(wpa_s);
758 }
759
760
761 static int wpas_copy_go_neg_results(struct wpa_supplicant *wpa_s,
762                                     struct p2p_go_neg_results *params)
763 {
764         if (wpa_s->go_params == NULL) {
765                 wpa_s->go_params = os_malloc(sizeof(*params));
766                 if (wpa_s->go_params == NULL)
767                         return -1;
768         }
769         os_memcpy(wpa_s->go_params, params, sizeof(*params));
770         return 0;
771 }
772
773
774 static void wpas_start_wps_enrollee(struct wpa_supplicant *wpa_s,
775                                     struct p2p_go_neg_results *res)
776 {
777         wpa_printf(MSG_DEBUG, "P2P: Start WPS Enrollee for peer " MACSTR,
778                    MAC2STR(res->peer_interface_addr));
779         wpa_hexdump_ascii(MSG_DEBUG, "P2P: Start WPS Enrollee for SSID",
780                           res->ssid, res->ssid_len);
781         wpa_supplicant_ap_deinit(wpa_s);
782         wpas_copy_go_neg_results(wpa_s, res);
783         if (res->wps_method == WPS_PBC)
784                 wpas_wps_start_pbc(wpa_s, res->peer_interface_addr, 1);
785         else {
786                 u16 dev_pw_id = DEV_PW_DEFAULT;
787                 if (wpa_s->p2p_wps_method == WPS_PIN_KEYPAD)
788                         dev_pw_id = DEV_PW_REGISTRAR_SPECIFIED;
789                 wpas_wps_start_pin(wpa_s, res->peer_interface_addr,
790                                    wpa_s->p2p_pin, 1, dev_pw_id);
791         }
792 }
793
794
795 static void p2p_go_configured(void *ctx, void *data)
796 {
797         struct wpa_supplicant *wpa_s = ctx;
798         struct p2p_go_neg_results *params = data;
799         struct wpa_ssid *ssid;
800         int network_id = -1;
801
802         ssid = wpa_s->current_ssid;
803         if (ssid && ssid->mode == WPAS_MODE_P2P_GO) {
804                 wpa_printf(MSG_DEBUG, "P2P: Group setup without provisioning");
805                 if (wpa_s->global->p2p_group_formation == wpa_s)
806                         wpa_s->global->p2p_group_formation = NULL;
807                 wpa_msg(wpa_s->parent, MSG_INFO, P2P_EVENT_GROUP_STARTED
808                         "%s GO ssid=\"%s\" freq=%d passphrase=\"%s\" "
809                         "go_dev_addr=" MACSTR "%s",
810                         wpa_s->ifname,
811                         wpa_ssid_txt(ssid->ssid, ssid->ssid_len),
812                         ssid->frequency,
813                         params->passphrase ? params->passphrase : "",
814                         MAC2STR(wpa_s->global->p2p_dev_addr),
815                         params->persistent_group ? " [PERSISTENT]" : "");
816
817                 if (params->persistent_group)
818                         network_id = wpas_p2p_store_persistent_group(
819                                 wpa_s->parent, ssid,
820                                 wpa_s->global->p2p_dev_addr);
821                 if (network_id < 0)
822                         network_id = ssid->id;
823                 wpas_notify_p2p_group_started(wpa_s, ssid, network_id, 0);
824                 wpas_p2p_cross_connect_setup(wpa_s);
825                 wpas_p2p_set_group_idle_timeout(wpa_s);
826                 return;
827         }
828
829         wpa_printf(MSG_DEBUG, "P2P: Setting up WPS for GO provisioning");
830         if (wpa_supplicant_ap_mac_addr_filter(wpa_s,
831                                               params->peer_interface_addr)) {
832                 wpa_printf(MSG_DEBUG, "P2P: Failed to setup MAC address "
833                            "filtering");
834                 return;
835         }
836         if (params->wps_method == WPS_PBC)
837                 wpa_supplicant_ap_wps_pbc(wpa_s, params->peer_interface_addr,
838                                           params->peer_device_addr);
839         else if (wpa_s->p2p_pin[0])
840                 wpa_supplicant_ap_wps_pin(wpa_s, params->peer_interface_addr,
841                                           wpa_s->p2p_pin, NULL, 0, 0);
842         os_free(wpa_s->go_params);
843         wpa_s->go_params = NULL;
844 }
845
846
847 static void wpas_start_wps_go(struct wpa_supplicant *wpa_s,
848                               struct p2p_go_neg_results *params,
849                               int group_formation)
850 {
851         struct wpa_ssid *ssid;
852
853         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Starting GO");
854         if (wpas_copy_go_neg_results(wpa_s, params) < 0) {
855                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Could not copy GO Negotiation "
856                         "results");
857                 return;
858         }
859
860         ssid = wpa_config_add_network(wpa_s->conf);
861         if (ssid == NULL) {
862                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Could not add network for GO");
863                 return;
864         }
865
866         wpa_s->show_group_started = 0;
867
868         wpa_config_set_network_defaults(ssid);
869         ssid->temporary = 1;
870         ssid->p2p_group = 1;
871         ssid->p2p_persistent_group = params->persistent_group;
872         ssid->mode = group_formation ? WPAS_MODE_P2P_GROUP_FORMATION :
873                 WPAS_MODE_P2P_GO;
874         ssid->frequency = params->freq;
875         ssid->ht40 = params->ht40;
876         ssid->ssid = os_zalloc(params->ssid_len + 1);
877         if (ssid->ssid) {
878                 os_memcpy(ssid->ssid, params->ssid, params->ssid_len);
879                 ssid->ssid_len = params->ssid_len;
880         }
881         ssid->auth_alg = WPA_AUTH_ALG_OPEN;
882         ssid->key_mgmt = WPA_KEY_MGMT_PSK;
883         ssid->proto = WPA_PROTO_RSN;
884         ssid->pairwise_cipher = WPA_CIPHER_CCMP;
885         ssid->passphrase = os_strdup(params->passphrase);
886         if (ssid->passphrase == NULL) {
887                 wpa_msg(wpa_s, MSG_ERROR, "P2P: Failed to copy passphrase for "
888                         "GO");
889                 wpa_config_remove_network(wpa_s->conf, ssid->id);
890                 return;
891         }
892         ssid->psk_set = params->psk_set;
893         if (ssid->psk_set)
894                 os_memcpy(ssid->psk, params->psk, sizeof(ssid->psk));
895         else
896                 wpa_config_update_psk(ssid);
897         ssid->ap_max_inactivity = wpa_s->parent->conf->p2p_go_max_inactivity;
898
899         wpa_s->ap_configured_cb = p2p_go_configured;
900         wpa_s->ap_configured_cb_ctx = wpa_s;
901         wpa_s->ap_configured_cb_data = wpa_s->go_params;
902         wpa_s->connect_without_scan = ssid;
903         wpa_s->reassociate = 1;
904         wpa_s->disconnected = 0;
905         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Request scan (that will be skipped) to "
906                 "start GO)");
907         wpa_supplicant_req_scan(wpa_s, 0, 0);
908 }
909
910
911 static void wpas_p2p_clone_config(struct wpa_supplicant *dst,
912                                   const struct wpa_supplicant *src)
913 {
914         struct wpa_config *d;
915         const struct wpa_config *s;
916
917         d = dst->conf;
918         s = src->conf;
919
920 #define C(n) if (s->n) d->n = os_strdup(s->n)
921         C(device_name);
922         C(manufacturer);
923         C(model_name);
924         C(model_number);
925         C(serial_number);
926         C(config_methods);
927 #undef C
928
929         os_memcpy(d->device_type, s->device_type, WPS_DEV_TYPE_LEN);
930         os_memcpy(d->sec_device_type, s->sec_device_type,
931                   sizeof(d->sec_device_type));
932         d->num_sec_device_types = s->num_sec_device_types;
933
934         d->p2p_group_idle = s->p2p_group_idle;
935         d->p2p_intra_bss = s->p2p_intra_bss;
936         d->persistent_reconnect = s->persistent_reconnect;
937         d->max_num_sta = s->max_num_sta;
938         d->pbc_in_m1 = s->pbc_in_m1;
939 }
940
941
942 static int wpas_p2p_add_group_interface(struct wpa_supplicant *wpa_s,
943                                         enum wpa_driver_if_type type)
944 {
945         char ifname[120], force_ifname[120];
946
947         if (wpa_s->pending_interface_name[0]) {
948                 wpa_printf(MSG_DEBUG, "P2P: Pending virtual interface exists "
949                            "- skip creation of a new one");
950                 if (is_zero_ether_addr(wpa_s->pending_interface_addr)) {
951                         wpa_printf(MSG_DEBUG, "P2P: Pending virtual address "
952                                    "unknown?! ifname='%s'",
953                                    wpa_s->pending_interface_name);
954                         return -1;
955                 }
956                 return 0;
957         }
958
959         os_snprintf(ifname, sizeof(ifname), "p2p-%s-%d", wpa_s->ifname,
960                     wpa_s->p2p_group_idx);
961         if (os_strlen(ifname) >= IFNAMSIZ &&
962             os_strlen(wpa_s->ifname) < IFNAMSIZ) {
963                 /* Try to avoid going over the IFNAMSIZ length limit */
964                 os_snprintf(ifname, sizeof(ifname), "p2p-%d",
965                             wpa_s->p2p_group_idx);
966         }
967         force_ifname[0] = '\0';
968
969         wpa_printf(MSG_DEBUG, "P2P: Create a new interface %s for the group",
970                    ifname);
971         wpa_s->p2p_group_idx++;
972
973         wpa_s->pending_interface_type = type;
974         if (wpa_drv_if_add(wpa_s, type, ifname, NULL, NULL, force_ifname,
975                            wpa_s->pending_interface_addr, NULL) < 0) {
976                 wpa_printf(MSG_ERROR, "P2P: Failed to create new group "
977                            "interface");
978                 return -1;
979         }
980
981         if (force_ifname[0]) {
982                 wpa_printf(MSG_DEBUG, "P2P: Driver forced interface name %s",
983                            force_ifname);
984                 os_strlcpy(wpa_s->pending_interface_name, force_ifname,
985                            sizeof(wpa_s->pending_interface_name));
986         } else
987                 os_strlcpy(wpa_s->pending_interface_name, ifname,
988                            sizeof(wpa_s->pending_interface_name));
989         wpa_printf(MSG_DEBUG, "P2P: Created pending virtual interface %s addr "
990                    MACSTR, wpa_s->pending_interface_name,
991                    MAC2STR(wpa_s->pending_interface_addr));
992
993         return 0;
994 }
995
996
997 static void wpas_p2p_remove_pending_group_interface(
998         struct wpa_supplicant *wpa_s)
999 {
1000         if (!wpa_s->pending_interface_name[0] ||
1001             is_zero_ether_addr(wpa_s->pending_interface_addr))
1002                 return; /* No pending virtual interface */
1003
1004         wpa_printf(MSG_DEBUG, "P2P: Removing pending group interface %s",
1005                    wpa_s->pending_interface_name);
1006         wpa_drv_if_remove(wpa_s, wpa_s->pending_interface_type,
1007                           wpa_s->pending_interface_name);
1008         os_memset(wpa_s->pending_interface_addr, 0, ETH_ALEN);
1009         wpa_s->pending_interface_name[0] = '\0';
1010 }
1011
1012
1013 static struct wpa_supplicant *
1014 wpas_p2p_init_group_interface(struct wpa_supplicant *wpa_s, int go)
1015 {
1016         struct wpa_interface iface;
1017         struct wpa_supplicant *group_wpa_s;
1018
1019         if (!wpa_s->pending_interface_name[0]) {
1020                 wpa_printf(MSG_ERROR, "P2P: No pending group interface");
1021                 if (!wpas_p2p_create_iface(wpa_s))
1022                         return NULL;
1023                 /*
1024                  * Something has forced us to remove the pending interface; try
1025                  * to create a new one and hope for the best that we will get
1026                  * the same local address.
1027                  */
1028                 if (wpas_p2p_add_group_interface(wpa_s, go ? WPA_IF_P2P_GO :
1029                                                  WPA_IF_P2P_CLIENT) < 0)
1030                         return NULL;
1031         }
1032
1033         os_memset(&iface, 0, sizeof(iface));
1034         iface.ifname = wpa_s->pending_interface_name;
1035         iface.driver = wpa_s->driver->name;
1036         iface.ctrl_interface = wpa_s->conf->ctrl_interface;
1037         iface.driver_param = wpa_s->conf->driver_param;
1038         group_wpa_s = wpa_supplicant_add_iface(wpa_s->global, &iface);
1039         if (group_wpa_s == NULL) {
1040                 wpa_printf(MSG_ERROR, "P2P: Failed to create new "
1041                            "wpa_supplicant interface");
1042                 return NULL;
1043         }
1044         wpa_s->pending_interface_name[0] = '\0';
1045         group_wpa_s->parent = wpa_s;
1046         group_wpa_s->p2p_group_interface = go ? P2P_GROUP_INTERFACE_GO :
1047                 P2P_GROUP_INTERFACE_CLIENT;
1048         wpa_s->global->p2p_group_formation = group_wpa_s;
1049
1050         wpas_p2p_clone_config(group_wpa_s, wpa_s);
1051
1052         return group_wpa_s;
1053 }
1054
1055
1056 static void wpas_p2p_group_formation_timeout(void *eloop_ctx,
1057                                              void *timeout_ctx)
1058 {
1059         struct wpa_supplicant *wpa_s = eloop_ctx;
1060         wpa_printf(MSG_DEBUG, "P2P: Group Formation timed out");
1061         if (wpa_s->global->p2p)
1062                 p2p_group_formation_failed(wpa_s->global->p2p);
1063         else if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
1064                 wpa_drv_p2p_group_formation_failed(wpa_s);
1065         wpas_group_formation_completed(wpa_s, 0);
1066 }
1067
1068
1069 void wpas_go_neg_completed(void *ctx, struct p2p_go_neg_results *res)
1070 {
1071         struct wpa_supplicant *wpa_s = ctx;
1072
1073         if (wpa_s->off_channel_freq || wpa_s->roc_waiting_drv_freq) {
1074                 wpa_drv_cancel_remain_on_channel(wpa_s);
1075                 wpa_s->off_channel_freq = 0;
1076                 wpa_s->roc_waiting_drv_freq = 0;
1077         }
1078
1079         if (res->status) {
1080                 wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_GO_NEG_FAILURE "status=%d",
1081                         res->status);
1082                 wpas_notify_p2p_go_neg_completed(wpa_s, res);
1083                 wpas_p2p_remove_pending_group_interface(wpa_s);
1084                 return;
1085         }
1086
1087         if (wpa_s->p2p_go_ht40)
1088                 res->ht40 = 1;
1089
1090         wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_GO_NEG_SUCCESS);
1091         wpas_notify_p2p_go_neg_completed(wpa_s, res);
1092
1093         if (res->role_go && wpa_s->p2p_persistent_id >= 0) {
1094                 struct wpa_ssid *ssid;
1095                 ssid = wpa_config_get_network(wpa_s->conf,
1096                                               wpa_s->p2p_persistent_id);
1097                 if (ssid && ssid->disabled == 2 &&
1098                     ssid->mode == WPAS_MODE_P2P_GO && ssid->passphrase) {
1099                         size_t len = os_strlen(ssid->passphrase);
1100                         wpa_printf(MSG_DEBUG, "P2P: Override passphrase based "
1101                                    "on requested persistent group");
1102                         os_memcpy(res->passphrase, ssid->passphrase, len);
1103                         res->passphrase[len] = '\0';
1104                 }
1105         }
1106
1107         if (wpa_s->create_p2p_iface) {
1108                 struct wpa_supplicant *group_wpa_s =
1109                         wpas_p2p_init_group_interface(wpa_s, res->role_go);
1110                 if (group_wpa_s == NULL) {
1111                         wpas_p2p_remove_pending_group_interface(wpa_s);
1112                         return;
1113                 }
1114                 if (group_wpa_s != wpa_s) {
1115                         os_memcpy(group_wpa_s->p2p_pin, wpa_s->p2p_pin,
1116                                   sizeof(group_wpa_s->p2p_pin));
1117                         group_wpa_s->p2p_wps_method = wpa_s->p2p_wps_method;
1118                 }
1119                 os_memset(wpa_s->pending_interface_addr, 0, ETH_ALEN);
1120                 wpa_s->pending_interface_name[0] = '\0';
1121                 group_wpa_s->p2p_in_provisioning = 1;
1122
1123                 if (res->role_go)
1124                         wpas_start_wps_go(group_wpa_s, res, 1);
1125                 else
1126                         wpas_start_wps_enrollee(group_wpa_s, res);
1127         } else {
1128                 wpa_s->p2p_in_provisioning = 1;
1129                 wpa_s->global->p2p_group_formation = wpa_s;
1130
1131                 if (res->role_go)
1132                         wpas_start_wps_go(wpa_s, res, 1);
1133                 else
1134                         wpas_start_wps_enrollee(ctx, res);
1135         }
1136
1137         wpa_s->p2p_long_listen = 0;
1138         eloop_cancel_timeout(wpas_p2p_long_listen_timeout, wpa_s, NULL);
1139
1140         eloop_cancel_timeout(wpas_p2p_group_formation_timeout, wpa_s, NULL);
1141         eloop_register_timeout(15 + res->peer_config_timeout / 100,
1142                                (res->peer_config_timeout % 100) * 10000,
1143                                wpas_p2p_group_formation_timeout, wpa_s, NULL);
1144 }
1145
1146
1147 void wpas_go_neg_req_rx(void *ctx, const u8 *src, u16 dev_passwd_id)
1148 {
1149         struct wpa_supplicant *wpa_s = ctx;
1150         wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_GO_NEG_REQUEST MACSTR
1151                 " dev_passwd_id=%u", MAC2STR(src), dev_passwd_id);
1152
1153         wpas_notify_p2p_go_neg_req(wpa_s, src, dev_passwd_id);
1154 }
1155
1156
1157 void wpas_dev_found(void *ctx, const u8 *addr,
1158                     const struct p2p_peer_info *info,
1159                     int new_device)
1160 {
1161 #ifndef CONFIG_NO_STDOUT_DEBUG
1162         struct wpa_supplicant *wpa_s = ctx;
1163         char devtype[WPS_DEV_TYPE_BUFSIZE];
1164
1165         wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_DEVICE_FOUND MACSTR
1166                 " p2p_dev_addr=" MACSTR
1167                 " pri_dev_type=%s name='%s' config_methods=0x%x "
1168                 "dev_capab=0x%x group_capab=0x%x",
1169                 MAC2STR(addr), MAC2STR(info->p2p_device_addr),
1170                 wps_dev_type_bin2str(info->pri_dev_type, devtype,
1171                                      sizeof(devtype)),
1172                 info->device_name, info->config_methods,
1173                 info->dev_capab, info->group_capab);
1174 #endif /* CONFIG_NO_STDOUT_DEBUG */
1175
1176         wpas_notify_p2p_device_found(ctx, info->p2p_device_addr, new_device);
1177 }
1178
1179
1180 static void wpas_dev_lost(void *ctx, const u8 *dev_addr)
1181 {
1182         struct wpa_supplicant *wpa_s = ctx;
1183
1184         wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_DEVICE_LOST
1185                 "p2p_dev_addr=" MACSTR, MAC2STR(dev_addr));
1186
1187         wpas_notify_p2p_device_lost(wpa_s, dev_addr);
1188 }
1189
1190
1191 static int wpas_start_listen(void *ctx, unsigned int freq,
1192                              unsigned int duration,
1193                              const struct wpabuf *probe_resp_ie)
1194 {
1195         struct wpa_supplicant *wpa_s = ctx;
1196
1197         wpa_drv_set_ap_wps_ie(wpa_s, NULL, probe_resp_ie, NULL);
1198
1199         if (wpa_drv_probe_req_report(wpa_s, 1) < 0) {
1200                 wpa_printf(MSG_DEBUG, "P2P: Failed to request the driver to "
1201                            "report received Probe Request frames");
1202                 return -1;
1203         }
1204
1205         wpa_s->pending_listen_freq = freq;
1206         wpa_s->pending_listen_duration = duration;
1207
1208         if (wpa_drv_remain_on_channel(wpa_s, freq, duration) < 0) {
1209                 wpa_printf(MSG_DEBUG, "P2P: Failed to request the driver "
1210                            "to remain on channel (%u MHz) for Listen "
1211                            "state", freq);
1212                 wpa_s->pending_listen_freq = 0;
1213                 return -1;
1214         }
1215         wpa_s->off_channel_freq = 0;
1216         wpa_s->roc_waiting_drv_freq = freq;
1217
1218         return 0;
1219 }
1220
1221
1222 static void wpas_stop_listen(void *ctx)
1223 {
1224         struct wpa_supplicant *wpa_s = ctx;
1225         if (wpa_s->off_channel_freq || wpa_s->roc_waiting_drv_freq) {
1226                 wpa_drv_cancel_remain_on_channel(wpa_s);
1227                 wpa_s->off_channel_freq = 0;
1228                 wpa_s->roc_waiting_drv_freq = 0;
1229         }
1230         wpa_drv_set_ap_wps_ie(wpa_s, NULL, NULL, NULL);
1231         wpa_drv_probe_req_report(wpa_s, 0);
1232 }
1233
1234
1235 static int wpas_send_probe_resp(void *ctx, const struct wpabuf *buf)
1236 {
1237         struct wpa_supplicant *wpa_s = ctx;
1238         return wpa_drv_send_mlme(wpa_s, wpabuf_head(buf), wpabuf_len(buf), 1);
1239 }
1240
1241
1242 /*
1243  * DNS Header section is used only to calculate compression pointers, so the
1244  * contents of this data does not matter, but the length needs to be reserved
1245  * in the virtual packet.
1246  */
1247 #define DNS_HEADER_LEN 12
1248
1249 /*
1250  * 27-octet in-memory packet from P2P specification containing two implied
1251  * queries for _tcp.lcoal. PTR IN and _udp.local. PTR IN
1252  */
1253 #define P2P_SD_IN_MEMORY_LEN 27
1254
1255 static int p2p_sd_dns_uncompress_label(char **upos, char *uend, u8 *start,
1256                                        u8 **spos, const u8 *end)
1257 {
1258         while (*spos < end) {
1259                 u8 val = ((*spos)[0] & 0xc0) >> 6;
1260                 int len;
1261
1262                 if (val == 1 || val == 2) {
1263                         /* These are reserved values in RFC 1035 */
1264                         wpa_printf(MSG_DEBUG, "P2P: Invalid domain name "
1265                                    "sequence starting with 0x%x", val);
1266                         return -1;
1267                 }
1268
1269                 if (val == 3) {
1270                         u16 offset;
1271                         u8 *spos_tmp;
1272
1273                         /* Offset */
1274                         if (*spos + 2 > end) {
1275                                 wpa_printf(MSG_DEBUG, "P2P: No room for full "
1276                                            "DNS offset field");
1277                                 return -1;
1278                         }
1279
1280                         offset = (((*spos)[0] & 0x3f) << 8) | (*spos)[1];
1281                         if (offset >= *spos - start) {
1282                                 wpa_printf(MSG_DEBUG, "P2P: Invalid DNS "
1283                                            "pointer offset %u", offset);
1284                                 return -1;
1285                         }
1286
1287                         (*spos) += 2;
1288                         spos_tmp = start + offset;
1289                         return p2p_sd_dns_uncompress_label(upos, uend, start,
1290                                                            &spos_tmp,
1291                                                            *spos - 2);
1292                 }
1293
1294                 /* Label */
1295                 len = (*spos)[0] & 0x3f;
1296                 if (len == 0)
1297                         return 0;
1298
1299                 (*spos)++;
1300                 if (*spos + len > end) {
1301                         wpa_printf(MSG_DEBUG, "P2P: Invalid domain name "
1302                                    "sequence - no room for label with length "
1303                                    "%u", len);
1304                         return -1;
1305                 }
1306
1307                 if (*upos + len + 2 > uend)
1308                         return -2;
1309
1310                 os_memcpy(*upos, *spos, len);
1311                 *spos += len;
1312                 *upos += len;
1313                 (*upos)[0] = '.';
1314                 (*upos)++;
1315                 (*upos)[0] = '\0';
1316         }
1317
1318         return 0;
1319 }
1320
1321
1322 /* Uncompress domain names per RFC 1035 using the P2P SD in-memory packet.
1323  * Returns -1 on parsing error (invalid input sequence), -2 if output buffer is
1324  * not large enough */
1325 static int p2p_sd_dns_uncompress(char *buf, size_t buf_len, const u8 *msg,
1326                                  size_t msg_len, size_t offset)
1327 {
1328         /* 27-octet in-memory packet from P2P specification */
1329         const char *prefix = "\x04_tcp\x05local\x00\x00\x0C\x00\x01"
1330                 "\x04_udp\xC0\x11\x00\x0C\x00\x01";
1331         u8 *tmp, *end, *spos;
1332         char *upos, *uend;
1333         int ret = 0;
1334
1335         if (buf_len < 2)
1336                 return -1;
1337         if (offset > msg_len)
1338                 return -1;
1339
1340         tmp = os_malloc(DNS_HEADER_LEN + P2P_SD_IN_MEMORY_LEN + msg_len);
1341         if (tmp == NULL)
1342                 return -1;
1343         spos = tmp + DNS_HEADER_LEN + P2P_SD_IN_MEMORY_LEN;
1344         end = spos + msg_len;
1345         spos += offset;
1346
1347         os_memset(tmp, 0, DNS_HEADER_LEN);
1348         os_memcpy(tmp + DNS_HEADER_LEN, prefix, P2P_SD_IN_MEMORY_LEN);
1349         os_memcpy(tmp + DNS_HEADER_LEN + P2P_SD_IN_MEMORY_LEN, msg, msg_len);
1350
1351         upos = buf;
1352         uend = buf + buf_len;
1353
1354         ret = p2p_sd_dns_uncompress_label(&upos, uend, tmp, &spos, end);
1355         if (ret) {
1356                 os_free(tmp);
1357                 return ret;
1358         }
1359
1360         if (upos == buf) {
1361                 upos[0] = '.';
1362                 upos[1] = '\0';
1363         } else if (upos[-1] == '.')
1364                 upos[-1] = '\0';
1365
1366         os_free(tmp);
1367         return 0;
1368 }
1369
1370
1371 static struct p2p_srv_bonjour *
1372 wpas_p2p_service_get_bonjour(struct wpa_supplicant *wpa_s,
1373                              const struct wpabuf *query)
1374 {
1375         struct p2p_srv_bonjour *bsrv;
1376         size_t len;
1377
1378         len = wpabuf_len(query);
1379         dl_list_for_each(bsrv, &wpa_s->global->p2p_srv_bonjour,
1380                          struct p2p_srv_bonjour, list) {
1381                 if (len == wpabuf_len(bsrv->query) &&
1382                     os_memcmp(wpabuf_head(query), wpabuf_head(bsrv->query),
1383                               len) == 0)
1384                         return bsrv;
1385         }
1386         return NULL;
1387 }
1388
1389
1390 static struct p2p_srv_upnp *
1391 wpas_p2p_service_get_upnp(struct wpa_supplicant *wpa_s, u8 version,
1392                           const char *service)
1393 {
1394         struct p2p_srv_upnp *usrv;
1395
1396         dl_list_for_each(usrv, &wpa_s->global->p2p_srv_upnp,
1397                          struct p2p_srv_upnp, list) {
1398                 if (version == usrv->version &&
1399                     os_strcmp(service, usrv->service) == 0)
1400                         return usrv;
1401         }
1402         return NULL;
1403 }
1404
1405
1406 static void wpas_sd_add_proto_not_avail(struct wpabuf *resp, u8 srv_proto,
1407                                         u8 srv_trans_id)
1408 {
1409         u8 *len_pos;
1410
1411         if (wpabuf_tailroom(resp) < 5)
1412                 return;
1413
1414         /* Length (to be filled) */
1415         len_pos = wpabuf_put(resp, 2);
1416         wpabuf_put_u8(resp, srv_proto);
1417         wpabuf_put_u8(resp, srv_trans_id);
1418         /* Status Code */
1419         wpabuf_put_u8(resp, P2P_SD_PROTO_NOT_AVAILABLE);
1420         /* Response Data: empty */
1421         WPA_PUT_LE16(len_pos, (u8 *) wpabuf_put(resp, 0) - len_pos - 2);
1422 }
1423
1424
1425 static void wpas_sd_all_bonjour(struct wpa_supplicant *wpa_s,
1426                                 struct wpabuf *resp, u8 srv_trans_id)
1427 {
1428         struct p2p_srv_bonjour *bsrv;
1429         u8 *len_pos;
1430
1431         wpa_printf(MSG_DEBUG, "P2P: SD Request for all Bonjour services");
1432
1433         if (dl_list_empty(&wpa_s->global->p2p_srv_bonjour)) {
1434                 wpa_printf(MSG_DEBUG, "P2P: Bonjour protocol not available");
1435                 return;
1436         }
1437
1438         dl_list_for_each(bsrv, &wpa_s->global->p2p_srv_bonjour,
1439                          struct p2p_srv_bonjour, list) {
1440                 if (wpabuf_tailroom(resp) <
1441                     5 + wpabuf_len(bsrv->query) + wpabuf_len(bsrv->resp))
1442                         return;
1443                 /* Length (to be filled) */
1444                 len_pos = wpabuf_put(resp, 2);
1445                 wpabuf_put_u8(resp, P2P_SERV_BONJOUR);
1446                 wpabuf_put_u8(resp, srv_trans_id);
1447                 /* Status Code */
1448                 wpabuf_put_u8(resp, P2P_SD_SUCCESS);
1449                 wpa_hexdump_ascii(MSG_DEBUG, "P2P: Matching Bonjour service",
1450                                   wpabuf_head(bsrv->resp),
1451                                   wpabuf_len(bsrv->resp));
1452                 /* Response Data */
1453                 wpabuf_put_buf(resp, bsrv->query); /* Key */
1454                 wpabuf_put_buf(resp, bsrv->resp); /* Value */
1455                 WPA_PUT_LE16(len_pos, (u8 *) wpabuf_put(resp, 0) - len_pos -
1456                              2);
1457         }
1458 }
1459
1460
1461 static int match_bonjour_query(struct p2p_srv_bonjour *bsrv, const u8 *query,
1462                                size_t query_len)
1463 {
1464         char str_rx[256], str_srv[256];
1465
1466         if (query_len < 3 || wpabuf_len(bsrv->query) < 3)
1467                 return 0; /* Too short to include DNS Type and Version */
1468         if (os_memcmp(query + query_len - 3,
1469                       wpabuf_head_u8(bsrv->query) + wpabuf_len(bsrv->query) - 3,
1470                       3) != 0)
1471                 return 0; /* Mismatch in DNS Type or Version */
1472         if (query_len == wpabuf_len(bsrv->query) &&
1473             os_memcmp(query, wpabuf_head(bsrv->query), query_len - 3) == 0)
1474                 return 1; /* Binary match */
1475
1476         if (p2p_sd_dns_uncompress(str_rx, sizeof(str_rx), query, query_len - 3,
1477                                   0))
1478                 return 0; /* Failed to uncompress query */
1479         if (p2p_sd_dns_uncompress(str_srv, sizeof(str_srv),
1480                                   wpabuf_head(bsrv->query),
1481                                   wpabuf_len(bsrv->query) - 3, 0))
1482                 return 0; /* Failed to uncompress service */
1483
1484         return os_strcmp(str_rx, str_srv) == 0;
1485 }
1486
1487
1488 static void wpas_sd_req_bonjour(struct wpa_supplicant *wpa_s,
1489                                 struct wpabuf *resp, u8 srv_trans_id,
1490                                 const u8 *query, size_t query_len)
1491 {
1492         struct p2p_srv_bonjour *bsrv;
1493         u8 *len_pos;
1494         int matches = 0;
1495
1496         wpa_hexdump_ascii(MSG_DEBUG, "P2P: SD Request for Bonjour",
1497                           query, query_len);
1498         if (dl_list_empty(&wpa_s->global->p2p_srv_bonjour)) {
1499                 wpa_printf(MSG_DEBUG, "P2P: Bonjour protocol not available");
1500                 wpas_sd_add_proto_not_avail(resp, P2P_SERV_BONJOUR,
1501                                             srv_trans_id);
1502                 return;
1503         }
1504
1505         if (query_len == 0) {
1506                 wpas_sd_all_bonjour(wpa_s, resp, srv_trans_id);
1507                 return;
1508         }
1509
1510         dl_list_for_each(bsrv, &wpa_s->global->p2p_srv_bonjour,
1511                          struct p2p_srv_bonjour, list) {
1512                 if (!match_bonjour_query(bsrv, query, query_len))
1513                         continue;
1514
1515                 if (wpabuf_tailroom(resp) <
1516                     5 + query_len + wpabuf_len(bsrv->resp))
1517                         return;
1518
1519                 matches++;
1520
1521                 /* Length (to be filled) */
1522                 len_pos = wpabuf_put(resp, 2);
1523                 wpabuf_put_u8(resp, P2P_SERV_BONJOUR);
1524                 wpabuf_put_u8(resp, srv_trans_id);
1525
1526                 /* Status Code */
1527                 wpabuf_put_u8(resp, P2P_SD_SUCCESS);
1528                 wpa_hexdump_ascii(MSG_DEBUG, "P2P: Matching Bonjour service",
1529                                   wpabuf_head(bsrv->resp),
1530                                   wpabuf_len(bsrv->resp));
1531
1532                 /* Response Data */
1533                 wpabuf_put_data(resp, query, query_len); /* Key */
1534                 wpabuf_put_buf(resp, bsrv->resp); /* Value */
1535
1536                 WPA_PUT_LE16(len_pos, (u8 *) wpabuf_put(resp, 0) - len_pos - 2);
1537         }
1538
1539         if (matches == 0) {
1540                 wpa_printf(MSG_DEBUG, "P2P: Requested Bonjour service not "
1541                            "available");
1542                 if (wpabuf_tailroom(resp) < 5)
1543                         return;
1544
1545                 /* Length (to be filled) */
1546                 len_pos = wpabuf_put(resp, 2);
1547                 wpabuf_put_u8(resp, P2P_SERV_BONJOUR);
1548                 wpabuf_put_u8(resp, srv_trans_id);
1549
1550                 /* Status Code */
1551                 wpabuf_put_u8(resp, P2P_SD_REQUESTED_INFO_NOT_AVAILABLE);
1552                 /* Response Data: empty */
1553                 WPA_PUT_LE16(len_pos, (u8 *) wpabuf_put(resp, 0) - len_pos -
1554                              2);
1555         }
1556 }
1557
1558
1559 static void wpas_sd_all_upnp(struct wpa_supplicant *wpa_s,
1560                              struct wpabuf *resp, u8 srv_trans_id)
1561 {
1562         struct p2p_srv_upnp *usrv;
1563         u8 *len_pos;
1564
1565         wpa_printf(MSG_DEBUG, "P2P: SD Request for all UPnP services");
1566
1567         if (dl_list_empty(&wpa_s->global->p2p_srv_upnp)) {
1568                 wpa_printf(MSG_DEBUG, "P2P: UPnP protocol not available");
1569                 return;
1570         }
1571
1572         dl_list_for_each(usrv, &wpa_s->global->p2p_srv_upnp,
1573                          struct p2p_srv_upnp, list) {
1574                 if (wpabuf_tailroom(resp) < 5 + 1 + os_strlen(usrv->service))
1575                         return;
1576
1577                 /* Length (to be filled) */
1578                 len_pos = wpabuf_put(resp, 2);
1579                 wpabuf_put_u8(resp, P2P_SERV_UPNP);
1580                 wpabuf_put_u8(resp, srv_trans_id);
1581
1582                 /* Status Code */
1583                 wpabuf_put_u8(resp, P2P_SD_SUCCESS);
1584                 /* Response Data */
1585                 wpabuf_put_u8(resp, usrv->version);
1586                 wpa_printf(MSG_DEBUG, "P2P: Matching UPnP Service: %s",
1587                            usrv->service);
1588                 wpabuf_put_str(resp, usrv->service);
1589                 WPA_PUT_LE16(len_pos, (u8 *) wpabuf_put(resp, 0) - len_pos -
1590                              2);
1591         }
1592 }
1593
1594
1595 static void wpas_sd_req_upnp(struct wpa_supplicant *wpa_s,
1596                              struct wpabuf *resp, u8 srv_trans_id,
1597                              const u8 *query, size_t query_len)
1598 {
1599         struct p2p_srv_upnp *usrv;
1600         u8 *len_pos;
1601         u8 version;
1602         char *str;
1603         int count = 0;
1604
1605         wpa_hexdump_ascii(MSG_DEBUG, "P2P: SD Request for UPnP",
1606                           query, query_len);
1607
1608         if (dl_list_empty(&wpa_s->global->p2p_srv_upnp)) {
1609                 wpa_printf(MSG_DEBUG, "P2P: UPnP protocol not available");
1610                 wpas_sd_add_proto_not_avail(resp, P2P_SERV_UPNP,
1611                                             srv_trans_id);
1612                 return;
1613         }
1614
1615         if (query_len == 0) {
1616                 wpas_sd_all_upnp(wpa_s, resp, srv_trans_id);
1617                 return;
1618         }
1619
1620         if (wpabuf_tailroom(resp) < 5)
1621                 return;
1622
1623         /* Length (to be filled) */
1624         len_pos = wpabuf_put(resp, 2);
1625         wpabuf_put_u8(resp, P2P_SERV_UPNP);
1626         wpabuf_put_u8(resp, srv_trans_id);
1627
1628         version = query[0];
1629         str = os_malloc(query_len);
1630         if (str == NULL)
1631                 return;
1632         os_memcpy(str, query + 1, query_len - 1);
1633         str[query_len - 1] = '\0';
1634
1635         dl_list_for_each(usrv, &wpa_s->global->p2p_srv_upnp,
1636                          struct p2p_srv_upnp, list) {
1637                 if (version != usrv->version)
1638                         continue;
1639
1640                 if (os_strcmp(str, "ssdp:all") != 0 &&
1641                     os_strstr(usrv->service, str) == NULL)
1642                         continue;
1643
1644                 if (wpabuf_tailroom(resp) < 2)
1645                         break;
1646                 if (count == 0) {
1647                         /* Status Code */
1648                         wpabuf_put_u8(resp, P2P_SD_SUCCESS);
1649                         /* Response Data */
1650                         wpabuf_put_u8(resp, version);
1651                 } else
1652                         wpabuf_put_u8(resp, ',');
1653
1654                 count++;
1655
1656                 wpa_printf(MSG_DEBUG, "P2P: Matching UPnP Service: %s",
1657                            usrv->service);
1658                 if (wpabuf_tailroom(resp) < os_strlen(usrv->service))
1659                         break;
1660                 wpabuf_put_str(resp, usrv->service);
1661         }
1662         os_free(str);
1663
1664         if (count == 0) {
1665                 wpa_printf(MSG_DEBUG, "P2P: Requested UPnP service not "
1666                            "available");
1667                 /* Status Code */
1668                 wpabuf_put_u8(resp, P2P_SD_REQUESTED_INFO_NOT_AVAILABLE);
1669                 /* Response Data: empty */
1670         }
1671
1672         WPA_PUT_LE16(len_pos, (u8 *) wpabuf_put(resp, 0) - len_pos - 2);
1673 }
1674
1675
1676 #ifdef CONFIG_WIFI_DISPLAY
1677 static void wpas_sd_req_wfd(struct wpa_supplicant *wpa_s,
1678                             struct wpabuf *resp, u8 srv_trans_id,
1679                             const u8 *query, size_t query_len)
1680 {
1681         const u8 *pos;
1682         u8 role;
1683         u8 *len_pos;
1684
1685         wpa_hexdump(MSG_DEBUG, "P2P: SD Request for WFD", query, query_len);
1686
1687         if (!wpa_s->global->wifi_display) {
1688                 wpa_printf(MSG_DEBUG, "P2P: WFD protocol not available");
1689                 wpas_sd_add_proto_not_avail(resp, P2P_SERV_WIFI_DISPLAY,
1690                                             srv_trans_id);
1691                 return;
1692         }
1693
1694         if (query_len < 1) {
1695                 wpa_printf(MSG_DEBUG, "P2P: Missing WFD Requested Device "
1696                            "Role");
1697                 return;
1698         }
1699
1700         if (wpabuf_tailroom(resp) < 5)
1701                 return;
1702
1703         pos = query;
1704         role = *pos++;
1705         wpa_printf(MSG_DEBUG, "P2P: WSD for device role 0x%x", role);
1706
1707         /* TODO: role specific handling */
1708
1709         /* Length (to be filled) */
1710         len_pos = wpabuf_put(resp, 2);
1711         wpabuf_put_u8(resp, P2P_SERV_WIFI_DISPLAY);
1712         wpabuf_put_u8(resp, srv_trans_id);
1713         wpabuf_put_u8(resp, P2P_SD_SUCCESS); /* Status Code */
1714
1715         while (pos < query + query_len) {
1716                 if (*pos < MAX_WFD_SUBELEMS &&
1717                     wpa_s->global->wfd_subelem[*pos] &&
1718                     wpabuf_tailroom(resp) >=
1719                     wpabuf_len(wpa_s->global->wfd_subelem[*pos])) {
1720                         wpa_printf(MSG_DEBUG, "P2P: Add WSD response "
1721                                    "subelement %u", *pos);
1722                         wpabuf_put_buf(resp, wpa_s->global->wfd_subelem[*pos]);
1723                 }
1724                 pos++;
1725         }
1726
1727         WPA_PUT_LE16(len_pos, (u8 *) wpabuf_put(resp, 0) - len_pos - 2);
1728 }
1729 #endif /* CONFIG_WIFI_DISPLAY */
1730
1731
1732 void wpas_sd_request(void *ctx, int freq, const u8 *sa, u8 dialog_token,
1733                      u16 update_indic, const u8 *tlvs, size_t tlvs_len)
1734 {
1735         struct wpa_supplicant *wpa_s = ctx;
1736         const u8 *pos = tlvs;
1737         const u8 *end = tlvs + tlvs_len;
1738         const u8 *tlv_end;
1739         u16 slen;
1740         struct wpabuf *resp;
1741         u8 srv_proto, srv_trans_id;
1742         size_t buf_len;
1743         char *buf;
1744
1745         wpa_hexdump(MSG_MSGDUMP, "P2P: Service Discovery Request TLVs",
1746                     tlvs, tlvs_len);
1747         buf_len = 2 * tlvs_len + 1;
1748         buf = os_malloc(buf_len);
1749         if (buf) {
1750                 wpa_snprintf_hex(buf, buf_len, tlvs, tlvs_len);
1751                 wpa_msg_ctrl(wpa_s, MSG_INFO, P2P_EVENT_SERV_DISC_REQ "%d "
1752                              MACSTR " %u %u %s",
1753                              freq, MAC2STR(sa), dialog_token, update_indic,
1754                              buf);
1755                 os_free(buf);
1756         }
1757
1758         if (wpa_s->p2p_sd_over_ctrl_iface) {
1759                 wpas_notify_p2p_sd_request(wpa_s, freq, sa, dialog_token,
1760                                            update_indic, tlvs, tlvs_len);
1761                 return; /* to be processed by an external program */
1762         }
1763
1764         resp = wpabuf_alloc(10000);
1765         if (resp == NULL)
1766                 return;
1767
1768         while (pos + 1 < end) {
1769                 wpa_printf(MSG_DEBUG, "P2P: Service Request TLV");
1770                 slen = WPA_GET_LE16(pos);
1771                 pos += 2;
1772                 if (pos + slen > end || slen < 2) {
1773                         wpa_printf(MSG_DEBUG, "P2P: Unexpected Query Data "
1774                                    "length");
1775                         wpabuf_free(resp);
1776                         return;
1777                 }
1778                 tlv_end = pos + slen;
1779
1780                 srv_proto = *pos++;
1781                 wpa_printf(MSG_DEBUG, "P2P: Service Protocol Type %u",
1782                            srv_proto);
1783                 srv_trans_id = *pos++;
1784                 wpa_printf(MSG_DEBUG, "P2P: Service Transaction ID %u",
1785                            srv_trans_id);
1786
1787                 wpa_hexdump(MSG_MSGDUMP, "P2P: Query Data",
1788                             pos, tlv_end - pos);
1789
1790
1791                 if (wpa_s->force_long_sd) {
1792                         wpa_printf(MSG_DEBUG, "P2P: SD test - force long "
1793                                    "response");
1794                         wpas_sd_all_bonjour(wpa_s, resp, srv_trans_id);
1795                         wpas_sd_all_upnp(wpa_s, resp, srv_trans_id);
1796                         goto done;
1797                 }
1798
1799                 switch (srv_proto) {
1800                 case P2P_SERV_ALL_SERVICES:
1801                         wpa_printf(MSG_DEBUG, "P2P: Service Discovery Request "
1802                                    "for all services");
1803                         if (dl_list_empty(&wpa_s->global->p2p_srv_upnp) &&
1804                             dl_list_empty(&wpa_s->global->p2p_srv_bonjour)) {
1805                                 wpa_printf(MSG_DEBUG, "P2P: No service "
1806                                            "discovery protocols available");
1807                                 wpas_sd_add_proto_not_avail(
1808                                         resp, P2P_SERV_ALL_SERVICES,
1809                                         srv_trans_id);
1810                                 break;
1811                         }
1812                         wpas_sd_all_bonjour(wpa_s, resp, srv_trans_id);
1813                         wpas_sd_all_upnp(wpa_s, resp, srv_trans_id);
1814                         break;
1815                 case P2P_SERV_BONJOUR:
1816                         wpas_sd_req_bonjour(wpa_s, resp, srv_trans_id,
1817                                             pos, tlv_end - pos);
1818                         break;
1819                 case P2P_SERV_UPNP:
1820                         wpas_sd_req_upnp(wpa_s, resp, srv_trans_id,
1821                                          pos, tlv_end - pos);
1822                         break;
1823 #ifdef CONFIG_WIFI_DISPLAY
1824                 case P2P_SERV_WIFI_DISPLAY:
1825                         wpas_sd_req_wfd(wpa_s, resp, srv_trans_id,
1826                                         pos, tlv_end - pos);
1827                         break;
1828 #endif /* CONFIG_WIFI_DISPLAY */
1829                 default:
1830                         wpa_printf(MSG_DEBUG, "P2P: Unavailable service "
1831                                    "protocol %u", srv_proto);
1832                         wpas_sd_add_proto_not_avail(resp, srv_proto,
1833                                                     srv_trans_id);
1834                         break;
1835                 }
1836
1837                 pos = tlv_end;
1838         }
1839
1840 done:
1841         wpas_notify_p2p_sd_request(wpa_s, freq, sa, dialog_token,
1842                                    update_indic, tlvs, tlvs_len);
1843
1844         wpas_p2p_sd_response(wpa_s, freq, sa, dialog_token, resp);
1845
1846         wpabuf_free(resp);
1847 }
1848
1849
1850 void wpas_sd_response(void *ctx, const u8 *sa, u16 update_indic,
1851                       const u8 *tlvs, size_t tlvs_len)
1852 {
1853         struct wpa_supplicant *wpa_s = ctx;
1854         const u8 *pos = tlvs;
1855         const u8 *end = tlvs + tlvs_len;
1856         const u8 *tlv_end;
1857         u16 slen;
1858         size_t buf_len;
1859         char *buf;
1860
1861         wpa_hexdump(MSG_MSGDUMP, "P2P: Service Discovery Response TLVs",
1862                     tlvs, tlvs_len);
1863         if (tlvs_len > 1500) {
1864                 /* TODO: better way for handling this */
1865                 wpa_msg_ctrl(wpa_s, MSG_INFO,
1866                              P2P_EVENT_SERV_DISC_RESP MACSTR
1867                              " %u <long response: %u bytes>",
1868                              MAC2STR(sa), update_indic,
1869                              (unsigned int) tlvs_len);
1870         } else {
1871                 buf_len = 2 * tlvs_len + 1;
1872                 buf = os_malloc(buf_len);
1873                 if (buf) {
1874                         wpa_snprintf_hex(buf, buf_len, tlvs, tlvs_len);
1875                         wpa_msg_ctrl(wpa_s, MSG_INFO,
1876                                      P2P_EVENT_SERV_DISC_RESP MACSTR " %u %s",
1877                                      MAC2STR(sa), update_indic, buf);
1878                         os_free(buf);
1879                 }
1880         }
1881
1882         while (pos < end) {
1883                 u8 srv_proto, srv_trans_id, status;
1884
1885                 wpa_printf(MSG_DEBUG, "P2P: Service Response TLV");
1886                 slen = WPA_GET_LE16(pos);
1887                 pos += 2;
1888                 if (pos + slen > end || slen < 3) {
1889                         wpa_printf(MSG_DEBUG, "P2P: Unexpected Response Data "
1890                                    "length");
1891                         return;
1892                 }
1893                 tlv_end = pos + slen;
1894
1895                 srv_proto = *pos++;
1896                 wpa_printf(MSG_DEBUG, "P2P: Service Protocol Type %u",
1897                            srv_proto);
1898                 srv_trans_id = *pos++;
1899                 wpa_printf(MSG_DEBUG, "P2P: Service Transaction ID %u",
1900                            srv_trans_id);
1901                 status = *pos++;
1902                 wpa_printf(MSG_DEBUG, "P2P: Status Code ID %u",
1903                            status);
1904
1905                 wpa_hexdump(MSG_MSGDUMP, "P2P: Response Data",
1906                             pos, tlv_end - pos);
1907
1908                 pos = tlv_end;
1909         }
1910
1911         wpas_notify_p2p_sd_response(wpa_s, sa, update_indic, tlvs, tlvs_len);
1912 }
1913
1914
1915 u64 wpas_p2p_sd_request(struct wpa_supplicant *wpa_s, const u8 *dst,
1916                         const struct wpabuf *tlvs)
1917 {
1918         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
1919                 return wpa_drv_p2p_sd_request(wpa_s, dst, tlvs);
1920         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
1921                 return 0;
1922         return (uintptr_t) p2p_sd_request(wpa_s->global->p2p, dst, tlvs);
1923 }
1924
1925
1926 u64 wpas_p2p_sd_request_upnp(struct wpa_supplicant *wpa_s, const u8 *dst,
1927                              u8 version, const char *query)
1928 {
1929         struct wpabuf *tlvs;
1930         u64 ret;
1931
1932         tlvs = wpabuf_alloc(2 + 1 + 1 + 1 + os_strlen(query));
1933         if (tlvs == NULL)
1934                 return 0;
1935         wpabuf_put_le16(tlvs, 1 + 1 + 1 + os_strlen(query));
1936         wpabuf_put_u8(tlvs, P2P_SERV_UPNP); /* Service Protocol Type */
1937         wpabuf_put_u8(tlvs, 1); /* Service Transaction ID */
1938         wpabuf_put_u8(tlvs, version);
1939         wpabuf_put_str(tlvs, query);
1940         ret = wpas_p2p_sd_request(wpa_s, dst, tlvs);
1941         wpabuf_free(tlvs);
1942         return ret;
1943 }
1944
1945
1946 #ifdef CONFIG_WIFI_DISPLAY
1947
1948 static u64 wpas_p2p_sd_request_wfd(struct wpa_supplicant *wpa_s, const u8 *dst,
1949                                    const struct wpabuf *tlvs)
1950 {
1951         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
1952                 return 0;
1953         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
1954                 return 0;
1955         return (uintptr_t) p2p_sd_request_wfd(wpa_s->global->p2p, dst, tlvs);
1956 }
1957
1958
1959 #define MAX_WFD_SD_SUBELEMS 20
1960
1961 static void wfd_add_sd_req_role(struct wpabuf *tlvs, u8 id, u8 role,
1962                                 const char *subelems)
1963 {
1964         u8 *len;
1965         const char *pos;
1966         int val;
1967         int count = 0;
1968
1969         len = wpabuf_put(tlvs, 2);
1970         wpabuf_put_u8(tlvs, P2P_SERV_WIFI_DISPLAY); /* Service Protocol Type */
1971         wpabuf_put_u8(tlvs, id); /* Service Transaction ID */
1972
1973         wpabuf_put_u8(tlvs, role);
1974
1975         pos = subelems;
1976         while (*pos) {
1977                 val = atoi(pos);
1978                 if (val >= 0 && val < 256) {
1979                         wpabuf_put_u8(tlvs, val);
1980                         count++;
1981                         if (count == MAX_WFD_SD_SUBELEMS)
1982                                 break;
1983                 }
1984                 pos = os_strchr(pos + 1, ',');
1985                 if (pos == NULL)
1986                         break;
1987                 pos++;
1988         }
1989
1990         WPA_PUT_LE16(len, (u8 *) wpabuf_put(tlvs, 0) - len - 2);
1991 }
1992
1993
1994 u64 wpas_p2p_sd_request_wifi_display(struct wpa_supplicant *wpa_s,
1995                                      const u8 *dst, const char *role)
1996 {
1997         struct wpabuf *tlvs;
1998         u64 ret;
1999         const char *subelems;
2000         u8 id = 1;
2001
2002         subelems = os_strchr(role, ' ');
2003         if (subelems == NULL)
2004                 return 0;
2005         subelems++;
2006
2007         tlvs = wpabuf_alloc(4 * (2 + 1 + 1 + 1 + MAX_WFD_SD_SUBELEMS));
2008         if (tlvs == NULL)
2009                 return 0;
2010
2011         if (os_strstr(role, "[source]"))
2012                 wfd_add_sd_req_role(tlvs, id++, 0x00, subelems);
2013         if (os_strstr(role, "[pri-sink]"))
2014                 wfd_add_sd_req_role(tlvs, id++, 0x01, subelems);
2015         if (os_strstr(role, "[sec-sink]"))
2016                 wfd_add_sd_req_role(tlvs, id++, 0x02, subelems);
2017         if (os_strstr(role, "[source+sink]"))
2018                 wfd_add_sd_req_role(tlvs, id++, 0x03, subelems);
2019
2020         ret = wpas_p2p_sd_request_wfd(wpa_s, dst, tlvs);
2021         wpabuf_free(tlvs);
2022         return ret;
2023 }
2024
2025 #endif /* CONFIG_WIFI_DISPLAY */
2026
2027
2028 int wpas_p2p_sd_cancel_request(struct wpa_supplicant *wpa_s, u64 req)
2029 {
2030         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
2031                 return wpa_drv_p2p_sd_cancel_request(wpa_s, req);
2032         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
2033                 return -1;
2034         return p2p_sd_cancel_request(wpa_s->global->p2p,
2035                                      (void *) (uintptr_t) req);
2036 }
2037
2038
2039 void wpas_p2p_sd_response(struct wpa_supplicant *wpa_s, int freq,
2040                           const u8 *dst, u8 dialog_token,
2041                           const struct wpabuf *resp_tlvs)
2042 {
2043         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT) {
2044                 wpa_drv_p2p_sd_response(wpa_s, freq, dst, dialog_token,
2045                                         resp_tlvs);
2046                 return;
2047         }
2048         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
2049                 return;
2050         p2p_sd_response(wpa_s->global->p2p, freq, dst, dialog_token,
2051                         resp_tlvs);
2052 }
2053
2054
2055 void wpas_p2p_sd_service_update(struct wpa_supplicant *wpa_s)
2056 {
2057         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT) {
2058                 wpa_drv_p2p_service_update(wpa_s);
2059                 return;
2060         }
2061         if (wpa_s->global->p2p)
2062                 p2p_sd_service_update(wpa_s->global->p2p);
2063 }
2064
2065
2066 static void wpas_p2p_srv_bonjour_free(struct p2p_srv_bonjour *bsrv)
2067 {
2068         dl_list_del(&bsrv->list);
2069         wpabuf_free(bsrv->query);
2070         wpabuf_free(bsrv->resp);
2071         os_free(bsrv);
2072 }
2073
2074
2075 static void wpas_p2p_srv_upnp_free(struct p2p_srv_upnp *usrv)
2076 {
2077         dl_list_del(&usrv->list);
2078         os_free(usrv->service);
2079         os_free(usrv);
2080 }
2081
2082
2083 void wpas_p2p_service_flush(struct wpa_supplicant *wpa_s)
2084 {
2085         struct p2p_srv_bonjour *bsrv, *bn;
2086         struct p2p_srv_upnp *usrv, *un;
2087
2088         dl_list_for_each_safe(bsrv, bn, &wpa_s->global->p2p_srv_bonjour,
2089                               struct p2p_srv_bonjour, list)
2090                 wpas_p2p_srv_bonjour_free(bsrv);
2091
2092         dl_list_for_each_safe(usrv, un, &wpa_s->global->p2p_srv_upnp,
2093                               struct p2p_srv_upnp, list)
2094                 wpas_p2p_srv_upnp_free(usrv);
2095
2096         wpas_p2p_sd_service_update(wpa_s);
2097 }
2098
2099
2100 int wpas_p2p_service_add_bonjour(struct wpa_supplicant *wpa_s,
2101                                  struct wpabuf *query, struct wpabuf *resp)
2102 {
2103         struct p2p_srv_bonjour *bsrv;
2104
2105         bsrv = os_zalloc(sizeof(*bsrv));
2106         if (bsrv == NULL)
2107                 return -1;
2108         bsrv->query = query;
2109         bsrv->resp = resp;
2110         dl_list_add(&wpa_s->global->p2p_srv_bonjour, &bsrv->list);
2111
2112         wpas_p2p_sd_service_update(wpa_s);
2113         return 0;
2114 }
2115
2116
2117 int wpas_p2p_service_del_bonjour(struct wpa_supplicant *wpa_s,
2118                                  const struct wpabuf *query)
2119 {
2120         struct p2p_srv_bonjour *bsrv;
2121
2122         bsrv = wpas_p2p_service_get_bonjour(wpa_s, query);
2123         if (bsrv == NULL)
2124                 return -1;
2125         wpas_p2p_srv_bonjour_free(bsrv);
2126         wpas_p2p_sd_service_update(wpa_s);
2127         return 0;
2128 }
2129
2130
2131 int wpas_p2p_service_add_upnp(struct wpa_supplicant *wpa_s, u8 version,
2132                               const char *service)
2133 {
2134         struct p2p_srv_upnp *usrv;
2135
2136         if (wpas_p2p_service_get_upnp(wpa_s, version, service))
2137                 return 0; /* Already listed */
2138         usrv = os_zalloc(sizeof(*usrv));
2139         if (usrv == NULL)
2140                 return -1;
2141         usrv->version = version;
2142         usrv->service = os_strdup(service);
2143         if (usrv->service == NULL) {
2144                 os_free(usrv);
2145                 return -1;
2146         }
2147         dl_list_add(&wpa_s->global->p2p_srv_upnp, &usrv->list);
2148
2149         wpas_p2p_sd_service_update(wpa_s);
2150         return 0;
2151 }
2152
2153
2154 int wpas_p2p_service_del_upnp(struct wpa_supplicant *wpa_s, u8 version,
2155                               const char *service)
2156 {
2157         struct p2p_srv_upnp *usrv;
2158
2159         usrv = wpas_p2p_service_get_upnp(wpa_s, version, service);
2160         if (usrv == NULL)
2161                 return -1;
2162         wpas_p2p_srv_upnp_free(usrv);
2163         wpas_p2p_sd_service_update(wpa_s);
2164         return 0;
2165 }
2166
2167
2168 static void wpas_prov_disc_local_display(struct wpa_supplicant *wpa_s,
2169                                          const u8 *peer, const char *params,
2170                                          unsigned int generated_pin)
2171 {
2172         wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_PROV_DISC_SHOW_PIN MACSTR " %08d%s",
2173                 MAC2STR(peer), generated_pin, params);
2174 }
2175
2176
2177 static void wpas_prov_disc_local_keypad(struct wpa_supplicant *wpa_s,
2178                                         const u8 *peer, const char *params)
2179 {
2180         wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_PROV_DISC_ENTER_PIN MACSTR "%s",
2181                 MAC2STR(peer), params);
2182 }
2183
2184
2185 void wpas_prov_disc_req(void *ctx, const u8 *peer, u16 config_methods,
2186                         const u8 *dev_addr, const u8 *pri_dev_type,
2187                         const char *dev_name, u16 supp_config_methods,
2188                         u8 dev_capab, u8 group_capab, const u8 *group_id,
2189                         size_t group_id_len)
2190 {
2191         struct wpa_supplicant *wpa_s = ctx;
2192         char devtype[WPS_DEV_TYPE_BUFSIZE];
2193         char params[300];
2194         u8 empty_dev_type[8];
2195         unsigned int generated_pin = 0;
2196         struct wpa_supplicant *group = NULL;
2197
2198         if (group_id) {
2199                 for (group = wpa_s->global->ifaces; group; group = group->next)
2200                 {
2201                         struct wpa_ssid *s = group->current_ssid;
2202                         if (s != NULL &&
2203                             s->mode == WPAS_MODE_P2P_GO &&
2204                             group_id_len - ETH_ALEN == s->ssid_len &&
2205                             os_memcmp(group_id + ETH_ALEN, s->ssid,
2206                                       s->ssid_len) == 0)
2207                                 break;
2208                 }
2209         }
2210
2211         if (pri_dev_type == NULL) {
2212                 os_memset(empty_dev_type, 0, sizeof(empty_dev_type));
2213                 pri_dev_type = empty_dev_type;
2214         }
2215         os_snprintf(params, sizeof(params), " p2p_dev_addr=" MACSTR
2216                     " pri_dev_type=%s name='%s' config_methods=0x%x "
2217                     "dev_capab=0x%x group_capab=0x%x%s%s",
2218                     MAC2STR(dev_addr),
2219                     wps_dev_type_bin2str(pri_dev_type, devtype,
2220                                          sizeof(devtype)),
2221                     dev_name, supp_config_methods, dev_capab, group_capab,
2222                     group ? " group=" : "",
2223                     group ? group->ifname : "");
2224         params[sizeof(params) - 1] = '\0';
2225
2226         if (config_methods & WPS_CONFIG_DISPLAY) {
2227                 generated_pin = wps_generate_pin();
2228                 wpas_prov_disc_local_display(wpa_s, peer, params,
2229                                              generated_pin);
2230         } else if (config_methods & WPS_CONFIG_KEYPAD)
2231                 wpas_prov_disc_local_keypad(wpa_s, peer, params);
2232         else if (config_methods & WPS_CONFIG_PUSHBUTTON)
2233                 wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_PROV_DISC_PBC_REQ MACSTR
2234                         "%s", MAC2STR(peer), params);
2235
2236         wpas_notify_p2p_provision_discovery(wpa_s, peer, 1 /* request */,
2237                                             P2P_PROV_DISC_SUCCESS,
2238                                             config_methods, generated_pin);
2239 }
2240
2241
2242 void wpas_prov_disc_resp(void *ctx, const u8 *peer, u16 config_methods)
2243 {
2244         struct wpa_supplicant *wpa_s = ctx;
2245         unsigned int generated_pin = 0;
2246         char params[20];
2247
2248         if (wpa_s->pending_pd_before_join &&
2249             (os_memcmp(peer, wpa_s->pending_join_dev_addr, ETH_ALEN) == 0 ||
2250              os_memcmp(peer, wpa_s->pending_join_iface_addr, ETH_ALEN) == 0)) {
2251                 wpa_s->pending_pd_before_join = 0;
2252                 wpa_printf(MSG_DEBUG, "P2P: Starting pending "
2253                            "join-existing-group operation");
2254                 wpas_p2p_join_start(wpa_s);
2255                 return;
2256         }
2257
2258         if (wpa_s->pending_pd_use == AUTO_PD_JOIN ||
2259             wpa_s->pending_pd_use == AUTO_PD_GO_NEG)
2260                 os_snprintf(params, sizeof(params), " peer_go=%d",
2261                             wpa_s->pending_pd_use == AUTO_PD_JOIN);
2262         else
2263                 params[0] = '\0';
2264
2265         if (config_methods & WPS_CONFIG_DISPLAY)
2266                 wpas_prov_disc_local_keypad(wpa_s, peer, params);
2267         else if (config_methods & WPS_CONFIG_KEYPAD) {
2268                 generated_pin = wps_generate_pin();
2269                 wpas_prov_disc_local_display(wpa_s, peer, params,
2270                                              generated_pin);
2271         } else if (config_methods & WPS_CONFIG_PUSHBUTTON)
2272                 wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_PROV_DISC_PBC_RESP MACSTR
2273                         "%s", MAC2STR(peer), params);
2274
2275         wpas_notify_p2p_provision_discovery(wpa_s, peer, 0 /* response */,
2276                                             P2P_PROV_DISC_SUCCESS,
2277                                             config_methods, generated_pin);
2278 }
2279
2280
2281 static void wpas_prov_disc_fail(void *ctx, const u8 *peer,
2282                                 enum p2p_prov_disc_status status)
2283 {
2284         struct wpa_supplicant *wpa_s = ctx;
2285
2286         if (wpa_s->p2p_fallback_to_go_neg) {
2287                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: PD for p2p_connect-auto "
2288                         "failed - fall back to GO Negotiation");
2289                 wpas_p2p_fallback_to_go_neg(wpa_s, 0);
2290                 return;
2291         }
2292
2293         wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_PROV_DISC_FAILURE
2294                 " p2p_dev_addr=" MACSTR " status=%d",
2295                 MAC2STR(peer), status);
2296
2297         wpas_notify_p2p_provision_discovery(wpa_s, peer, 0 /* response */,
2298                                             status, 0, 0);
2299 }
2300
2301
2302 static u8 wpas_invitation_process(void *ctx, const u8 *sa, const u8 *bssid,
2303                                   const u8 *go_dev_addr, const u8 *ssid,
2304                                   size_t ssid_len, int *go, u8 *group_bssid,
2305                                   int *force_freq, int persistent_group)
2306 {
2307         struct wpa_supplicant *wpa_s = ctx;
2308         struct wpa_ssid *s;
2309         u8 cur_bssid[ETH_ALEN];
2310         int res;
2311         struct wpa_supplicant *grp;
2312
2313         if (!persistent_group) {
2314                 wpa_printf(MSG_DEBUG, "P2P: Invitation from " MACSTR
2315                            " to join an active group", MAC2STR(sa));
2316                 if (!is_zero_ether_addr(wpa_s->p2p_auth_invite) &&
2317                     (os_memcmp(go_dev_addr, wpa_s->p2p_auth_invite, ETH_ALEN)
2318                      == 0 ||
2319                      os_memcmp(sa, wpa_s->p2p_auth_invite, ETH_ALEN) == 0)) {
2320                         wpa_printf(MSG_DEBUG, "P2P: Accept previously "
2321                                    "authorized invitation");
2322                         goto accept_inv;
2323                 }
2324                 /*
2325                  * Do not accept the invitation automatically; notify user and
2326                  * request approval.
2327                  */
2328                 return P2P_SC_FAIL_INFO_CURRENTLY_UNAVAILABLE;
2329         }
2330
2331         grp = wpas_get_p2p_group(wpa_s, ssid, ssid_len, go);
2332         if (grp) {
2333                 wpa_printf(MSG_DEBUG, "P2P: Accept invitation to already "
2334                            "running persistent group");
2335                 if (*go)
2336                         os_memcpy(group_bssid, grp->own_addr, ETH_ALEN);
2337                 goto accept_inv;
2338         }
2339
2340         if (!wpa_s->conf->persistent_reconnect)
2341                 return P2P_SC_FAIL_INFO_CURRENTLY_UNAVAILABLE;
2342
2343         for (s = wpa_s->conf->ssid; s; s = s->next) {
2344                 if (s->disabled == 2 &&
2345                     os_memcmp(s->bssid, go_dev_addr, ETH_ALEN) == 0 &&
2346                     s->ssid_len == ssid_len &&
2347                     os_memcmp(ssid, s->ssid, ssid_len) == 0)
2348                         break;
2349         }
2350
2351         if (!s) {
2352                 wpa_printf(MSG_DEBUG, "P2P: Invitation from " MACSTR
2353                            " requested reinvocation of an unknown group",
2354                            MAC2STR(sa));
2355                 return P2P_SC_FAIL_UNKNOWN_GROUP;
2356         }
2357
2358         if (s->mode == WPAS_MODE_P2P_GO && !wpas_p2p_create_iface(wpa_s)) {
2359                 *go = 1;
2360                 if (wpa_s->wpa_state >= WPA_AUTHENTICATING) {
2361                         wpa_printf(MSG_DEBUG, "P2P: The only available "
2362                                    "interface is already in use - reject "
2363                                    "invitation");
2364                         return P2P_SC_FAIL_UNABLE_TO_ACCOMMODATE;
2365                 }
2366                 os_memcpy(group_bssid, wpa_s->own_addr, ETH_ALEN);
2367         } else if (s->mode == WPAS_MODE_P2P_GO) {
2368                 *go = 1;
2369                 if (wpas_p2p_add_group_interface(wpa_s, WPA_IF_P2P_GO) < 0)
2370                 {
2371                         wpa_printf(MSG_ERROR, "P2P: Failed to allocate a new "
2372                                    "interface address for the group");
2373                         return P2P_SC_FAIL_UNABLE_TO_ACCOMMODATE;
2374                 }
2375                 os_memcpy(group_bssid, wpa_s->pending_interface_addr,
2376                           ETH_ALEN);
2377         }
2378
2379 accept_inv:
2380         if (wpa_s->current_ssid && wpa_drv_get_bssid(wpa_s, cur_bssid) == 0 &&
2381             wpa_s->assoc_freq) {
2382                 wpa_printf(MSG_DEBUG, "P2P: Trying to force channel to match "
2383                            "the channel we are already using");
2384                 *force_freq = wpa_s->assoc_freq;
2385         }
2386
2387         res = wpa_drv_shared_freq(wpa_s);
2388         if (res > 0) {
2389                 wpa_printf(MSG_DEBUG, "P2P: Trying to force channel to match "
2390                            "with the channel we are already using on a "
2391                            "shared interface");
2392                 *force_freq = res;
2393         }
2394
2395         return P2P_SC_SUCCESS;
2396 }
2397
2398
2399 static void wpas_invitation_received(void *ctx, const u8 *sa, const u8 *bssid,
2400                                      const u8 *ssid, size_t ssid_len,
2401                                      const u8 *go_dev_addr, u8 status,
2402                                      int op_freq)
2403 {
2404         struct wpa_supplicant *wpa_s = ctx;
2405         struct wpa_ssid *s;
2406
2407         for (s = wpa_s->conf->ssid; s; s = s->next) {
2408                 if (s->disabled == 2 &&
2409                     s->ssid_len == ssid_len &&
2410                     os_memcmp(ssid, s->ssid, ssid_len) == 0)
2411                         break;
2412         }
2413
2414         if (status == P2P_SC_SUCCESS) {
2415                 wpa_printf(MSG_DEBUG, "P2P: Invitation from peer " MACSTR
2416                            " was accepted; op_freq=%d MHz",
2417                            MAC2STR(sa), op_freq);
2418                 if (s) {
2419                         int go = s->mode == WPAS_MODE_P2P_GO;
2420                         wpas_p2p_group_add_persistent(
2421                                 wpa_s, s, go, go ? op_freq : 0, 0);
2422                 } else if (bssid) {
2423                         wpas_p2p_join(wpa_s, bssid, go_dev_addr,
2424                                       wpa_s->p2p_wps_method, 0);
2425                 }
2426                 return;
2427         }
2428
2429         if (status != P2P_SC_FAIL_INFO_CURRENTLY_UNAVAILABLE) {
2430                 wpa_printf(MSG_DEBUG, "P2P: Invitation from peer " MACSTR
2431                            " was rejected (status %u)", MAC2STR(sa), status);
2432                 return;
2433         }
2434
2435         if (!s) {
2436                 if (bssid) {
2437                         wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_INVITATION_RECEIVED
2438                                 "sa=" MACSTR " go_dev_addr=" MACSTR
2439                                 " bssid=" MACSTR " unknown-network",
2440                                 MAC2STR(sa), MAC2STR(go_dev_addr),
2441                                 MAC2STR(bssid));
2442                 } else {
2443                         wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_INVITATION_RECEIVED
2444                                 "sa=" MACSTR " go_dev_addr=" MACSTR
2445                                 " unknown-network",
2446                                 MAC2STR(sa), MAC2STR(go_dev_addr));
2447                 }
2448                 return;
2449         }
2450
2451         wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_INVITATION_RECEIVED "sa=" MACSTR
2452                 " persistent=%d", MAC2STR(sa), s->id);
2453 }
2454
2455
2456 static void wpas_invitation_result(void *ctx, int status, const u8 *bssid)
2457 {
2458         struct wpa_supplicant *wpa_s = ctx;
2459         struct wpa_ssid *ssid;
2460
2461         if (bssid) {
2462                 wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_INVITATION_RESULT
2463                         "status=%d " MACSTR,
2464                         status, MAC2STR(bssid));
2465         } else {
2466                 wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_INVITATION_RESULT
2467                         "status=%d ", status);
2468         }
2469         wpas_notify_p2p_invitation_result(wpa_s, status, bssid);
2470
2471         if (wpa_s->pending_invite_ssid_id == -1)
2472                 return; /* Invitation to active group */
2473
2474         if (status != P2P_SC_SUCCESS) {
2475                 wpas_p2p_remove_pending_group_interface(wpa_s);
2476                 return;
2477         }
2478
2479         ssid = wpa_config_get_network(wpa_s->conf,
2480                                       wpa_s->pending_invite_ssid_id);
2481         if (ssid == NULL) {
2482                 wpa_printf(MSG_ERROR, "P2P: Could not find persistent group "
2483                            "data matching with invitation");
2484                 return;
2485         }
2486
2487         /*
2488          * The peer could have missed our ctrl::ack frame for Invitation
2489          * Response and continue retransmitting the frame. To reduce the
2490          * likelihood of the peer not getting successful TX status for the
2491          * Invitation Response frame, wait a short time here before starting
2492          * the persistent group so that we will remain on the current channel to
2493          * acknowledge any possible retransmission from the peer.
2494          */
2495         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: 50 ms wait on current channel before "
2496                 "starting persistent group");
2497         os_sleep(0, 50000);
2498
2499         wpas_p2p_group_add_persistent(wpa_s, ssid,
2500                                       ssid->mode == WPAS_MODE_P2P_GO,
2501                                       wpa_s->p2p_persistent_go_freq,
2502                                       wpa_s->p2p_go_ht40);
2503 }
2504
2505
2506 static int wpas_p2p_disallowed_freq(struct wpa_global *global,
2507                                     unsigned int freq)
2508 {
2509         unsigned int i;
2510
2511         if (global->p2p_disallow_freq == NULL)
2512                 return 0;
2513
2514         for (i = 0; i < global->num_p2p_disallow_freq; i++) {
2515                 if (freq >= global->p2p_disallow_freq[i].min &&
2516                     freq <= global->p2p_disallow_freq[i].max)
2517                         return 1;
2518         }
2519
2520         return 0;
2521 }
2522
2523
2524 static void wpas_p2p_add_chan(struct p2p_reg_class *reg, u8 chan)
2525 {
2526         reg->channel[reg->channels] = chan;
2527         reg->channels++;
2528 }
2529
2530
2531 static int wpas_p2p_default_channels(struct wpa_supplicant *wpa_s,
2532                                      struct p2p_channels *chan)
2533 {
2534         int i, cla = 0;
2535
2536         wpa_printf(MSG_DEBUG, "P2P: Enable operating classes for 2.4 GHz "
2537                    "band");
2538
2539         /* Operating class 81 - 2.4 GHz band channels 1..13 */
2540         chan->reg_class[cla].reg_class = 81;
2541         chan->reg_class[cla].channels = 0;
2542         for (i = 0; i < 11; i++) {
2543                 if (!wpas_p2p_disallowed_freq(wpa_s->global, 2412 + i * 5))
2544                         wpas_p2p_add_chan(&chan->reg_class[cla], i + 1);
2545         }
2546         if (chan->reg_class[cla].channels)
2547                 cla++;
2548
2549         wpa_printf(MSG_DEBUG, "P2P: Enable operating classes for lower 5 GHz "
2550                    "band");
2551
2552         /* Operating class 115 - 5 GHz, channels 36-48 */
2553         chan->reg_class[cla].reg_class = 115;
2554         chan->reg_class[cla].channels = 0;
2555         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 36 * 5))
2556                 wpas_p2p_add_chan(&chan->reg_class[cla], 36);
2557         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 40 * 5))
2558                 wpas_p2p_add_chan(&chan->reg_class[cla], 40);
2559         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 44 * 5))
2560                 wpas_p2p_add_chan(&chan->reg_class[cla], 44);
2561         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 48 * 5))
2562                 wpas_p2p_add_chan(&chan->reg_class[cla], 48);
2563         if (chan->reg_class[cla].channels)
2564                 cla++;
2565
2566         wpa_printf(MSG_DEBUG, "P2P: Enable operating classes for higher 5 GHz "
2567                    "band");
2568
2569         /* Operating class 124 - 5 GHz, channels 149,153,157,161 */
2570         chan->reg_class[cla].reg_class = 124;
2571         chan->reg_class[cla].channels = 0;
2572         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 149 * 5))
2573                 wpas_p2p_add_chan(&chan->reg_class[cla], 149);
2574         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 153 * 5))
2575                 wpas_p2p_add_chan(&chan->reg_class[cla], 153);
2576         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 156 * 5))
2577                 wpas_p2p_add_chan(&chan->reg_class[cla], 157);
2578         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 161 * 5))
2579                 wpas_p2p_add_chan(&chan->reg_class[cla], 161);
2580         if (chan->reg_class[cla].channels)
2581                 cla++;
2582
2583         chan->reg_classes = cla;
2584         return 0;
2585 }
2586
2587
2588 static struct hostapd_hw_modes * get_mode(struct hostapd_hw_modes *modes,
2589                                           u16 num_modes,
2590                                           enum hostapd_hw_mode mode)
2591 {
2592         u16 i;
2593
2594         for (i = 0; i < num_modes; i++) {
2595                 if (modes[i].mode == mode)
2596                         return &modes[i];
2597         }
2598
2599         return NULL;
2600 }
2601
2602
2603 static int has_channel(struct wpa_global *global,
2604                        struct hostapd_hw_modes *mode, u8 chan, int *flags)
2605 {
2606         int i;
2607         unsigned int freq;
2608
2609         freq = (mode->mode == HOSTAPD_MODE_IEEE80211A ? 5000 : 2407) +
2610                 chan * 5;
2611         if (wpas_p2p_disallowed_freq(global, freq))
2612                 return 0;
2613
2614         for (i = 0; i < mode->num_channels; i++) {
2615                 if (mode->channels[i].chan == chan) {
2616                         if (flags)
2617                                 *flags = mode->channels[i].flag;
2618                         return !(mode->channels[i].flag &
2619                                  (HOSTAPD_CHAN_DISABLED |
2620                                   HOSTAPD_CHAN_PASSIVE_SCAN |
2621                                   HOSTAPD_CHAN_NO_IBSS |
2622                                   HOSTAPD_CHAN_RADAR));
2623                 }
2624         }
2625
2626         return 0;
2627 }
2628
2629
2630 struct p2p_oper_class_map {
2631         enum hostapd_hw_mode mode;
2632         u8 op_class;
2633         u8 min_chan;
2634         u8 max_chan;
2635         u8 inc;
2636         enum { BW20, BW40PLUS, BW40MINUS } bw;
2637 };
2638
2639 static struct p2p_oper_class_map op_class[] = {
2640         { HOSTAPD_MODE_IEEE80211G, 81, 1, 13, 1, BW20 },
2641 #if 0 /* Do not enable HT40 on 2 GHz for now */
2642         { HOSTAPD_MODE_IEEE80211G, 83, 1, 9, 1, BW40PLUS },
2643         { HOSTAPD_MODE_IEEE80211G, 84, 5, 13, 1, BW40MINUS },
2644 #endif
2645         { HOSTAPD_MODE_IEEE80211A, 115, 36, 48, 4, BW20 },
2646         { HOSTAPD_MODE_IEEE80211A, 124, 149, 161, 4, BW20 },
2647         { HOSTAPD_MODE_IEEE80211A, 116, 36, 44, 8, BW40PLUS },
2648         { HOSTAPD_MODE_IEEE80211A, 117, 40, 48, 8, BW40MINUS },
2649         { HOSTAPD_MODE_IEEE80211A, 126, 149, 157, 8, BW40PLUS },
2650         { HOSTAPD_MODE_IEEE80211A, 127, 153, 161, 8, BW40MINUS },
2651         { -1, 0, 0, 0, 0, BW20 }
2652 };
2653
2654
2655 static int wpas_p2p_verify_channel(struct wpa_supplicant *wpa_s,
2656                                    struct hostapd_hw_modes *mode,
2657                                    u8 channel, u8 bw)
2658 {
2659         int flag;
2660
2661         if (!has_channel(wpa_s->global, mode, channel, &flag))
2662                 return -1;
2663         if (bw == BW40MINUS &&
2664             (!(flag & HOSTAPD_CHAN_HT40MINUS) ||
2665              !has_channel(wpa_s->global, mode, channel - 4, NULL)))
2666                 return 0;
2667         if (bw == BW40PLUS &&
2668             (!(flag & HOSTAPD_CHAN_HT40PLUS) ||
2669              !has_channel(wpa_s->global, mode, channel + 4, NULL)))
2670                 return 0;
2671         return 1;
2672 }
2673
2674
2675 static int wpas_p2p_setup_channels(struct wpa_supplicant *wpa_s,
2676                                    struct p2p_channels *chan)
2677 {
2678         struct hostapd_hw_modes *mode;
2679         int cla, op;
2680
2681         if (wpa_s->hw.modes == NULL) {
2682                 wpa_printf(MSG_DEBUG, "P2P: Driver did not support fetching "
2683                            "of all supported channels; assume dualband "
2684                            "support");
2685                 return wpas_p2p_default_channels(wpa_s, chan);
2686         }
2687
2688         cla = 0;
2689
2690         for (op = 0; op_class[op].op_class; op++) {
2691                 struct p2p_oper_class_map *o = &op_class[op];
2692                 u8 ch;
2693                 struct p2p_reg_class *reg = NULL;
2694
2695                 mode = get_mode(wpa_s->hw.modes, wpa_s->hw.num_modes, o->mode);
2696                 if (mode == NULL)
2697                         continue;
2698                 for (ch = o->min_chan; ch <= o->max_chan; ch += o->inc) {
2699                         if (wpas_p2p_verify_channel(wpa_s, mode, ch, o->bw) < 1)
2700                                 continue;
2701                         if (reg == NULL) {
2702                                 wpa_printf(MSG_DEBUG, "P2P: Add operating "
2703                                            "class %u", o->op_class);
2704                                 reg = &chan->reg_class[cla];
2705                                 cla++;
2706                                 reg->reg_class = o->op_class;
2707                         }
2708                         reg->channel[reg->channels] = ch;
2709                         reg->channels++;
2710                 }
2711                 if (reg) {
2712                         wpa_hexdump(MSG_DEBUG, "P2P: Channels",
2713                                     reg->channel, reg->channels);
2714                 }
2715         }
2716
2717         chan->reg_classes = cla;
2718
2719         return 0;
2720 }
2721
2722
2723 int wpas_p2p_get_ht40_mode(struct wpa_supplicant *wpa_s,
2724                            struct hostapd_hw_modes *mode, u8 channel)
2725 {
2726         int op, ret;
2727
2728         for (op = 0; op_class[op].op_class; op++) {
2729                 struct p2p_oper_class_map *o = &op_class[op];
2730                 u8 ch;
2731
2732                 for (ch = o->min_chan; ch <= o->max_chan; ch += o->inc) {
2733                         if (o->mode != HOSTAPD_MODE_IEEE80211A ||
2734                             o->bw == BW20 || ch != channel)
2735                                 continue;
2736                         ret = wpas_p2p_verify_channel(wpa_s, mode, ch, o->bw);
2737                         if (ret < 0)
2738                                 continue;
2739                         else if (ret > 0)
2740                                 return (o->bw == BW40MINUS) ? -1 : 1;
2741                         else
2742                                 return 0;
2743                 }
2744         }
2745         return 0;
2746 }
2747
2748
2749 static int wpas_get_noa(void *ctx, const u8 *interface_addr, u8 *buf,
2750                         size_t buf_len)
2751 {
2752         struct wpa_supplicant *wpa_s = ctx;
2753
2754         for (wpa_s = wpa_s->global->ifaces; wpa_s; wpa_s = wpa_s->next) {
2755                 if (os_memcmp(wpa_s->own_addr, interface_addr, ETH_ALEN) == 0)
2756                         break;
2757         }
2758         if (wpa_s == NULL)
2759                 return -1;
2760
2761         return wpa_drv_get_noa(wpa_s, buf, buf_len);
2762 }
2763
2764
2765 static int wpas_go_connected(void *ctx, const u8 *dev_addr)
2766 {
2767         struct wpa_supplicant *wpa_s = ctx;
2768
2769         for (wpa_s = wpa_s->global->ifaces; wpa_s; wpa_s = wpa_s->next) {
2770                 struct wpa_ssid *ssid = wpa_s->current_ssid;
2771                 if (ssid == NULL)
2772                         continue;
2773                 if (ssid->mode != WPAS_MODE_INFRA)
2774                         continue;
2775                 if (wpa_s->wpa_state != WPA_COMPLETED &&
2776                     wpa_s->wpa_state != WPA_GROUP_HANDSHAKE)
2777                         continue;
2778                 if (os_memcmp(wpa_s->go_dev_addr, dev_addr, ETH_ALEN) == 0)
2779                         return 1;
2780         }
2781
2782         return 0;
2783 }
2784
2785
2786 /**
2787  * wpas_p2p_init - Initialize P2P module for %wpa_supplicant
2788  * @global: Pointer to global data from wpa_supplicant_init()
2789  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
2790  * Returns: 0 on success, -1 on failure
2791  */
2792 int wpas_p2p_init(struct wpa_global *global, struct wpa_supplicant *wpa_s)
2793 {
2794         struct p2p_config p2p;
2795         unsigned int r;
2796         int i;
2797
2798         if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_CAPABLE))
2799                 return 0;
2800
2801         if (global->p2p)
2802                 return 0;
2803
2804         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT) {
2805                 struct p2p_params params;
2806
2807                 wpa_printf(MSG_DEBUG, "P2P: Use driver-based P2P management");
2808                 os_memset(&params, 0, sizeof(params));
2809                 params.dev_name = wpa_s->conf->device_name;
2810                 os_memcpy(params.pri_dev_type, wpa_s->conf->device_type,
2811                           WPS_DEV_TYPE_LEN);
2812                 params.num_sec_dev_types = wpa_s->conf->num_sec_device_types;
2813                 os_memcpy(params.sec_dev_type,
2814                           wpa_s->conf->sec_device_type,
2815                           params.num_sec_dev_types * WPS_DEV_TYPE_LEN);
2816
2817                 if (wpa_drv_p2p_set_params(wpa_s, &params) < 0)
2818                         return -1;
2819
2820                 return 0;
2821         }
2822
2823         os_memset(&p2p, 0, sizeof(p2p));
2824         p2p.msg_ctx = wpa_s;
2825         p2p.cb_ctx = wpa_s;
2826         p2p.p2p_scan = wpas_p2p_scan;
2827         p2p.send_action = wpas_send_action;
2828         p2p.send_action_done = wpas_send_action_done;
2829         p2p.go_neg_completed = wpas_go_neg_completed;
2830         p2p.go_neg_req_rx = wpas_go_neg_req_rx;
2831         p2p.dev_found = wpas_dev_found;
2832         p2p.dev_lost = wpas_dev_lost;
2833         p2p.start_listen = wpas_start_listen;
2834         p2p.stop_listen = wpas_stop_listen;
2835         p2p.send_probe_resp = wpas_send_probe_resp;
2836         p2p.sd_request = wpas_sd_request;
2837         p2p.sd_response = wpas_sd_response;
2838         p2p.prov_disc_req = wpas_prov_disc_req;
2839         p2p.prov_disc_resp = wpas_prov_disc_resp;
2840         p2p.prov_disc_fail = wpas_prov_disc_fail;
2841         p2p.invitation_process = wpas_invitation_process;
2842         p2p.invitation_received = wpas_invitation_received;
2843         p2p.invitation_result = wpas_invitation_result;
2844         p2p.get_noa = wpas_get_noa;
2845         p2p.go_connected = wpas_go_connected;
2846
2847         os_memcpy(wpa_s->global->p2p_dev_addr, wpa_s->own_addr, ETH_ALEN);
2848         os_memcpy(p2p.dev_addr, wpa_s->global->p2p_dev_addr, ETH_ALEN);
2849         p2p.dev_name = wpa_s->conf->device_name;
2850         p2p.manufacturer = wpa_s->conf->manufacturer;
2851         p2p.model_name = wpa_s->conf->model_name;
2852         p2p.model_number = wpa_s->conf->model_number;
2853         p2p.serial_number = wpa_s->conf->serial_number;
2854         if (wpa_s->wps) {
2855                 os_memcpy(p2p.uuid, wpa_s->wps->uuid, 16);
2856                 p2p.config_methods = wpa_s->wps->config_methods;
2857         }
2858
2859         if (wpa_s->conf->p2p_listen_reg_class &&
2860             wpa_s->conf->p2p_listen_channel) {
2861                 p2p.reg_class = wpa_s->conf->p2p_listen_reg_class;
2862                 p2p.channel = wpa_s->conf->p2p_listen_channel;
2863         } else {
2864                 p2p.reg_class = 81;
2865                 /*
2866                  * Pick one of the social channels randomly as the listen
2867                  * channel.
2868                  */
2869                 os_get_random((u8 *) &r, sizeof(r));
2870                 p2p.channel = 1 + (r % 3) * 5;
2871         }
2872         wpa_printf(MSG_DEBUG, "P2P: Own listen channel: %d", p2p.channel);
2873
2874         if (wpa_s->conf->p2p_oper_reg_class &&
2875             wpa_s->conf->p2p_oper_channel) {
2876                 p2p.op_reg_class = wpa_s->conf->p2p_oper_reg_class;
2877                 p2p.op_channel = wpa_s->conf->p2p_oper_channel;
2878                 p2p.cfg_op_channel = 1;
2879                 wpa_printf(MSG_DEBUG, "P2P: Configured operating channel: "
2880                            "%d:%d", p2p.op_reg_class, p2p.op_channel);
2881
2882         } else {
2883                 p2p.op_reg_class = 81;
2884                 /*
2885                  * Use random operation channel from (1, 6, 11) if no other
2886                  * preference is indicated.
2887                  */
2888                 os_get_random((u8 *) &r, sizeof(r));
2889                 p2p.op_channel = 1 + (r % 3) * 5;
2890                 p2p.cfg_op_channel = 0;
2891                 wpa_printf(MSG_DEBUG, "P2P: Random operating channel: "
2892                            "%d:%d", p2p.op_reg_class, p2p.op_channel);
2893         }
2894         if (wpa_s->conf->country[0] && wpa_s->conf->country[1]) {
2895                 os_memcpy(p2p.country, wpa_s->conf->country, 2);
2896                 p2p.country[2] = 0x04;
2897         } else
2898                 os_memcpy(p2p.country, "XX\x04", 3);
2899
2900         if (wpas_p2p_setup_channels(wpa_s, &p2p.channels)) {
2901                 wpa_printf(MSG_ERROR, "P2P: Failed to configure supported "
2902                            "channel list");
2903                 return -1;
2904         }
2905
2906         os_memcpy(p2p.pri_dev_type, wpa_s->conf->device_type,
2907                   WPS_DEV_TYPE_LEN);
2908
2909         p2p.num_sec_dev_types = wpa_s->conf->num_sec_device_types;
2910         os_memcpy(p2p.sec_dev_type, wpa_s->conf->sec_device_type,
2911                   p2p.num_sec_dev_types * WPS_DEV_TYPE_LEN);
2912
2913         p2p.concurrent_operations = !!(wpa_s->drv_flags &
2914                                        WPA_DRIVER_FLAGS_P2P_CONCURRENT);
2915
2916         p2p.max_peers = 100;
2917
2918         if (wpa_s->conf->p2p_ssid_postfix) {
2919                 p2p.ssid_postfix_len =
2920                         os_strlen(wpa_s->conf->p2p_ssid_postfix);
2921                 if (p2p.ssid_postfix_len > sizeof(p2p.ssid_postfix))
2922                         p2p.ssid_postfix_len = sizeof(p2p.ssid_postfix);
2923                 os_memcpy(p2p.ssid_postfix, wpa_s->conf->p2p_ssid_postfix,
2924                           p2p.ssid_postfix_len);
2925         }
2926
2927         p2p.p2p_intra_bss = wpa_s->conf->p2p_intra_bss;
2928
2929         p2p.max_listen = wpa_s->max_remain_on_chan;
2930
2931         global->p2p = p2p_init(&p2p);
2932         if (global->p2p == NULL)
2933                 return -1;
2934         global->p2p_init_wpa_s = wpa_s;
2935
2936         for (i = 0; i < MAX_WPS_VENDOR_EXT; i++) {
2937                 if (wpa_s->conf->wps_vendor_ext[i] == NULL)
2938                         continue;
2939                 p2p_add_wps_vendor_extension(
2940                         global->p2p, wpa_s->conf->wps_vendor_ext[i]);
2941         }
2942
2943         return 0;
2944 }
2945
2946
2947 /**
2948  * wpas_p2p_deinit - Deinitialize per-interface P2P data
2949  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
2950  *
2951  * This function deinitialize per-interface P2P data.
2952  */
2953 void wpas_p2p_deinit(struct wpa_supplicant *wpa_s)
2954 {
2955         if (wpa_s->driver && wpa_s->drv_priv)
2956                 wpa_drv_probe_req_report(wpa_s, 0);
2957
2958         if (wpa_s->go_params) {
2959                 /* Clear any stored provisioning info */
2960                 p2p_clear_provisioning_info(
2961                         wpa_s->global->p2p,
2962                         wpa_s->go_params->peer_device_addr);
2963         }
2964
2965         os_free(wpa_s->go_params);
2966         wpa_s->go_params = NULL;
2967         eloop_cancel_timeout(wpas_p2p_group_formation_timeout, wpa_s, NULL);
2968         eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
2969         eloop_cancel_timeout(wpas_p2p_pd_before_join_timeout, wpa_s, NULL);
2970         wpa_s->p2p_long_listen = 0;
2971         eloop_cancel_timeout(wpas_p2p_long_listen_timeout, wpa_s, NULL);
2972         eloop_cancel_timeout(wpas_p2p_group_idle_timeout, wpa_s, NULL);
2973         wpas_p2p_remove_pending_group_interface(wpa_s);
2974
2975         /* TODO: remove group interface from the driver if this wpa_s instance
2976          * is on top of a P2P group interface */
2977 }
2978
2979
2980 /**
2981  * wpas_p2p_deinit_global - Deinitialize global P2P module
2982  * @global: Pointer to global data from wpa_supplicant_init()
2983  *
2984  * This function deinitializes the global (per device) P2P module.
2985  */
2986 void wpas_p2p_deinit_global(struct wpa_global *global)
2987 {
2988         struct wpa_supplicant *wpa_s, *tmp;
2989
2990         wpa_s = global->ifaces;
2991         if (wpa_s)
2992                 wpas_p2p_service_flush(wpa_s);
2993
2994         if (global->p2p == NULL)
2995                 return;
2996
2997         /* Remove remaining P2P group interfaces */
2998         while (wpa_s && wpa_s->p2p_group_interface != NOT_P2P_GROUP_INTERFACE)
2999                 wpa_s = wpa_s->next;
3000         while (wpa_s) {
3001                 tmp = global->ifaces;
3002                 while (tmp &&
3003                        (tmp == wpa_s ||
3004                         tmp->p2p_group_interface == NOT_P2P_GROUP_INTERFACE)) {
3005                         tmp = tmp->next;
3006                 }
3007                 if (tmp == NULL)
3008                         break;
3009                 /* Disconnect from the P2P group and deinit the interface */
3010                 wpas_p2p_disconnect(tmp);
3011         }
3012
3013         /*
3014          * Deinit GO data on any possibly remaining interface (if main
3015          * interface is used as GO).
3016          */
3017         for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) {
3018                 if (wpa_s->ap_iface)
3019                         wpas_p2p_group_deinit(wpa_s);
3020         }
3021
3022         p2p_deinit(global->p2p);
3023         global->p2p = NULL;
3024         global->p2p_init_wpa_s = NULL;
3025 }
3026
3027
3028 static int wpas_p2p_create_iface(struct wpa_supplicant *wpa_s)
3029 {
3030         if (wpa_s->conf->p2p_no_group_iface)
3031                 return 0; /* separate interface disabled per configuration */
3032         if (wpa_s->drv_flags &
3033             (WPA_DRIVER_FLAGS_P2P_DEDICATED_INTERFACE |
3034              WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P))
3035                 return 1; /* P2P group requires a new interface in every case
3036                            */
3037         if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_CONCURRENT))
3038                 return 0; /* driver does not support concurrent operations */
3039         if (wpa_s->global->ifaces->next)
3040                 return 1; /* more that one interface already in use */
3041         if (wpa_s->wpa_state >= WPA_AUTHENTICATING)
3042                 return 1; /* this interface is already in use */
3043         return 0;
3044 }
3045
3046
3047 static int wpas_p2p_start_go_neg(struct wpa_supplicant *wpa_s,
3048                                  const u8 *peer_addr,
3049                                  enum p2p_wps_method wps_method,
3050                                  int go_intent, const u8 *own_interface_addr,
3051                                  unsigned int force_freq, int persistent_group,
3052                                  struct wpa_ssid *ssid, unsigned int pref_freq)
3053 {
3054         if (persistent_group && wpa_s->conf->persistent_reconnect)
3055                 persistent_group = 2;
3056
3057         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT) {
3058                 return wpa_drv_p2p_connect(wpa_s, peer_addr, wps_method,
3059                                            go_intent, own_interface_addr,
3060                                            force_freq, persistent_group);
3061         }
3062
3063         /*
3064          * Increase GO config timeout if HT40 is used since it takes some time
3065          * to scan channels for coex purposes before the BSS can be started.
3066          */
3067         p2p_set_config_timeout(wpa_s->global->p2p,
3068                                wpa_s->p2p_go_ht40 ? 255 : 100, 20);
3069
3070         return p2p_connect(wpa_s->global->p2p, peer_addr, wps_method,
3071                            go_intent, own_interface_addr, force_freq,
3072                            persistent_group, ssid ? ssid->ssid : NULL,
3073                            ssid ? ssid->ssid_len : 0,
3074                            wpa_s->p2p_pd_before_go_neg, pref_freq);
3075 }
3076
3077
3078 static int wpas_p2p_auth_go_neg(struct wpa_supplicant *wpa_s,
3079                                 const u8 *peer_addr,
3080                                 enum p2p_wps_method wps_method,
3081                                 int go_intent, const u8 *own_interface_addr,
3082                                 unsigned int force_freq, int persistent_group,
3083                                 struct wpa_ssid *ssid, unsigned int pref_freq)
3084 {
3085         if (persistent_group && wpa_s->conf->persistent_reconnect)
3086                 persistent_group = 2;
3087
3088         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
3089                 return -1;
3090
3091         return p2p_authorize(wpa_s->global->p2p, peer_addr, wps_method,
3092                              go_intent, own_interface_addr, force_freq,
3093                              persistent_group, ssid ? ssid->ssid : NULL,
3094                              ssid ? ssid->ssid_len : 0, pref_freq);
3095 }
3096
3097
3098 static void wpas_p2p_check_join_scan_limit(struct wpa_supplicant *wpa_s)
3099 {
3100         wpa_s->p2p_join_scan_count++;
3101         wpa_printf(MSG_DEBUG, "P2P: Join scan attempt %d",
3102                    wpa_s->p2p_join_scan_count);
3103         if (wpa_s->p2p_join_scan_count > P2P_MAX_JOIN_SCAN_ATTEMPTS) {
3104                 wpa_printf(MSG_DEBUG, "P2P: Failed to find GO " MACSTR
3105                            " for join operationg - stop join attempt",
3106                            MAC2STR(wpa_s->pending_join_iface_addr));
3107                 eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
3108                 if (wpa_s->p2p_auto_pd) {
3109                         wpa_s->p2p_auto_pd = 0;
3110                         wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_PROV_DISC_FAILURE
3111                                 " p2p_dev_addr=" MACSTR " status=N/A",
3112                                 MAC2STR(wpa_s->pending_join_dev_addr));
3113                         return;
3114                 }
3115                 wpa_msg(wpa_s->parent, MSG_INFO,
3116                         P2P_EVENT_GROUP_FORMATION_FAILURE);
3117         }
3118 }
3119
3120
3121 static void wpas_p2p_pd_before_join_timeout(void *eloop_ctx, void *timeout_ctx)
3122 {
3123         struct wpa_supplicant *wpa_s = eloop_ctx;
3124         if (!wpa_s->pending_pd_before_join)
3125                 return;
3126         wpa_s->pending_pd_before_join = 0;
3127         /*
3128          * Provision Discovery Response may have been lost - try to connect
3129          * anyway since we do not need any information from this PD.
3130          */
3131         wpa_printf(MSG_DEBUG, "P2P: PD timeout for join-existing-group - "
3132                    "try to connect anyway");
3133         wpas_p2p_join_start(wpa_s);
3134 }
3135
3136
3137 static int wpas_check_freq_conflict(struct wpa_supplicant *wpa_s, int freq)
3138 {
3139         struct wpa_supplicant *iface;
3140         int shared_freq;
3141         u8 bssid[ETH_ALEN];
3142
3143         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_MULTI_CHANNEL_CONCURRENT)
3144                 return 0;
3145
3146         for (iface = wpa_s->global->ifaces; iface; iface = iface->next) {
3147                 if (!wpas_p2p_create_iface(wpa_s) && iface == wpa_s)
3148                         continue;
3149                 if (iface->current_ssid == NULL || iface->assoc_freq == 0)
3150                         continue;
3151                 if (iface->current_ssid->mode == WPAS_MODE_AP ||
3152                     iface->current_ssid->mode == WPAS_MODE_P2P_GO)
3153                         shared_freq = iface->current_ssid->frequency;
3154                 else if (wpa_drv_get_bssid(iface, bssid) == 0)
3155                         shared_freq = iface->assoc_freq;
3156                 else
3157                         shared_freq = 0;
3158
3159                 if (shared_freq && freq != shared_freq) {
3160                         wpa_printf(MSG_DEBUG, "P2P: Frequency conflict - %s "
3161                                    "connected on %d MHz - new connection on "
3162                                    "%d MHz", iface->ifname, shared_freq, freq);
3163                         return 1;
3164                 }
3165         }
3166
3167         shared_freq = wpa_drv_shared_freq(wpa_s);
3168         if (shared_freq > 0 && shared_freq != freq) {
3169                 wpa_printf(MSG_DEBUG, "P2P: Frequency conflict - shared "
3170                            "virtual interface connected on %d MHz - new "
3171                            "connection on %d MHz", shared_freq, freq);
3172                 return 1;
3173         }
3174
3175         return 0;
3176 }
3177
3178
3179 static int wpas_p2p_peer_go(struct wpa_supplicant *wpa_s,
3180                             const u8 *peer_dev_addr)
3181 {
3182         struct wpa_bss *bss;
3183         int updated;
3184
3185         bss = wpa_bss_get_p2p_dev_addr(wpa_s, peer_dev_addr);
3186         if (bss == NULL)
3187                 return -1;
3188         if (bss->last_update_idx < wpa_s->bss_update_idx) {
3189                 wpa_printf(MSG_DEBUG, "P2P: Peer BSS entry not updated in the "
3190                            "last scan");
3191                 return 0;
3192         }
3193
3194         updated = os_time_before(&wpa_s->p2p_auto_started, &bss->last_update);
3195         wpa_printf(MSG_DEBUG, "P2P: Current BSS entry for peer updated at "
3196                    "%ld.%06ld (%supdated in last scan)",
3197                    bss->last_update.sec, bss->last_update.usec,
3198                    updated ? "": "not ");
3199
3200         return updated;
3201 }
3202
3203
3204 static void wpas_p2p_scan_res_join(struct wpa_supplicant *wpa_s,
3205                                    struct wpa_scan_results *scan_res)
3206 {
3207         struct wpa_bss *bss;
3208         int freq;
3209         u8 iface_addr[ETH_ALEN];
3210
3211         eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
3212
3213         if (wpa_s->global->p2p_disabled)
3214                 return;
3215
3216         wpa_printf(MSG_DEBUG, "P2P: Scan results received (%d BSS) for %sjoin",
3217                    scan_res ? (int) scan_res->num : -1,
3218                    wpa_s->p2p_auto_join ? "auto_" : "");
3219
3220         if (scan_res)
3221                 wpas_p2p_scan_res_handler(wpa_s, scan_res);
3222
3223         if (wpa_s->p2p_auto_pd) {
3224                 int join = wpas_p2p_peer_go(wpa_s,
3225                                             wpa_s->pending_join_dev_addr);
3226                 if (join == 0 &&
3227                     wpa_s->auto_pd_scan_retry < P2P_AUTO_PD_SCAN_ATTEMPTS) {
3228                         wpa_s->auto_pd_scan_retry++;
3229                         bss = wpa_bss_get_bssid(wpa_s,
3230                                                 wpa_s->pending_join_dev_addr);
3231                         if (bss) {
3232                                 freq = bss->freq;
3233                                 wpa_printf(MSG_DEBUG, "P2P: Scan retry %d for "
3234                                            "the peer " MACSTR " at %d MHz",
3235                                            wpa_s->auto_pd_scan_retry,
3236                                            MAC2STR(wpa_s->
3237                                                    pending_join_dev_addr),
3238                                            freq);
3239                                 wpas_p2p_join_scan_req(wpa_s, freq);
3240                                 return;
3241                         }
3242                 }
3243
3244                 if (join < 0)
3245                         join = 0;
3246
3247                 wpa_s->p2p_auto_pd = 0;
3248                 wpa_s->pending_pd_use = join ? AUTO_PD_JOIN : AUTO_PD_GO_NEG;
3249                 wpa_printf(MSG_DEBUG, "P2P: Auto PD with " MACSTR " join=%d",
3250                            MAC2STR(wpa_s->pending_join_dev_addr), join);
3251                 if (p2p_prov_disc_req(wpa_s->global->p2p,
3252                                       wpa_s->pending_join_dev_addr,
3253                                       wpa_s->pending_pd_config_methods, join,
3254                                       0) < 0) {
3255                         wpa_s->p2p_auto_pd = 0;
3256                         wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_PROV_DISC_FAILURE
3257                                 " p2p_dev_addr=" MACSTR " status=N/A",
3258                                 MAC2STR(wpa_s->pending_join_dev_addr));
3259                 }
3260                 return;
3261         }
3262
3263         if (wpa_s->p2p_auto_join) {
3264                 int join = wpas_p2p_peer_go(wpa_s,
3265                                             wpa_s->pending_join_dev_addr);
3266                 if (join < 0) {
3267                         wpa_printf(MSG_DEBUG, "P2P: Peer was not found to be "
3268                                    "running a GO -> use GO Negotiation");
3269                         wpas_p2p_connect(wpa_s, wpa_s->pending_join_dev_addr,
3270                                          wpa_s->p2p_pin, wpa_s->p2p_wps_method,
3271                                          wpa_s->p2p_persistent_group, 0, 0, 0,
3272                                          wpa_s->p2p_go_intent,
3273                                          wpa_s->p2p_connect_freq,
3274                                          wpa_s->p2p_persistent_id,
3275                                          wpa_s->p2p_pd_before_go_neg,
3276                                          wpa_s->p2p_go_ht40);
3277                         return;
3278                 }
3279
3280                 wpa_printf(MSG_DEBUG, "P2P: Peer was found running GO%s -> "
3281                            "try to join the group", join ? "" :
3282                            " in older scan");
3283                 if (!join)
3284                         wpa_s->p2p_fallback_to_go_neg = 1;
3285         }
3286
3287         freq = p2p_get_oper_freq(wpa_s->global->p2p,
3288                                  wpa_s->pending_join_iface_addr);
3289         if (freq < 0 &&
3290             p2p_get_interface_addr(wpa_s->global->p2p,
3291                                    wpa_s->pending_join_dev_addr,
3292                                    iface_addr) == 0 &&
3293             os_memcmp(iface_addr, wpa_s->pending_join_dev_addr, ETH_ALEN) != 0)
3294         {
3295                 wpa_printf(MSG_DEBUG, "P2P: Overwrite pending interface "
3296                            "address for join from " MACSTR " to " MACSTR
3297                            " based on newly discovered P2P peer entry",
3298                            MAC2STR(wpa_s->pending_join_iface_addr),
3299                            MAC2STR(iface_addr));
3300                 os_memcpy(wpa_s->pending_join_iface_addr, iface_addr,
3301                           ETH_ALEN);
3302
3303                 freq = p2p_get_oper_freq(wpa_s->global->p2p,
3304                                          wpa_s->pending_join_iface_addr);
3305         }
3306         if (freq >= 0) {
3307                 wpa_printf(MSG_DEBUG, "P2P: Target GO operating frequency "
3308                            "from P2P peer table: %d MHz", freq);
3309         }
3310         bss = wpa_bss_get_bssid(wpa_s, wpa_s->pending_join_iface_addr);
3311         if (bss) {
3312                 freq = bss->freq;
3313                 wpa_printf(MSG_DEBUG, "P2P: Target GO operating frequency "
3314                            "from BSS table: %d MHz", freq);
3315         }
3316         if (freq > 0) {
3317                 u16 method;
3318
3319                 if (wpas_check_freq_conflict(wpa_s, freq) > 0) {
3320                         wpa_msg(wpa_s->parent, MSG_INFO,
3321                                 P2P_EVENT_GROUP_FORMATION_FAILURE
3322                                 "reason=FREQ_CONFLICT");
3323                         return;
3324                 }
3325
3326                 wpa_printf(MSG_DEBUG, "P2P: Send Provision Discovery Request "
3327                            "prior to joining an existing group (GO " MACSTR
3328                            " freq=%u MHz)",
3329                            MAC2STR(wpa_s->pending_join_dev_addr), freq);
3330                 wpa_s->pending_pd_before_join = 1;
3331
3332                 switch (wpa_s->pending_join_wps_method) {
3333                 case WPS_PIN_DISPLAY:
3334                         method = WPS_CONFIG_KEYPAD;
3335                         break;
3336                 case WPS_PIN_KEYPAD:
3337                         method = WPS_CONFIG_DISPLAY;
3338                         break;
3339                 case WPS_PBC:
3340                         method = WPS_CONFIG_PUSHBUTTON;
3341                         break;
3342                 default:
3343                         method = 0;
3344                         break;
3345                 }
3346
3347                 if ((p2p_get_provisioning_info(wpa_s->global->p2p,
3348                                                wpa_s->pending_join_dev_addr) ==
3349                      method)) {
3350                         /*
3351                          * We have already performed provision discovery for
3352                          * joining the group. Proceed directly to join
3353                          * operation without duplicated provision discovery. */
3354                         wpa_printf(MSG_DEBUG, "P2P: Provision discovery "
3355                                    "with " MACSTR " already done - proceed to "
3356                                    "join",
3357                                    MAC2STR(wpa_s->pending_join_dev_addr));
3358                         wpa_s->pending_pd_before_join = 0;
3359                         goto start;
3360                 }
3361
3362                 if (p2p_prov_disc_req(wpa_s->global->p2p,
3363                                       wpa_s->pending_join_dev_addr, method, 1,
3364                                       freq) < 0) {
3365                         wpa_printf(MSG_DEBUG, "P2P: Failed to send Provision "
3366                                    "Discovery Request before joining an "
3367                                    "existing group");
3368                         wpa_s->pending_pd_before_join = 0;
3369                         goto start;
3370                 }
3371
3372                 /*
3373                  * Actual join operation will be started from the Action frame
3374                  * TX status callback (if no ACK is received) or when the
3375                  * Provision Discovery Response is received. Use a short
3376                  * timeout as a backup mechanism should the Provision Discovery
3377                  * Response be lost for any reason.
3378                  */
3379                 eloop_cancel_timeout(wpas_p2p_pd_before_join_timeout, wpa_s,
3380                                      NULL);
3381                 eloop_register_timeout(2, 0, wpas_p2p_pd_before_join_timeout,
3382                                        wpa_s, NULL);
3383                 return;
3384         }
3385
3386         wpa_printf(MSG_DEBUG, "P2P: Failed to find BSS/GO - try again later");
3387         eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
3388         eloop_register_timeout(1, 0, wpas_p2p_join_scan, wpa_s, NULL);
3389         wpas_p2p_check_join_scan_limit(wpa_s);
3390         return;
3391
3392 start:
3393         /* Start join operation immediately */
3394         wpas_p2p_join_start(wpa_s);
3395 }
3396
3397
3398 static void wpas_p2p_join_scan_req(struct wpa_supplicant *wpa_s, int freq)
3399 {
3400         int ret;
3401         struct wpa_driver_scan_params params;
3402         struct wpabuf *wps_ie, *ies;
3403         size_t ielen;
3404         int freqs[2] = { 0, 0 };
3405
3406         os_memset(&params, 0, sizeof(params));
3407
3408         /* P2P Wildcard SSID */
3409         params.num_ssids = 1;
3410         params.ssids[0].ssid = (u8 *) P2P_WILDCARD_SSID;
3411         params.ssids[0].ssid_len = P2P_WILDCARD_SSID_LEN;
3412
3413         wpa_s->wps->dev.p2p = 1;
3414         wps_ie = wps_build_probe_req_ie(DEV_PW_DEFAULT, &wpa_s->wps->dev,
3415                                         wpa_s->wps->uuid, WPS_REQ_ENROLLEE, 0,
3416                                         NULL);
3417         if (wps_ie == NULL) {
3418                 wpas_p2p_scan_res_join(wpa_s, NULL);
3419                 return;
3420         }
3421
3422         ielen = p2p_scan_ie_buf_len(wpa_s->global->p2p);
3423         ies = wpabuf_alloc(wpabuf_len(wps_ie) + ielen);
3424         if (ies == NULL) {
3425                 wpabuf_free(wps_ie);
3426                 wpas_p2p_scan_res_join(wpa_s, NULL);
3427                 return;
3428         }
3429         wpabuf_put_buf(ies, wps_ie);
3430         wpabuf_free(wps_ie);
3431
3432         p2p_scan_ie(wpa_s->global->p2p, ies, NULL);
3433
3434         params.p2p_probe = 1;
3435         params.extra_ies = wpabuf_head(ies);
3436         params.extra_ies_len = wpabuf_len(ies);
3437         if (freq > 0) {
3438                 freqs[0] = freq;
3439                 params.freqs = freqs;
3440         }
3441
3442         /*
3443          * Run a scan to update BSS table and start Provision Discovery once
3444          * the new scan results become available.
3445          */
3446         ret = wpa_drv_scan(wpa_s, &params);
3447         if (!ret)
3448                 wpa_s->scan_res_handler = wpas_p2p_scan_res_join;
3449
3450         wpabuf_free(ies);
3451
3452         if (ret) {
3453                 wpa_printf(MSG_DEBUG, "P2P: Failed to start scan for join - "
3454                            "try again later");
3455                 eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
3456                 eloop_register_timeout(1, 0, wpas_p2p_join_scan, wpa_s, NULL);
3457                 wpas_p2p_check_join_scan_limit(wpa_s);
3458         }
3459 }
3460
3461
3462 static void wpas_p2p_join_scan(void *eloop_ctx, void *timeout_ctx)
3463 {
3464         struct wpa_supplicant *wpa_s = eloop_ctx;
3465         wpas_p2p_join_scan_req(wpa_s, 0);
3466 }
3467
3468
3469 static int wpas_p2p_join(struct wpa_supplicant *wpa_s, const u8 *iface_addr,
3470                          const u8 *dev_addr, enum p2p_wps_method wps_method,
3471                          int auto_join)
3472 {
3473         wpa_printf(MSG_DEBUG, "P2P: Request to join existing group (iface "
3474                    MACSTR " dev " MACSTR ")%s",
3475                    MAC2STR(iface_addr), MAC2STR(dev_addr),
3476                    auto_join ? " (auto_join)" : "");
3477
3478         wpa_s->p2p_auto_pd = 0;
3479         wpa_s->p2p_auto_join = !!auto_join;
3480         os_memcpy(wpa_s->pending_join_iface_addr, iface_addr, ETH_ALEN);
3481         os_memcpy(wpa_s->pending_join_dev_addr, dev_addr, ETH_ALEN);
3482         wpa_s->pending_join_wps_method = wps_method;
3483
3484         /* Make sure we are not running find during connection establishment */
3485         wpas_p2p_stop_find(wpa_s);
3486
3487         wpa_s->p2p_join_scan_count = 0;
3488         wpas_p2p_join_scan(wpa_s, NULL);
3489         return 0;
3490 }
3491
3492
3493 static int wpas_p2p_join_start(struct wpa_supplicant *wpa_s)
3494 {
3495         struct wpa_supplicant *group;
3496         struct p2p_go_neg_results res;
3497         struct wpa_bss *bss;
3498
3499         eloop_cancel_timeout(wpas_p2p_pd_before_join_timeout, wpa_s, NULL);
3500         group = wpas_p2p_get_group_iface(wpa_s, 0, 0);
3501         if (group == NULL)
3502                 return -1;
3503         if (group != wpa_s) {
3504                 os_memcpy(group->p2p_pin, wpa_s->p2p_pin,
3505                           sizeof(group->p2p_pin));
3506                 group->p2p_wps_method = wpa_s->p2p_wps_method;
3507         }
3508
3509         group->p2p_in_provisioning = 1;
3510         group->p2p_fallback_to_go_neg = wpa_s->p2p_fallback_to_go_neg;
3511
3512         os_memset(&res, 0, sizeof(res));
3513         os_memcpy(res.peer_interface_addr, wpa_s->pending_join_iface_addr,
3514                   ETH_ALEN);
3515         res.wps_method = wpa_s->pending_join_wps_method;
3516         bss = wpa_bss_get_bssid(wpa_s, wpa_s->pending_join_iface_addr);
3517         if (bss) {
3518                 res.freq = bss->freq;
3519                 res.ssid_len = bss->ssid_len;
3520                 os_memcpy(res.ssid, bss->ssid, bss->ssid_len);
3521         }
3522
3523         if (wpa_s->off_channel_freq || wpa_s->roc_waiting_drv_freq) {
3524                 wpa_printf(MSG_DEBUG, "P2P: Cancel remain-on-channel prior to "
3525                            "starting client");
3526                 wpa_drv_cancel_remain_on_channel(wpa_s);
3527                 wpa_s->off_channel_freq = 0;
3528                 wpa_s->roc_waiting_drv_freq = 0;
3529         }
3530         wpas_start_wps_enrollee(group, &res);
3531
3532         /*
3533          * Allow a longer timeout for join-a-running-group than normal 15
3534          * second group formation timeout since the GO may not have authorized
3535          * our connection yet.
3536          */
3537         eloop_cancel_timeout(wpas_p2p_group_formation_timeout, wpa_s, NULL);
3538         eloop_register_timeout(60, 0, wpas_p2p_group_formation_timeout,
3539                                wpa_s, NULL);
3540
3541         return 0;
3542 }
3543
3544
3545 /**
3546  * wpas_p2p_connect - Request P2P Group Formation to be started
3547  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
3548  * @peer_addr: Address of the peer P2P Device
3549  * @pin: PIN to use during provisioning or %NULL to indicate PBC mode
3550  * @persistent_group: Whether to create a persistent group
3551  * @auto_join: Whether to select join vs. GO Negotiation automatically
3552  * @join: Whether to join an existing group (as a client) instead of starting
3553  *      Group Owner negotiation; @peer_addr is BSSID in that case
3554  * @auth: Whether to only authorize the connection instead of doing that and
3555  *      initiating Group Owner negotiation
3556  * @go_intent: GO Intent or -1 to use default
3557  * @freq: Frequency for the group or 0 for auto-selection
3558  * @persistent_id: Persistent group credentials to use for forcing GO
3559  *      parameters or -1 to generate new values (SSID/passphrase)
3560  * @pd: Whether to send Provision Discovery prior to GO Negotiation as an
3561  *      interoperability workaround when initiating group formation
3562  * @ht40: Start GO with 40 MHz channel width
3563  * Returns: 0 or new PIN (if pin was %NULL) on success, -1 on unspecified
3564  *      failure, -2 on failure due to channel not currently available,
3565  *      -3 if forced channel is not supported
3566  */
3567 int wpas_p2p_connect(struct wpa_supplicant *wpa_s, const u8 *peer_addr,
3568                      const char *pin, enum p2p_wps_method wps_method,
3569                      int persistent_group, int auto_join, int join, int auth,
3570                      int go_intent, int freq, int persistent_id, int pd,
3571                      int ht40)
3572 {
3573         int force_freq = 0, pref_freq = 0, oper_freq = 0;
3574         u8 bssid[ETH_ALEN];
3575         int ret = 0;
3576         enum wpa_driver_if_type iftype;
3577         const u8 *if_addr;
3578         struct wpa_ssid *ssid = NULL;
3579
3580         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
3581                 return -1;
3582
3583         if (persistent_id >= 0) {
3584                 ssid = wpa_config_get_network(wpa_s->conf, persistent_id);
3585                 if (ssid == NULL || ssid->disabled != 2 ||
3586                     ssid->mode != WPAS_MODE_P2P_GO)
3587                         return -1;
3588         }
3589
3590         if (go_intent < 0)
3591                 go_intent = wpa_s->conf->p2p_go_intent;
3592
3593         if (!auth)
3594                 wpa_s->p2p_long_listen = 0;
3595
3596         wpa_s->p2p_wps_method = wps_method;
3597         wpa_s->p2p_persistent_group = !!persistent_group;
3598         wpa_s->p2p_persistent_id = persistent_id;
3599         wpa_s->p2p_go_intent = go_intent;
3600         wpa_s->p2p_connect_freq = freq;
3601         wpa_s->p2p_fallback_to_go_neg = 0;
3602         wpa_s->p2p_pd_before_go_neg = !!pd;
3603         wpa_s->p2p_go_ht40 = !!ht40;
3604
3605         if (pin)
3606                 os_strlcpy(wpa_s->p2p_pin, pin, sizeof(wpa_s->p2p_pin));
3607         else if (wps_method == WPS_PIN_DISPLAY) {
3608                 ret = wps_generate_pin();
3609                 os_snprintf(wpa_s->p2p_pin, sizeof(wpa_s->p2p_pin), "%08d",
3610                             ret);
3611                 wpa_printf(MSG_DEBUG, "P2P: Randomly generated PIN: %s",
3612                            wpa_s->p2p_pin);
3613         } else
3614                 wpa_s->p2p_pin[0] = '\0';
3615
3616         if (join || auto_join) {
3617                 u8 iface_addr[ETH_ALEN], dev_addr[ETH_ALEN];
3618                 if (auth) {
3619                         wpa_printf(MSG_DEBUG, "P2P: Authorize invitation to "
3620                                    "connect a running group from " MACSTR,
3621                                    MAC2STR(peer_addr));
3622                         os_memcpy(wpa_s->p2p_auth_invite, peer_addr, ETH_ALEN);
3623                         return ret;
3624                 }
3625                 os_memcpy(dev_addr, peer_addr, ETH_ALEN);
3626                 if (p2p_get_interface_addr(wpa_s->global->p2p, peer_addr,
3627                                            iface_addr) < 0) {
3628                         os_memcpy(iface_addr, peer_addr, ETH_ALEN);
3629                         p2p_get_dev_addr(wpa_s->global->p2p, peer_addr,
3630                                          dev_addr);
3631                 }
3632                 if (auto_join) {
3633                         os_get_time(&wpa_s->p2p_auto_started);
3634                         wpa_printf(MSG_DEBUG, "P2P: Auto join started at "
3635                                    "%ld.%06ld",
3636                                    wpa_s->p2p_auto_started.sec,
3637                                    wpa_s->p2p_auto_started.usec);
3638                 }
3639                 if (wpas_p2p_join(wpa_s, iface_addr, dev_addr, wps_method,
3640                                   auto_join) < 0)
3641                         return -1;
3642                 return ret;
3643         }
3644
3645         if (wpa_s->current_ssid && wpa_drv_get_bssid(wpa_s, bssid) == 0 &&
3646             wpa_s->assoc_freq)
3647                 oper_freq = wpa_s->assoc_freq;
3648         else {
3649                 oper_freq = wpa_drv_shared_freq(wpa_s);
3650                 if (oper_freq < 0)
3651                         oper_freq = 0;
3652         }
3653
3654         if (freq > 0) {
3655                 if (!p2p_supported_freq(wpa_s->global->p2p, freq)) {
3656                         wpa_printf(MSG_DEBUG, "P2P: The forced channel "
3657                                    "(%u MHz) is not supported for P2P uses",
3658                                    freq);
3659                         return -3;
3660                 }
3661
3662                 if (oper_freq > 0 && freq != oper_freq &&
3663                     !(wpa_s->drv_flags &
3664                       WPA_DRIVER_FLAGS_MULTI_CHANNEL_CONCURRENT)) {
3665                         wpa_printf(MSG_DEBUG, "P2P: Cannot start P2P group "
3666                                    "on %u MHz while connected on another "
3667                                    "channel (%u MHz)", freq, oper_freq);
3668                         return -2;
3669                 }
3670                 wpa_printf(MSG_DEBUG, "P2P: Trying to force us to use the "
3671                            "requested channel (%u MHz)", freq);
3672                 force_freq = freq;
3673         } else if (oper_freq > 0 &&
3674                    !p2p_supported_freq(wpa_s->global->p2p, oper_freq)) {
3675                 if (!(wpa_s->drv_flags &
3676                       WPA_DRIVER_FLAGS_MULTI_CHANNEL_CONCURRENT)) {
3677                         wpa_printf(MSG_DEBUG, "P2P: Cannot start P2P group "
3678                                    "while connected on non-P2P supported "
3679                                    "channel (%u MHz)", oper_freq);
3680                         return -2;
3681                 }
3682                 wpa_printf(MSG_DEBUG, "P2P: Current operating channel "
3683                            "(%u MHz) not available for P2P - try to use "
3684                            "another channel", oper_freq);
3685                 force_freq = 0;
3686         } else if (oper_freq > 0 &&
3687                    (wpa_s->drv_flags &
3688                     WPA_DRIVER_FLAGS_MULTI_CHANNEL_CONCURRENT)) {
3689                 wpa_printf(MSG_DEBUG, "P2P: Trying to prefer the channel we "
3690                            "are already using (%u MHz) on another interface",
3691                            oper_freq);
3692                 pref_freq = oper_freq;
3693         } else if (oper_freq > 0) {
3694                 wpa_printf(MSG_DEBUG, "P2P: Trying to force us to use the "
3695                            "channel we are already using (%u MHz) on another "
3696                            "interface", oper_freq);
3697                 force_freq = oper_freq;
3698         }
3699
3700         wpa_s->create_p2p_iface = wpas_p2p_create_iface(wpa_s);
3701
3702         if (wpa_s->create_p2p_iface) {
3703                 /* Prepare to add a new interface for the group */
3704                 iftype = WPA_IF_P2P_GROUP;
3705                 if (go_intent == 15)
3706                         iftype = WPA_IF_P2P_GO;
3707                 if (wpas_p2p_add_group_interface(wpa_s, iftype) < 0) {
3708                         wpa_printf(MSG_ERROR, "P2P: Failed to allocate a new "
3709                                    "interface for the group");
3710                         return -1;
3711                 }
3712
3713                 if_addr = wpa_s->pending_interface_addr;
3714         } else
3715                 if_addr = wpa_s->own_addr;
3716
3717         if (auth) {
3718                 if (wpas_p2p_auth_go_neg(wpa_s, peer_addr, wps_method,
3719                                          go_intent, if_addr,
3720                                          force_freq, persistent_group, ssid,
3721                                          pref_freq) < 0)
3722                         return -1;
3723                 return ret;
3724         }
3725
3726         if (wpas_p2p_start_go_neg(wpa_s, peer_addr, wps_method,
3727                                   go_intent, if_addr, force_freq,
3728                                   persistent_group, ssid, pref_freq) < 0) {
3729                 if (wpa_s->create_p2p_iface)
3730                         wpas_p2p_remove_pending_group_interface(wpa_s);
3731                 return -1;
3732         }
3733         return ret;
3734 }
3735
3736
3737 /**
3738  * wpas_p2p_remain_on_channel_cb - Indication of remain-on-channel start
3739  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
3740  * @freq: Frequency of the channel in MHz
3741  * @duration: Duration of the stay on the channel in milliseconds
3742  *
3743  * This callback is called when the driver indicates that it has started the
3744  * requested remain-on-channel duration.
3745  */
3746 void wpas_p2p_remain_on_channel_cb(struct wpa_supplicant *wpa_s,
3747                                    unsigned int freq, unsigned int duration)
3748 {
3749         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
3750                 return;
3751         if (wpa_s->off_channel_freq == wpa_s->pending_listen_freq) {
3752                 p2p_listen_cb(wpa_s->global->p2p, wpa_s->pending_listen_freq,
3753                               wpa_s->pending_listen_duration);
3754                 wpa_s->pending_listen_freq = 0;
3755         }
3756 }
3757
3758
3759 static int wpas_p2p_listen_start(struct wpa_supplicant *wpa_s,
3760                                  unsigned int timeout)
3761 {
3762         /* Limit maximum Listen state time based on driver limitation. */
3763         if (timeout > wpa_s->max_remain_on_chan)
3764                 timeout = wpa_s->max_remain_on_chan;
3765
3766         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
3767                 return wpa_drv_p2p_listen(wpa_s, timeout);
3768
3769         return p2p_listen(wpa_s->global->p2p, timeout);
3770 }
3771
3772
3773 /**
3774  * wpas_p2p_cancel_remain_on_channel_cb - Remain-on-channel timeout
3775  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
3776  * @freq: Frequency of the channel in MHz
3777  *
3778  * This callback is called when the driver indicates that a remain-on-channel
3779  * operation has been completed, i.e., the duration on the requested channel
3780  * has timed out.
3781  */
3782 void wpas_p2p_cancel_remain_on_channel_cb(struct wpa_supplicant *wpa_s,
3783                                           unsigned int freq)
3784 {
3785         wpa_printf(MSG_DEBUG, "P2P: Cancel remain-on-channel callback "
3786                    "(p2p_long_listen=%d ms pending_action_tx=%p)",
3787                    wpa_s->p2p_long_listen, wpa_s->pending_action_tx);
3788         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
3789                 return;
3790         if (p2p_listen_end(wpa_s->global->p2p, freq) > 0)
3791                 return; /* P2P module started a new operation */
3792         if (wpa_s->pending_action_tx)
3793                 return;
3794         if (wpa_s->p2p_long_listen > 0)
3795                 wpa_s->p2p_long_listen -= wpa_s->max_remain_on_chan;
3796         if (wpa_s->p2p_long_listen > 0) {
3797                 wpa_printf(MSG_DEBUG, "P2P: Continuing long Listen state");
3798                 wpas_p2p_listen_start(wpa_s, wpa_s->p2p_long_listen);
3799         }
3800 }
3801
3802
3803 /**
3804  * wpas_p2p_group_remove - Remove a P2P group
3805  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
3806  * @ifname: Network interface name of the group interface or "*" to remove all
3807  *      groups
3808  * Returns: 0 on success, -1 on failure
3809  *
3810  * This function is used to remove a P2P group. This can be used to disconnect
3811  * from a group in which the local end is a P2P Client or to end a P2P Group in
3812  * case the local end is the Group Owner. If a virtual network interface was
3813  * created for this group, that interface will be removed. Otherwise, only the
3814  * configured P2P group network will be removed from the interface.
3815  */
3816 int wpas_p2p_group_remove(struct wpa_supplicant *wpa_s, const char *ifname)
3817 {
3818         struct wpa_global *global = wpa_s->global;
3819
3820         if (os_strcmp(ifname, "*") == 0) {
3821                 struct wpa_supplicant *prev;
3822                 wpa_s = global->ifaces;
3823                 while (wpa_s) {
3824                         prev = wpa_s;
3825                         wpa_s = wpa_s->next;
3826                         wpas_p2p_disconnect(prev);
3827                 }
3828                 return 0;
3829         }
3830
3831         for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) {
3832                 if (os_strcmp(wpa_s->ifname, ifname) == 0)
3833                         break;
3834         }
3835
3836         return wpas_p2p_disconnect(wpa_s);
3837 }
3838
3839
3840 static int wpas_p2p_init_go_params(struct wpa_supplicant *wpa_s,
3841                                    struct p2p_go_neg_results *params,
3842                                    int freq, int ht40)
3843 {
3844         u8 bssid[ETH_ALEN];
3845         int res;
3846
3847         os_memset(params, 0, sizeof(*params));
3848         params->role_go = 1;
3849         params->ht40 = ht40;
3850         if (freq) {
3851                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on forced "
3852                            "frequency %d MHz", freq);
3853                 params->freq = freq;
3854         } else if (wpa_s->conf->p2p_oper_reg_class == 81 &&
3855                    wpa_s->conf->p2p_oper_channel >= 1 &&
3856                    wpa_s->conf->p2p_oper_channel <= 11) {
3857                 params->freq = 2407 + 5 * wpa_s->conf->p2p_oper_channel;
3858                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on configured "
3859                            "frequency %d MHz", params->freq);
3860         } else if (wpa_s->conf->p2p_oper_reg_class == 115 ||
3861                    wpa_s->conf->p2p_oper_reg_class == 124) {
3862                 params->freq = 5000 + 5 * wpa_s->conf->p2p_oper_channel;
3863                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on configured "
3864                            "frequency %d MHz", params->freq);
3865         } else if (wpa_s->conf->p2p_oper_channel == 0 &&
3866                    wpa_s->best_overall_freq > 0 &&
3867                    p2p_supported_freq(wpa_s->global->p2p,
3868                                       wpa_s->best_overall_freq)) {
3869                 params->freq = wpa_s->best_overall_freq;
3870                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on best overall "
3871                            "channel %d MHz", params->freq);
3872         } else if (wpa_s->conf->p2p_oper_channel == 0 &&
3873                    wpa_s->best_24_freq > 0 &&
3874                    p2p_supported_freq(wpa_s->global->p2p,
3875                                       wpa_s->best_24_freq)) {
3876                 params->freq = wpa_s->best_24_freq;
3877                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on best 2.4 GHz "
3878                            "channel %d MHz", params->freq);
3879         } else if (wpa_s->conf->p2p_oper_channel == 0 &&
3880                    wpa_s->best_5_freq > 0 &&
3881                    p2p_supported_freq(wpa_s->global->p2p,
3882                                       wpa_s->best_5_freq)) {
3883                 params->freq = wpa_s->best_5_freq;
3884                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on best 5 GHz "
3885                            "channel %d MHz", params->freq);
3886         } else {
3887                 int chan;
3888                 for (chan = 0; chan < 11; chan++) {
3889                         params->freq = 2412 + chan * 5;
3890                         if (!wpas_p2p_disallowed_freq(wpa_s->global,
3891                                                       params->freq))
3892                                 break;
3893                 }
3894                 if (chan == 11) {
3895                         wpa_printf(MSG_DEBUG, "P2P: No 2.4 GHz channel "
3896                                    "allowed");
3897                         return -1;
3898                 }
3899                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq %d MHz (no preference "
3900                            "known)", params->freq);
3901         }
3902
3903         if (wpa_s->current_ssid && wpa_drv_get_bssid(wpa_s, bssid) == 0 &&
3904             wpa_s->assoc_freq && !freq) {
3905                 wpa_printf(MSG_DEBUG, "P2P: Force GO on the channel we are "
3906                            "already using");
3907                 params->freq = wpa_s->assoc_freq;
3908         }
3909
3910         res = wpa_drv_shared_freq(wpa_s);
3911         if (res > 0 && !freq) {
3912                 wpa_printf(MSG_DEBUG, "P2P: Force GO on the channel we are "
3913                            "already using on a shared interface");
3914                 params->freq = res;
3915         } else if (res > 0 && freq != res &&
3916                    !(wpa_s->drv_flags &
3917                      WPA_DRIVER_FLAGS_MULTI_CHANNEL_CONCURRENT)) {
3918                 wpa_printf(MSG_DEBUG, "P2P: Cannot start P2P group on %u MHz "
3919                            "while connected on another channel (%u MHz)",
3920                            freq, res);
3921                 return -1;
3922         }
3923
3924         return 0;
3925 }
3926
3927
3928 static struct wpa_supplicant *
3929 wpas_p2p_get_group_iface(struct wpa_supplicant *wpa_s, int addr_allocated,
3930                          int go)
3931 {
3932         struct wpa_supplicant *group_wpa_s;
3933
3934         if (!wpas_p2p_create_iface(wpa_s)) {
3935                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Use same interface for group "
3936                         "operations");
3937                 return wpa_s;
3938         }
3939
3940         if (wpas_p2p_add_group_interface(wpa_s, go ? WPA_IF_P2P_GO :
3941                                          WPA_IF_P2P_CLIENT) < 0) {
3942                 wpa_msg(wpa_s, MSG_ERROR, "P2P: Failed to add group interface");
3943                 return NULL;
3944         }
3945         group_wpa_s = wpas_p2p_init_group_interface(wpa_s, go);
3946         if (group_wpa_s == NULL) {
3947                 wpa_msg(wpa_s, MSG_ERROR, "P2P: Failed to initialize group "
3948                         "interface");
3949                 wpas_p2p_remove_pending_group_interface(wpa_s);
3950                 return NULL;
3951         }
3952
3953         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Use separate group interface %s",
3954                 group_wpa_s->ifname);
3955         return group_wpa_s;
3956 }
3957
3958
3959 /**
3960  * wpas_p2p_group_add - Add a new P2P group with local end as Group Owner
3961  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
3962  * @persistent_group: Whether to create a persistent group
3963  * @freq: Frequency for the group or 0 to indicate no hardcoding
3964  * Returns: 0 on success, -1 on failure
3965  *
3966  * This function creates a new P2P group with the local end as the Group Owner,
3967  * i.e., without using Group Owner Negotiation.
3968  */
3969 int wpas_p2p_group_add(struct wpa_supplicant *wpa_s, int persistent_group,
3970                        int freq, int ht40)
3971 {
3972         struct p2p_go_neg_results params;
3973         unsigned int r;
3974
3975         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
3976                 return -1;
3977
3978         /* Make sure we are not running find during connection establishment */
3979         wpa_printf(MSG_DEBUG, "P2P: Stop any on-going P2P FIND");
3980         wpas_p2p_stop_find_oper(wpa_s);
3981
3982         if (freq == 2) {
3983                 wpa_printf(MSG_DEBUG, "P2P: Request to start GO on 2.4 GHz "
3984                            "band");
3985                 if (wpa_s->best_24_freq > 0 &&
3986                     p2p_supported_freq(wpa_s->global->p2p,
3987                                        wpa_s->best_24_freq)) {
3988                         freq = wpa_s->best_24_freq;
3989                         wpa_printf(MSG_DEBUG, "P2P: Use best 2.4 GHz band "
3990                                    "channel: %d MHz", freq);
3991                 } else {
3992                         os_get_random((u8 *) &r, sizeof(r));
3993                         freq = 2412 + (r % 3) * 25;
3994                         wpa_printf(MSG_DEBUG, "P2P: Use random 2.4 GHz band "
3995                                    "channel: %d MHz", freq);
3996                 }
3997         }
3998
3999         if (freq == 5) {
4000                 wpa_printf(MSG_DEBUG, "P2P: Request to start GO on 5 GHz "
4001                            "band");
4002                 if (wpa_s->best_5_freq > 0 &&
4003                     p2p_supported_freq(wpa_s->global->p2p,
4004                                        wpa_s->best_5_freq)) {
4005                         freq = wpa_s->best_5_freq;
4006                         wpa_printf(MSG_DEBUG, "P2P: Use best 5 GHz band "
4007                                    "channel: %d MHz", freq);
4008                 } else {
4009                         os_get_random((u8 *) &r, sizeof(r));
4010                         freq = 5180 + (r % 4) * 20;
4011                         if (!p2p_supported_freq(wpa_s->global->p2p, freq)) {
4012                                 wpa_printf(MSG_DEBUG, "P2P: Could not select "
4013                                            "5 GHz channel for P2P group");
4014                                 return -1;
4015                         }
4016                         wpa_printf(MSG_DEBUG, "P2P: Use random 5 GHz band "
4017                                    "channel: %d MHz", freq);
4018                 }
4019         }
4020
4021         if (freq > 0 && !p2p_supported_freq(wpa_s->global->p2p, freq)) {
4022                 wpa_printf(MSG_DEBUG, "P2P: The forced channel for GO "
4023                            "(%u MHz) is not supported for P2P uses",
4024                            freq);
4025                 return -1;
4026         }
4027
4028         if (wpas_p2p_init_go_params(wpa_s, &params, freq, ht40))
4029                 return -1;
4030         if (params.freq &&
4031             !p2p_supported_freq(wpa_s->global->p2p, params.freq)) {
4032                 wpa_printf(MSG_DEBUG, "P2P: The selected channel for GO "
4033                            "(%u MHz) is not supported for P2P uses",
4034                            params.freq);
4035                 return -1;
4036         }
4037         p2p_go_params(wpa_s->global->p2p, &params);
4038         params.persistent_group = persistent_group;
4039
4040         wpa_s = wpas_p2p_get_group_iface(wpa_s, 0, 1);
4041         if (wpa_s == NULL)
4042                 return -1;
4043         wpas_start_wps_go(wpa_s, &params, 0);
4044
4045         return 0;
4046 }
4047
4048
4049 static int wpas_start_p2p_client(struct wpa_supplicant *wpa_s,
4050                                  struct wpa_ssid *params, int addr_allocated)
4051 {
4052         struct wpa_ssid *ssid;
4053
4054         wpa_s = wpas_p2p_get_group_iface(wpa_s, addr_allocated, 0);
4055         if (wpa_s == NULL)
4056                 return -1;
4057
4058         wpa_supplicant_ap_deinit(wpa_s);
4059
4060         ssid = wpa_config_add_network(wpa_s->conf);
4061         if (ssid == NULL)
4062                 return -1;
4063         wpa_config_set_network_defaults(ssid);
4064         ssid->temporary = 1;
4065         ssid->proto = WPA_PROTO_RSN;
4066         ssid->pairwise_cipher = WPA_CIPHER_CCMP;
4067         ssid->group_cipher = WPA_CIPHER_CCMP;
4068         ssid->key_mgmt = WPA_KEY_MGMT_PSK;
4069         ssid->ssid = os_malloc(params->ssid_len);
4070         if (ssid->ssid == NULL) {
4071                 wpa_config_remove_network(wpa_s->conf, ssid->id);
4072                 return -1;
4073         }
4074         os_memcpy(ssid->ssid, params->ssid, params->ssid_len);
4075         ssid->ssid_len = params->ssid_len;
4076         ssid->p2p_group = 1;
4077         ssid->export_keys = 1;
4078         if (params->psk_set) {
4079                 os_memcpy(ssid->psk, params->psk, 32);
4080                 ssid->psk_set = 1;
4081         }
4082         if (params->passphrase)
4083                 ssid->passphrase = os_strdup(params->passphrase);
4084
4085         wpa_supplicant_select_network(wpa_s, ssid);
4086
4087         wpa_s->show_group_started = 1;
4088
4089         return 0;
4090 }
4091
4092
4093 int wpas_p2p_group_add_persistent(struct wpa_supplicant *wpa_s,
4094                                   struct wpa_ssid *ssid, int addr_allocated,
4095                                   int freq, int ht40)
4096 {
4097         struct p2p_go_neg_results params;
4098         int go = 0;
4099
4100         if (ssid->disabled != 2 || ssid->ssid == NULL)
4101                 return -1;
4102
4103         if (wpas_get_p2p_group(wpa_s, ssid->ssid, ssid->ssid_len, &go) &&
4104             go == (ssid->mode == WPAS_MODE_P2P_GO)) {
4105                 wpa_printf(MSG_DEBUG, "P2P: Requested persistent group is "
4106                            "already running");
4107                 return 0;
4108         }
4109
4110         /* Make sure we are not running find during connection establishment */
4111         wpas_p2p_stop_find_oper(wpa_s);
4112
4113         wpa_s->p2p_fallback_to_go_neg = 0;
4114
4115         if (ssid->mode == WPAS_MODE_INFRA)
4116                 return wpas_start_p2p_client(wpa_s, ssid, addr_allocated);
4117
4118         if (ssid->mode != WPAS_MODE_P2P_GO)
4119                 return -1;
4120
4121         if (wpas_p2p_init_go_params(wpa_s, &params, freq, ht40))
4122                 return -1;
4123
4124         params.role_go = 1;
4125         params.psk_set = ssid->psk_set;
4126         if (params.psk_set)
4127                 os_memcpy(params.psk, ssid->psk, sizeof(params.psk));
4128         if (ssid->passphrase == NULL ||
4129             os_strlen(ssid->passphrase) >= sizeof(params.passphrase)) {
4130                 wpa_printf(MSG_DEBUG, "P2P: Invalid passphrase in persistent "
4131                            "group");
4132                 return -1;
4133         }
4134         os_strlcpy(params.passphrase, ssid->passphrase,
4135                    sizeof(params.passphrase));
4136         os_memcpy(params.ssid, ssid->ssid, ssid->ssid_len);
4137         params.ssid_len = ssid->ssid_len;
4138         params.persistent_group = 1;
4139
4140         wpa_s = wpas_p2p_get_group_iface(wpa_s, addr_allocated, 1);
4141         if (wpa_s == NULL)
4142                 return -1;
4143
4144         wpas_start_wps_go(wpa_s, &params, 0);
4145
4146         return 0;
4147 }
4148
4149
4150 static void wpas_p2p_ie_update(void *ctx, struct wpabuf *beacon_ies,
4151                                struct wpabuf *proberesp_ies)
4152 {
4153         struct wpa_supplicant *wpa_s = ctx;
4154         if (wpa_s->ap_iface) {
4155                 struct hostapd_data *hapd = wpa_s->ap_iface->bss[0];
4156                 if (!(hapd->conf->p2p & P2P_GROUP_OWNER)) {
4157                         wpabuf_free(beacon_ies);
4158                         wpabuf_free(proberesp_ies);
4159                         return;
4160                 }
4161                 if (beacon_ies) {
4162                         wpabuf_free(hapd->p2p_beacon_ie);
4163                         hapd->p2p_beacon_ie = beacon_ies;
4164                 }
4165                 wpabuf_free(hapd->p2p_probe_resp_ie);
4166                 hapd->p2p_probe_resp_ie = proberesp_ies;
4167         } else {
4168                 wpabuf_free(beacon_ies);
4169                 wpabuf_free(proberesp_ies);
4170         }
4171         wpa_supplicant_ap_update_beacon(wpa_s);
4172 }
4173
4174
4175 static void wpas_p2p_idle_update(void *ctx, int idle)
4176 {
4177         struct wpa_supplicant *wpa_s = ctx;
4178         if (!wpa_s->ap_iface)
4179                 return;
4180         wpa_printf(MSG_DEBUG, "P2P: GO - group %sidle", idle ? "" : "not ");
4181         if (idle)
4182                 wpas_p2p_set_group_idle_timeout(wpa_s);
4183         else
4184                 eloop_cancel_timeout(wpas_p2p_group_idle_timeout, wpa_s, NULL);
4185 }
4186
4187
4188 struct p2p_group * wpas_p2p_group_init(struct wpa_supplicant *wpa_s,
4189                                        struct wpa_ssid *ssid)
4190 {
4191         struct p2p_group *group;
4192         struct p2p_group_config *cfg;
4193
4194         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
4195                 return NULL;
4196         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
4197                 return NULL;
4198
4199         cfg = os_zalloc(sizeof(*cfg));
4200         if (cfg == NULL)
4201                 return NULL;
4202
4203         if (ssid->p2p_persistent_group && wpa_s->conf->persistent_reconnect)
4204                 cfg->persistent_group = 2;
4205         else if (ssid->p2p_persistent_group)
4206                 cfg->persistent_group = 1;
4207         os_memcpy(cfg->interface_addr, wpa_s->own_addr, ETH_ALEN);
4208         if (wpa_s->max_stations &&
4209             wpa_s->max_stations < wpa_s->conf->max_num_sta)
4210                 cfg->max_clients = wpa_s->max_stations;
4211         else
4212                 cfg->max_clients = wpa_s->conf->max_num_sta;
4213         os_memcpy(cfg->ssid, ssid->ssid, ssid->ssid_len);
4214         cfg->ssid_len = ssid->ssid_len;
4215         cfg->cb_ctx = wpa_s;
4216         cfg->ie_update = wpas_p2p_ie_update;
4217         cfg->idle_update = wpas_p2p_idle_update;
4218
4219         group = p2p_group_init(wpa_s->global->p2p, cfg);
4220         if (group == NULL)
4221                 os_free(cfg);
4222         if (ssid->mode != WPAS_MODE_P2P_GROUP_FORMATION)
4223                 p2p_group_notif_formation_done(group);
4224         wpa_s->p2p_group = group;
4225         return group;
4226 }
4227
4228
4229 void wpas_p2p_wps_success(struct wpa_supplicant *wpa_s, const u8 *peer_addr,
4230                           int registrar)
4231 {
4232         struct wpa_ssid *ssid = wpa_s->current_ssid;
4233
4234         if (!wpa_s->p2p_in_provisioning) {
4235                 wpa_printf(MSG_DEBUG, "P2P: Ignore WPS success event - P2P "
4236                            "provisioning not in progress");
4237                 return;
4238         }
4239
4240         if (ssid && ssid->mode == WPAS_MODE_INFRA) {
4241                 u8 go_dev_addr[ETH_ALEN];
4242                 os_memcpy(go_dev_addr, wpa_s->bssid, ETH_ALEN);
4243                 wpas_p2p_persistent_group(wpa_s, go_dev_addr, ssid->ssid,
4244                                           ssid->ssid_len);
4245                 /* Clear any stored provisioning info */
4246                 p2p_clear_provisioning_info(wpa_s->global->p2p, go_dev_addr);
4247         }
4248
4249         eloop_cancel_timeout(wpas_p2p_group_formation_timeout, wpa_s->parent,
4250                              NULL);
4251         if (ssid && ssid->mode == WPAS_MODE_INFRA) {
4252                 /*
4253                  * Use a separate timeout for initial data connection to
4254                  * complete to allow the group to be removed automatically if
4255                  * something goes wrong in this step before the P2P group idle
4256                  * timeout mechanism is taken into use.
4257                  */
4258                 eloop_register_timeout(P2P_MAX_INITIAL_CONN_WAIT, 0,
4259                                        wpas_p2p_group_formation_timeout,
4260                                        wpa_s->parent, NULL);
4261         }
4262         if (wpa_s->global->p2p)
4263                 p2p_wps_success_cb(wpa_s->global->p2p, peer_addr);
4264         else if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
4265                 wpa_drv_wps_success_cb(wpa_s, peer_addr);
4266         wpas_group_formation_completed(wpa_s, 1);
4267 }
4268
4269
4270 void wpas_p2p_wps_failed(struct wpa_supplicant *wpa_s,
4271                          struct wps_event_fail *fail)
4272 {
4273         if (!wpa_s->p2p_in_provisioning) {
4274                 wpa_printf(MSG_DEBUG, "P2P: Ignore WPS fail event - P2P "
4275                            "provisioning not in progress");
4276                 return;
4277         }
4278
4279         if (wpa_s->go_params) {
4280                 p2p_clear_provisioning_info(
4281                         wpa_s->global->p2p,
4282                         wpa_s->go_params->peer_device_addr);
4283         }
4284
4285         wpas_notify_p2p_wps_failed(wpa_s, fail);
4286 }
4287
4288
4289 int wpas_p2p_prov_disc(struct wpa_supplicant *wpa_s, const u8 *peer_addr,
4290                        const char *config_method,
4291                        enum wpas_p2p_prov_disc_use use)
4292 {
4293         u16 config_methods;
4294
4295         wpa_s->p2p_fallback_to_go_neg = 0;
4296         wpa_s->pending_pd_use = NORMAL_PD;
4297         if (os_strncmp(config_method, "display", 7) == 0)
4298                 config_methods = WPS_CONFIG_DISPLAY;
4299         else if (os_strncmp(config_method, "keypad", 6) == 0)
4300                 config_methods = WPS_CONFIG_KEYPAD;
4301         else if (os_strncmp(config_method, "pbc", 3) == 0 ||
4302                  os_strncmp(config_method, "pushbutton", 10) == 0)
4303                 config_methods = WPS_CONFIG_PUSHBUTTON;
4304         else {
4305                 wpa_printf(MSG_DEBUG, "P2P: Unknown config method");
4306                 return -1;
4307         }
4308
4309         if (use == WPAS_P2P_PD_AUTO) {
4310                 os_memcpy(wpa_s->pending_join_dev_addr, peer_addr, ETH_ALEN);
4311                 wpa_s->pending_pd_config_methods = config_methods;
4312                 wpa_s->p2p_auto_pd = 1;
4313                 wpa_s->p2p_auto_join = 0;
4314                 wpa_s->pending_pd_before_join = 0;
4315                 wpa_s->auto_pd_scan_retry = 0;
4316                 wpas_p2p_stop_find(wpa_s);
4317                 wpa_s->p2p_join_scan_count = 0;
4318                 os_get_time(&wpa_s->p2p_auto_started);
4319                 wpa_printf(MSG_DEBUG, "P2P: Auto PD started at %ld.%06ld",
4320                            wpa_s->p2p_auto_started.sec,
4321                            wpa_s->p2p_auto_started.usec);
4322                 wpas_p2p_join_scan(wpa_s, NULL);
4323                 return 0;
4324         }
4325
4326         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT) {
4327                 return wpa_drv_p2p_prov_disc_req(wpa_s, peer_addr,
4328                                                  config_methods,
4329                                                  use == WPAS_P2P_PD_FOR_JOIN);
4330         }
4331
4332         if (wpa_s->global->p2p == NULL || wpa_s->global->p2p_disabled)
4333                 return -1;
4334
4335         return p2p_prov_disc_req(wpa_s->global->p2p, peer_addr,
4336                                  config_methods, use == WPAS_P2P_PD_FOR_JOIN,
4337                                  0);
4338 }
4339
4340
4341 int wpas_p2p_scan_result_text(const u8 *ies, size_t ies_len, char *buf,
4342                               char *end)
4343 {
4344         return p2p_scan_result_text(ies, ies_len, buf, end);
4345 }
4346
4347
4348 static void wpas_p2p_clear_pending_action_tx(struct wpa_supplicant *wpa_s)
4349 {
4350         if (!wpa_s->pending_action_tx)
4351                 return;
4352
4353         wpa_printf(MSG_DEBUG, "P2P: Drop pending Action TX due to new "
4354                    "operation request");
4355         wpabuf_free(wpa_s->pending_action_tx);
4356         wpa_s->pending_action_tx = NULL;
4357 }
4358
4359
4360 int wpas_p2p_find(struct wpa_supplicant *wpa_s, unsigned int timeout,
4361                   enum p2p_discovery_type type,
4362                   unsigned int num_req_dev_types, const u8 *req_dev_types,
4363                   const u8 *dev_id, unsigned int search_delay)
4364 {
4365         wpas_p2p_clear_pending_action_tx(wpa_s);
4366         wpa_s->p2p_long_listen = 0;
4367
4368         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
4369                 return wpa_drv_p2p_find(wpa_s, timeout, type);
4370
4371         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL ||
4372             wpa_s->p2p_in_provisioning)
4373                 return -1;
4374
4375         wpa_supplicant_cancel_sched_scan(wpa_s);
4376
4377         return p2p_find(wpa_s->global->p2p, timeout, type,
4378                         num_req_dev_types, req_dev_types, dev_id,
4379                         search_delay);
4380 }
4381
4382
4383 static int wpas_p2p_stop_find_oper(struct wpa_supplicant *wpa_s)
4384 {
4385         wpas_p2p_clear_pending_action_tx(wpa_s);
4386         wpa_s->p2p_long_listen = 0;
4387         eloop_cancel_timeout(wpas_p2p_long_listen_timeout, wpa_s, NULL);
4388         eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
4389         wpa_s->global->p2p_cb_on_scan_complete = 0;
4390
4391         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT) {
4392                 wpa_drv_p2p_stop_find(wpa_s);
4393                 return 1;
4394         }
4395
4396         if (wpa_s->global->p2p)
4397                 p2p_stop_find(wpa_s->global->p2p);
4398
4399         return 0;
4400 }
4401
4402
4403 void wpas_p2p_stop_find(struct wpa_supplicant *wpa_s)
4404 {
4405         if (wpas_p2p_stop_find_oper(wpa_s) > 0)
4406                 return;
4407         wpas_p2p_remove_pending_group_interface(wpa_s);
4408 }
4409
4410
4411 static void wpas_p2p_long_listen_timeout(void *eloop_ctx, void *timeout_ctx)
4412 {
4413         struct wpa_supplicant *wpa_s = eloop_ctx;
4414         wpa_s->p2p_long_listen = 0;
4415 }
4416
4417
4418 int wpas_p2p_listen(struct wpa_supplicant *wpa_s, unsigned int timeout)
4419 {
4420         int res;
4421
4422         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
4423                 return -1;
4424
4425         wpa_supplicant_cancel_sched_scan(wpa_s);
4426         wpas_p2p_clear_pending_action_tx(wpa_s);
4427
4428         if (timeout == 0) {
4429                 /*
4430                  * This is a request for unlimited Listen state. However, at
4431                  * least for now, this is mapped to a Listen state for one
4432                  * hour.
4433                  */
4434                 timeout = 3600;
4435         }
4436         eloop_cancel_timeout(wpas_p2p_long_listen_timeout, wpa_s, NULL);
4437         wpa_s->p2p_long_listen = 0;
4438
4439         /*
4440          * Stop previous find/listen operation to avoid trying to request a new
4441          * remain-on-channel operation while the driver is still running the
4442          * previous one.
4443          */
4444         if (wpa_s->global->p2p)
4445                 p2p_stop_find(wpa_s->global->p2p);
4446
4447         res = wpas_p2p_listen_start(wpa_s, timeout * 1000);
4448         if (res == 0 && timeout * 1000 > wpa_s->max_remain_on_chan) {
4449                 wpa_s->p2p_long_listen = timeout * 1000;
4450                 eloop_register_timeout(timeout, 0,
4451                                        wpas_p2p_long_listen_timeout,
4452                                        wpa_s, NULL);
4453         }
4454
4455         return res;
4456 }
4457
4458
4459 int wpas_p2p_assoc_req_ie(struct wpa_supplicant *wpa_s, struct wpa_bss *bss,
4460                           u8 *buf, size_t len, int p2p_group)
4461 {
4462         struct wpabuf *p2p_ie;
4463         int ret;
4464
4465         if (wpa_s->global->p2p_disabled)
4466                 return -1;
4467         if (wpa_s->global->p2p == NULL)
4468                 return -1;
4469         if (bss == NULL)
4470                 return -1;
4471
4472         p2p_ie = wpa_bss_get_vendor_ie_multi(bss, P2P_IE_VENDOR_TYPE);
4473         ret = p2p_assoc_req_ie(wpa_s->global->p2p, bss->bssid, buf, len,
4474                                p2p_group, p2p_ie);
4475         wpabuf_free(p2p_ie);
4476
4477         return ret;
4478 }
4479
4480
4481 int wpas_p2p_probe_req_rx(struct wpa_supplicant *wpa_s, const u8 *addr,
4482                           const u8 *dst, const u8 *bssid,
4483                           const u8 *ie, size_t ie_len, int ssi_signal)
4484 {
4485         if (wpa_s->global->p2p_disabled)
4486                 return 0;
4487         if (wpa_s->global->p2p == NULL)
4488                 return 0;
4489
4490         switch (p2p_probe_req_rx(wpa_s->global->p2p, addr, dst, bssid,
4491                                  ie, ie_len)) {
4492         case P2P_PREQ_NOT_P2P:
4493                 wpas_notify_preq(wpa_s, addr, dst, bssid, ie, ie_len,
4494                                  ssi_signal);
4495                 /* fall through */
4496         case P2P_PREQ_MALFORMED:
4497         case P2P_PREQ_NOT_LISTEN:
4498         case P2P_PREQ_NOT_PROCESSED:
4499         default: /* make gcc happy */
4500                 return 0;
4501         case P2P_PREQ_PROCESSED:
4502                 return 1;
4503         }
4504 }
4505
4506
4507 void wpas_p2p_rx_action(struct wpa_supplicant *wpa_s, const u8 *da,
4508                         const u8 *sa, const u8 *bssid,
4509                         u8 category, const u8 *data, size_t len, int freq)
4510 {
4511         if (wpa_s->global->p2p_disabled)
4512                 return;
4513         if (wpa_s->global->p2p == NULL)
4514                 return;
4515
4516         p2p_rx_action(wpa_s->global->p2p, da, sa, bssid, category, data, len,
4517                       freq);
4518 }
4519
4520
4521 void wpas_p2p_scan_ie(struct wpa_supplicant *wpa_s, struct wpabuf *ies)
4522 {
4523         if (wpa_s->global->p2p_disabled)
4524                 return;
4525         if (wpa_s->global->p2p == NULL)
4526                 return;
4527
4528         p2p_scan_ie(wpa_s->global->p2p, ies, NULL);
4529 }
4530
4531
4532 void wpas_p2p_group_deinit(struct wpa_supplicant *wpa_s)
4533 {
4534         p2p_group_deinit(wpa_s->p2p_group);
4535         wpa_s->p2p_group = NULL;
4536
4537         wpa_s->ap_configured_cb = NULL;
4538         wpa_s->ap_configured_cb_ctx = NULL;
4539         wpa_s->ap_configured_cb_data = NULL;
4540         wpa_s->connect_without_scan = NULL;
4541 }
4542
4543
4544 int wpas_p2p_reject(struct wpa_supplicant *wpa_s, const u8 *addr)
4545 {
4546         wpa_s->p2p_long_listen = 0;
4547
4548         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
4549                 return wpa_drv_p2p_reject(wpa_s, addr);
4550
4551         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
4552                 return -1;
4553
4554         return p2p_reject(wpa_s->global->p2p, addr);
4555 }
4556
4557
4558 /* Invite to reinvoke a persistent group */
4559 int wpas_p2p_invite(struct wpa_supplicant *wpa_s, const u8 *peer_addr,
4560                     struct wpa_ssid *ssid, const u8 *go_dev_addr, int freq,
4561                     int ht40)
4562 {
4563         enum p2p_invite_role role;
4564         u8 *bssid = NULL;
4565
4566         wpa_s->p2p_persistent_go_freq = freq;
4567         wpa_s->p2p_go_ht40 = !!ht40;
4568         if (ssid->mode == WPAS_MODE_P2P_GO) {
4569                 role = P2P_INVITE_ROLE_GO;
4570                 if (peer_addr == NULL) {
4571                         wpa_printf(MSG_DEBUG, "P2P: Missing peer "
4572                                    "address in invitation command");
4573                         return -1;
4574                 }
4575                 if (wpas_p2p_create_iface(wpa_s)) {
4576                         if (wpas_p2p_add_group_interface(wpa_s,
4577                                                          WPA_IF_P2P_GO) < 0) {
4578                                 wpa_printf(MSG_ERROR, "P2P: Failed to "
4579                                            "allocate a new interface for the "
4580                                            "group");
4581                                 return -1;
4582                         }
4583                         bssid = wpa_s->pending_interface_addr;
4584                 } else
4585                         bssid = wpa_s->own_addr;
4586         } else {
4587                 role = P2P_INVITE_ROLE_CLIENT;
4588                 peer_addr = ssid->bssid;
4589         }
4590         wpa_s->pending_invite_ssid_id = ssid->id;
4591
4592         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
4593                 return wpa_drv_p2p_invite(wpa_s, peer_addr, role, bssid,
4594                                           ssid->ssid, ssid->ssid_len,
4595                                           go_dev_addr, 1);
4596
4597         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
4598                 return -1;
4599
4600         return p2p_invite(wpa_s->global->p2p, peer_addr, role, bssid,
4601                           ssid->ssid, ssid->ssid_len, freq, go_dev_addr, 1);
4602 }
4603
4604
4605 /* Invite to join an active group */
4606 int wpas_p2p_invite_group(struct wpa_supplicant *wpa_s, const char *ifname,
4607                           const u8 *peer_addr, const u8 *go_dev_addr)
4608 {
4609         struct wpa_global *global = wpa_s->global;
4610         enum p2p_invite_role role;
4611         u8 *bssid = NULL;
4612         struct wpa_ssid *ssid;
4613         int persistent;
4614
4615         wpa_s->p2p_persistent_go_freq = 0;
4616         wpa_s->p2p_go_ht40 = 0;
4617
4618         for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) {
4619                 if (os_strcmp(wpa_s->ifname, ifname) == 0)
4620                         break;
4621         }
4622         if (wpa_s == NULL) {
4623                 wpa_printf(MSG_DEBUG, "P2P: Interface '%s' not found", ifname);
4624                 return -1;
4625         }
4626
4627         ssid = wpa_s->current_ssid;
4628         if (ssid == NULL) {
4629                 wpa_printf(MSG_DEBUG, "P2P: No current SSID to use for "
4630                            "invitation");
4631                 return -1;
4632         }
4633
4634         persistent = ssid->p2p_persistent_group &&
4635                 wpas_p2p_get_persistent(wpa_s->parent, peer_addr,
4636                                         ssid->ssid, ssid->ssid_len);
4637
4638         if (ssid->mode == WPAS_MODE_P2P_GO) {
4639                 role = P2P_INVITE_ROLE_ACTIVE_GO;
4640                 bssid = wpa_s->own_addr;
4641                 if (go_dev_addr == NULL)
4642                         go_dev_addr = wpa_s->global->p2p_dev_addr;
4643         } else {
4644                 role = P2P_INVITE_ROLE_CLIENT;
4645                 if (wpa_s->wpa_state < WPA_ASSOCIATED) {
4646                         wpa_printf(MSG_DEBUG, "P2P: Not associated - cannot "
4647                                    "invite to current group");
4648                         return -1;
4649                 }
4650                 bssid = wpa_s->bssid;
4651                 if (go_dev_addr == NULL &&
4652                     !is_zero_ether_addr(wpa_s->go_dev_addr))
4653                         go_dev_addr = wpa_s->go_dev_addr;
4654         }
4655         wpa_s->parent->pending_invite_ssid_id = -1;
4656
4657         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
4658                 return wpa_drv_p2p_invite(wpa_s, peer_addr, role, bssid,
4659                                           ssid->ssid, ssid->ssid_len,
4660                                           go_dev_addr, persistent);
4661
4662         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
4663                 return -1;
4664
4665         return p2p_invite(wpa_s->global->p2p, peer_addr, role, bssid,
4666                           ssid->ssid, ssid->ssid_len, wpa_s->assoc_freq,
4667                           go_dev_addr, persistent);
4668 }
4669
4670
4671 void wpas_p2p_completed(struct wpa_supplicant *wpa_s)
4672 {
4673         struct wpa_ssid *ssid = wpa_s->current_ssid;
4674         const char *ssid_txt;
4675         u8 go_dev_addr[ETH_ALEN];
4676         int network_id = -1;
4677         int persistent;
4678         int freq;
4679
4680         if (ssid == NULL || ssid->mode != WPAS_MODE_P2P_GROUP_FORMATION) {
4681                 eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
4682                                      wpa_s->parent, NULL);
4683         }
4684
4685         if (!wpa_s->show_group_started || !ssid)
4686                 goto done;
4687
4688         wpa_s->show_group_started = 0;
4689
4690         ssid_txt = wpa_ssid_txt(ssid->ssid, ssid->ssid_len);
4691         os_memset(go_dev_addr, 0, ETH_ALEN);
4692         if (ssid->bssid_set)
4693                 os_memcpy(go_dev_addr, ssid->bssid, ETH_ALEN);
4694         persistent = wpas_p2p_persistent_group(wpa_s, go_dev_addr, ssid->ssid,
4695                                                ssid->ssid_len);
4696         os_memcpy(wpa_s->go_dev_addr, go_dev_addr, ETH_ALEN);
4697
4698         if (wpa_s->global->p2p_group_formation == wpa_s)
4699                 wpa_s->global->p2p_group_formation = NULL;
4700
4701         freq = wpa_s->current_bss ? wpa_s->current_bss->freq :
4702                 (int) wpa_s->assoc_freq;
4703         if (ssid->passphrase == NULL && ssid->psk_set) {
4704                 char psk[65];
4705                 wpa_snprintf_hex(psk, sizeof(psk), ssid->psk, 32);
4706                 wpa_msg(wpa_s->parent, MSG_INFO, P2P_EVENT_GROUP_STARTED
4707                         "%s client ssid=\"%s\" freq=%d psk=%s go_dev_addr="
4708                         MACSTR "%s",
4709                         wpa_s->ifname, ssid_txt, freq, psk,
4710                         MAC2STR(go_dev_addr),
4711                         persistent ? " [PERSISTENT]" : "");
4712         } else {
4713                 wpa_msg(wpa_s->parent, MSG_INFO, P2P_EVENT_GROUP_STARTED
4714                         "%s client ssid=\"%s\" freq=%d passphrase=\"%s\" "
4715                         "go_dev_addr=" MACSTR "%s",
4716                         wpa_s->ifname, ssid_txt, freq,
4717                         ssid->passphrase ? ssid->passphrase : "",
4718                         MAC2STR(go_dev_addr),
4719                         persistent ? " [PERSISTENT]" : "");
4720         }
4721
4722         if (persistent)
4723                 network_id = wpas_p2p_store_persistent_group(wpa_s->parent,
4724                                                              ssid, go_dev_addr);
4725         if (network_id < 0)
4726                 network_id = ssid->id;
4727         wpas_notify_p2p_group_started(wpa_s, ssid, network_id, 1);
4728
4729 done:
4730         if (wpa_s->global->p2p_cb_on_scan_complete && !wpa_s->global->p2p_disabled &&
4731             wpa_s->global->p2p != NULL) {
4732                 wpa_s->global->p2p_cb_on_scan_complete = 0;
4733                 if (p2p_other_scan_completed(wpa_s->global->p2p) == 1) {
4734                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Pending P2P operation "
4735                                 "continued after successful connection");
4736                         p2p_increase_search_delay(
4737                                 wpa_s->global->p2p,
4738                                 wpas_p2p_search_delay(wpa_s));
4739                 }
4740         }
4741 }
4742
4743
4744 int wpas_p2p_presence_req(struct wpa_supplicant *wpa_s, u32 duration1,
4745                           u32 interval1, u32 duration2, u32 interval2)
4746 {
4747         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
4748                 return -1;
4749         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
4750                 return -1;
4751
4752         if (wpa_s->wpa_state < WPA_ASSOCIATED ||
4753             wpa_s->current_ssid == NULL ||
4754             wpa_s->current_ssid->mode != WPAS_MODE_INFRA)
4755                 return -1;
4756
4757         return p2p_presence_req(wpa_s->global->p2p, wpa_s->bssid,
4758                                 wpa_s->own_addr, wpa_s->assoc_freq,
4759                                 duration1, interval1, duration2, interval2);
4760 }
4761
4762
4763 int wpas_p2p_ext_listen(struct wpa_supplicant *wpa_s, unsigned int period,
4764                         unsigned int interval)
4765 {
4766         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
4767                 return -1;
4768
4769         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
4770                 return -1;
4771
4772         return p2p_ext_listen(wpa_s->global->p2p, period, interval);
4773 }
4774
4775
4776 static int wpas_p2p_is_client(struct wpa_supplicant *wpa_s)
4777 {
4778         if (wpa_s->current_ssid == NULL) {
4779                 /*
4780                  * current_ssid can be cleared when P2P client interface gets
4781                  * disconnected, so assume this interface was used as P2P
4782                  * client.
4783                  */
4784                 return 1;
4785         }
4786         return wpa_s->current_ssid->p2p_group &&
4787                 wpa_s->current_ssid->mode == WPAS_MODE_INFRA;
4788 }
4789
4790
4791 static void wpas_p2p_group_idle_timeout(void *eloop_ctx, void *timeout_ctx)
4792 {
4793         struct wpa_supplicant *wpa_s = eloop_ctx;
4794
4795         if (wpa_s->conf->p2p_group_idle == 0 && !wpas_p2p_is_client(wpa_s)) {
4796                 wpa_printf(MSG_DEBUG, "P2P: Ignore group idle timeout - "
4797                            "disabled");
4798                 return;
4799         }
4800
4801         wpa_printf(MSG_DEBUG, "P2P: Group idle timeout reached - terminate "
4802                    "group");
4803         wpas_p2p_group_delete(wpa_s, P2P_GROUP_REMOVAL_IDLE_TIMEOUT);
4804 }
4805
4806
4807 static void wpas_p2p_set_group_idle_timeout(struct wpa_supplicant *wpa_s)
4808 {
4809         int timeout;
4810
4811         if (eloop_cancel_timeout(wpas_p2p_group_idle_timeout, wpa_s, NULL) > 0)
4812                 wpa_printf(MSG_DEBUG, "P2P: Cancelled P2P group idle timeout");
4813
4814         if (wpa_s->current_ssid == NULL || !wpa_s->current_ssid->p2p_group)
4815                 return;
4816
4817         timeout = wpa_s->conf->p2p_group_idle;
4818         if (wpa_s->current_ssid->mode == WPAS_MODE_INFRA &&
4819             (timeout == 0 || timeout > P2P_MAX_CLIENT_IDLE))
4820             timeout = P2P_MAX_CLIENT_IDLE;
4821
4822         if (timeout == 0)
4823                 return;
4824
4825         if (timeout < 0) {
4826                 if (wpa_s->current_ssid->mode == WPAS_MODE_INFRA)
4827                         timeout = 0; /* special client mode no-timeout */
4828                 else
4829                         return;
4830         }
4831
4832         if (wpa_s->p2p_in_provisioning) {
4833                 /*
4834                  * Use the normal group formation timeout during the
4835                  * provisioning phase to avoid terminating this process too
4836                  * early due to group idle timeout.
4837                  */
4838                 wpa_printf(MSG_DEBUG, "P2P: Do not use P2P group idle timeout "
4839                            "during provisioning");
4840                 return;
4841         }
4842
4843         if (wpa_s->show_group_started) {
4844                 /*
4845                  * Use the normal group formation timeout between the end of
4846                  * the provisioning phase and completion of 4-way handshake to
4847                  * avoid terminating this process too early due to group idle
4848                  * timeout.
4849                  */
4850                 wpa_printf(MSG_DEBUG, "P2P: Do not use P2P group idle timeout "
4851                            "while waiting for initial 4-way handshake to "
4852                            "complete");
4853                 return;
4854         }
4855
4856         wpa_printf(MSG_DEBUG, "P2P: Set P2P group idle timeout to %u seconds",
4857                    timeout);
4858         eloop_register_timeout(timeout, 0, wpas_p2p_group_idle_timeout,
4859                                wpa_s, NULL);
4860 }
4861
4862
4863 /* Returns 1 if the interface was removed */
4864 int wpas_p2p_deauth_notif(struct wpa_supplicant *wpa_s, const u8 *bssid,
4865                           u16 reason_code, const u8 *ie, size_t ie_len,
4866                           int locally_generated)
4867 {
4868         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
4869                 return 0;
4870         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
4871                 return 0;
4872
4873         if (!locally_generated)
4874                 p2p_deauth_notif(wpa_s->global->p2p, bssid, reason_code, ie,
4875                                  ie_len);
4876
4877         if (reason_code == WLAN_REASON_DEAUTH_LEAVING && !locally_generated &&
4878             wpa_s->current_ssid &&
4879             wpa_s->current_ssid->p2p_group &&
4880             wpa_s->current_ssid->mode == WPAS_MODE_INFRA) {
4881                 wpa_printf(MSG_DEBUG, "P2P: GO indicated that the P2P Group "
4882                            "session is ending");
4883                 if (wpas_p2p_group_delete(wpa_s,
4884                                           P2P_GROUP_REMOVAL_GO_ENDING_SESSION)
4885                     > 0)
4886                         return 1;
4887         }
4888
4889         return 0;
4890 }
4891
4892
4893 void wpas_p2p_disassoc_notif(struct wpa_supplicant *wpa_s, const u8 *bssid,
4894                              u16 reason_code, const u8 *ie, size_t ie_len,
4895                              int locally_generated)
4896 {
4897         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
4898                 return;
4899         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
4900                 return;
4901
4902         if (!locally_generated)
4903                 p2p_disassoc_notif(wpa_s->global->p2p, bssid, reason_code, ie,
4904                                    ie_len);
4905 }
4906
4907
4908 void wpas_p2p_update_config(struct wpa_supplicant *wpa_s)
4909 {
4910         struct p2p_data *p2p = wpa_s->global->p2p;
4911
4912         if (p2p == NULL)
4913                 return;
4914
4915         if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_CAPABLE))
4916                 return;
4917
4918         if (wpa_s->conf->changed_parameters & CFG_CHANGED_DEVICE_NAME)
4919                 p2p_set_dev_name(p2p, wpa_s->conf->device_name);
4920
4921         if (wpa_s->conf->changed_parameters & CFG_CHANGED_DEVICE_TYPE)
4922                 p2p_set_pri_dev_type(p2p, wpa_s->conf->device_type);
4923
4924         if (wpa_s->wps &&
4925             (wpa_s->conf->changed_parameters & CFG_CHANGED_CONFIG_METHODS))
4926                 p2p_set_config_methods(p2p, wpa_s->wps->config_methods);
4927
4928         if (wpa_s->wps && (wpa_s->conf->changed_parameters & CFG_CHANGED_UUID))
4929                 p2p_set_uuid(p2p, wpa_s->wps->uuid);
4930
4931         if (wpa_s->conf->changed_parameters & CFG_CHANGED_WPS_STRING) {
4932                 p2p_set_manufacturer(p2p, wpa_s->conf->manufacturer);
4933                 p2p_set_model_name(p2p, wpa_s->conf->model_name);
4934                 p2p_set_model_number(p2p, wpa_s->conf->model_number);
4935                 p2p_set_serial_number(p2p, wpa_s->conf->serial_number);
4936         }
4937
4938         if (wpa_s->conf->changed_parameters & CFG_CHANGED_SEC_DEVICE_TYPE)
4939                 p2p_set_sec_dev_types(p2p,
4940                                       (void *) wpa_s->conf->sec_device_type,
4941                                       wpa_s->conf->num_sec_device_types);
4942
4943         if (wpa_s->conf->changed_parameters & CFG_CHANGED_VENDOR_EXTENSION) {
4944                 int i;
4945                 p2p_remove_wps_vendor_extensions(p2p);
4946                 for (i = 0; i < MAX_WPS_VENDOR_EXT; i++) {
4947                         if (wpa_s->conf->wps_vendor_ext[i] == NULL)
4948                                 continue;
4949                         p2p_add_wps_vendor_extension(
4950                                 p2p, wpa_s->conf->wps_vendor_ext[i]);
4951                 }
4952         }
4953
4954         if ((wpa_s->conf->changed_parameters & CFG_CHANGED_COUNTRY) &&
4955             wpa_s->conf->country[0] && wpa_s->conf->country[1]) {
4956                 char country[3];
4957                 country[0] = wpa_s->conf->country[0];
4958                 country[1] = wpa_s->conf->country[1];
4959                 country[2] = 0x04;
4960                 p2p_set_country(p2p, country);
4961         }
4962
4963         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_SSID_POSTFIX) {
4964                 p2p_set_ssid_postfix(p2p, (u8 *) wpa_s->conf->p2p_ssid_postfix,
4965                                      wpa_s->conf->p2p_ssid_postfix ?
4966                                      os_strlen(wpa_s->conf->p2p_ssid_postfix) :
4967                                      0);
4968         }
4969
4970         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_INTRA_BSS)
4971                 p2p_set_intra_bss_dist(p2p, wpa_s->conf->p2p_intra_bss);
4972
4973         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_LISTEN_CHANNEL) {
4974                 u8 reg_class, channel;
4975                 int ret;
4976                 unsigned int r;
4977                 if (wpa_s->conf->p2p_listen_reg_class &&
4978                     wpa_s->conf->p2p_listen_channel) {
4979                         reg_class = wpa_s->conf->p2p_listen_reg_class;
4980                         channel = wpa_s->conf->p2p_listen_channel;
4981                 } else {
4982                         reg_class = 81;
4983                         /*
4984                          * Pick one of the social channels randomly as the
4985                          * listen channel.
4986                          */
4987                         os_get_random((u8 *) &r, sizeof(r));
4988                         channel = 1 + (r % 3) * 5;
4989                 }
4990                 ret = p2p_set_listen_channel(p2p, reg_class, channel);
4991                 if (ret)
4992                         wpa_printf(MSG_ERROR, "P2P: Own listen channel update "
4993                                    "failed: %d", ret);
4994         }
4995         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_OPER_CHANNEL) {
4996                 u8 op_reg_class, op_channel, cfg_op_channel;
4997                 int ret = 0;
4998                 unsigned int r;
4999                 if (wpa_s->conf->p2p_oper_reg_class &&
5000                     wpa_s->conf->p2p_oper_channel) {
5001                         op_reg_class = wpa_s->conf->p2p_oper_reg_class;
5002                         op_channel = wpa_s->conf->p2p_oper_channel;
5003                         cfg_op_channel = 1;
5004                 } else {
5005                         op_reg_class = 81;
5006                         /*
5007                          * Use random operation channel from (1, 6, 11)
5008                          *if no other preference is indicated.
5009                          */
5010                         os_get_random((u8 *) &r, sizeof(r));
5011                         op_channel = 1 + (r % 3) * 5;
5012                         cfg_op_channel = 0;
5013                 }
5014                 ret = p2p_set_oper_channel(p2p, op_reg_class, op_channel,
5015                                            cfg_op_channel);
5016                 if (ret)
5017                         wpa_printf(MSG_ERROR, "P2P: Own oper channel update "
5018                                    "failed: %d", ret);
5019         }
5020
5021         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_PREF_CHAN) {
5022                 if (p2p_set_pref_chan(p2p, wpa_s->conf->num_p2p_pref_chan,
5023                                       wpa_s->conf->p2p_pref_chan) < 0) {
5024                         wpa_printf(MSG_ERROR, "P2P: Preferred channel list "
5025                                    "update failed");
5026                 }
5027         }
5028 }
5029
5030
5031 int wpas_p2p_set_noa(struct wpa_supplicant *wpa_s, u8 count, int start,
5032                      int duration)
5033 {
5034         if (!wpa_s->ap_iface)
5035                 return -1;
5036         return hostapd_p2p_set_noa(wpa_s->ap_iface->bss[0], count, start,
5037                                    duration);
5038 }
5039
5040
5041 int wpas_p2p_set_cross_connect(struct wpa_supplicant *wpa_s, int enabled)
5042 {
5043         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5044                 return -1;
5045         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT)
5046                 return -1;
5047
5048         wpa_s->global->cross_connection = enabled;
5049         p2p_set_cross_connect(wpa_s->global->p2p, enabled);
5050
5051         if (!enabled) {
5052                 struct wpa_supplicant *iface;
5053
5054                 for (iface = wpa_s->global->ifaces; iface; iface = iface->next)
5055                 {
5056                         if (iface->cross_connect_enabled == 0)
5057                                 continue;
5058
5059                         iface->cross_connect_enabled = 0;
5060                         iface->cross_connect_in_use = 0;
5061                         wpa_msg(iface->parent, MSG_INFO,
5062                                 P2P_EVENT_CROSS_CONNECT_DISABLE "%s %s",
5063                                 iface->ifname, iface->cross_connect_uplink);
5064                 }
5065         }
5066
5067         return 0;
5068 }
5069
5070
5071 static void wpas_p2p_enable_cross_connect(struct wpa_supplicant *uplink)
5072 {
5073         struct wpa_supplicant *iface;
5074
5075         if (!uplink->global->cross_connection)
5076                 return;
5077
5078         for (iface = uplink->global->ifaces; iface; iface = iface->next) {
5079                 if (!iface->cross_connect_enabled)
5080                         continue;
5081                 if (os_strcmp(uplink->ifname, iface->cross_connect_uplink) !=
5082                     0)
5083                         continue;
5084                 if (iface->ap_iface == NULL)
5085                         continue;
5086                 if (iface->cross_connect_in_use)
5087                         continue;
5088
5089                 iface->cross_connect_in_use = 1;
5090                 wpa_msg(iface->parent, MSG_INFO,
5091                         P2P_EVENT_CROSS_CONNECT_ENABLE "%s %s",
5092                         iface->ifname, iface->cross_connect_uplink);
5093         }
5094 }
5095
5096
5097 static void wpas_p2p_disable_cross_connect(struct wpa_supplicant *uplink)
5098 {
5099         struct wpa_supplicant *iface;
5100
5101         for (iface = uplink->global->ifaces; iface; iface = iface->next) {
5102                 if (!iface->cross_connect_enabled)
5103                         continue;
5104                 if (os_strcmp(uplink->ifname, iface->cross_connect_uplink) !=
5105                     0)
5106                         continue;
5107                 if (!iface->cross_connect_in_use)
5108                         continue;
5109
5110                 wpa_msg(iface->parent, MSG_INFO,
5111                         P2P_EVENT_CROSS_CONNECT_DISABLE "%s %s",
5112                         iface->ifname, iface->cross_connect_uplink);
5113                 iface->cross_connect_in_use = 0;
5114         }
5115 }
5116
5117
5118 void wpas_p2p_notif_connected(struct wpa_supplicant *wpa_s)
5119 {
5120         if (wpa_s->ap_iface || wpa_s->current_ssid == NULL ||
5121             wpa_s->current_ssid->mode != WPAS_MODE_INFRA ||
5122             wpa_s->cross_connect_disallowed)
5123                 wpas_p2p_disable_cross_connect(wpa_s);
5124         else
5125                 wpas_p2p_enable_cross_connect(wpa_s);
5126         if (!wpa_s->ap_iface &&
5127             eloop_cancel_timeout(wpas_p2p_group_idle_timeout, wpa_s, NULL) > 0)
5128                 wpa_printf(MSG_DEBUG, "P2P: Cancelled P2P group idle timeout");
5129 }
5130
5131
5132 void wpas_p2p_notif_disconnected(struct wpa_supplicant *wpa_s)
5133 {
5134         wpas_p2p_disable_cross_connect(wpa_s);
5135         if (!wpa_s->ap_iface &&
5136             !eloop_is_timeout_registered(wpas_p2p_group_idle_timeout,
5137                                          wpa_s, NULL))
5138                 wpas_p2p_set_group_idle_timeout(wpa_s);
5139 }
5140
5141
5142 static void wpas_p2p_cross_connect_setup(struct wpa_supplicant *wpa_s)
5143 {
5144         struct wpa_supplicant *iface;
5145
5146         if (!wpa_s->global->cross_connection)
5147                 return;
5148
5149         for (iface = wpa_s->global->ifaces; iface; iface = iface->next) {
5150                 if (iface == wpa_s)
5151                         continue;
5152                 if (iface->drv_flags &
5153                     WPA_DRIVER_FLAGS_P2P_DEDICATED_INTERFACE)
5154                         continue;
5155                 if (iface->drv_flags & WPA_DRIVER_FLAGS_P2P_CAPABLE)
5156                         continue;
5157
5158                 wpa_s->cross_connect_enabled = 1;
5159                 os_strlcpy(wpa_s->cross_connect_uplink, iface->ifname,
5160                            sizeof(wpa_s->cross_connect_uplink));
5161                 wpa_printf(MSG_DEBUG, "P2P: Enable cross connection from "
5162                            "%s to %s whenever uplink is available",
5163                            wpa_s->ifname, wpa_s->cross_connect_uplink);
5164
5165                 if (iface->ap_iface || iface->current_ssid == NULL ||
5166                     iface->current_ssid->mode != WPAS_MODE_INFRA ||
5167                     iface->cross_connect_disallowed ||
5168                     iface->wpa_state != WPA_COMPLETED)
5169                         break;
5170
5171                 wpa_s->cross_connect_in_use = 1;
5172                 wpa_msg(wpa_s->parent, MSG_INFO,
5173                         P2P_EVENT_CROSS_CONNECT_ENABLE "%s %s",
5174                         wpa_s->ifname, wpa_s->cross_connect_uplink);
5175                 break;
5176         }
5177 }
5178
5179
5180 int wpas_p2p_notif_pbc_overlap(struct wpa_supplicant *wpa_s)
5181 {
5182         if (wpa_s->p2p_group_interface != P2P_GROUP_INTERFACE_CLIENT &&
5183             !wpa_s->p2p_in_provisioning)
5184                 return 0; /* not P2P client operation */
5185
5186         wpa_printf(MSG_DEBUG, "P2P: Terminate connection due to WPS PBC "
5187                    "session overlap");
5188         if (wpa_s != wpa_s->parent)
5189                 wpa_msg_ctrl(wpa_s->parent, MSG_INFO, WPS_EVENT_OVERLAP);
5190
5191         if (wpa_s->global->p2p)
5192                 p2p_group_formation_failed(wpa_s->global->p2p);
5193
5194         eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
5195                              wpa_s->parent, NULL);
5196
5197         wpas_group_formation_completed(wpa_s, 0);
5198         return 1;
5199 }
5200
5201
5202 void wpas_p2p_update_channel_list(struct wpa_supplicant *wpa_s)
5203 {
5204         struct p2p_channels chan;
5205
5206         if (wpa_s->global == NULL || wpa_s->global->p2p == NULL)
5207                 return;
5208
5209         os_memset(&chan, 0, sizeof(chan));
5210         if (wpas_p2p_setup_channels(wpa_s, &chan)) {
5211                 wpa_printf(MSG_ERROR, "P2P: Failed to update supported "
5212                            "channel list");
5213                 return;
5214         }
5215
5216         p2p_update_channel_list(wpa_s->global->p2p, &chan);
5217 }
5218
5219
5220 int wpas_p2p_cancel(struct wpa_supplicant *wpa_s)
5221 {
5222         struct wpa_global *global = wpa_s->global;
5223         int found = 0;
5224         const u8 *peer;
5225
5226         if (global->p2p == NULL)
5227                 return -1;
5228
5229         wpa_printf(MSG_DEBUG, "P2P: Request to cancel group formation");
5230
5231         if (wpa_s->pending_interface_name[0] &&
5232             !is_zero_ether_addr(wpa_s->pending_interface_addr))
5233                 found = 1;
5234
5235         peer = p2p_get_go_neg_peer(global->p2p);
5236         if (peer) {
5237                 wpa_printf(MSG_DEBUG, "P2P: Unauthorize pending GO Neg peer "
5238                            MACSTR, MAC2STR(peer));
5239                 p2p_unauthorize(global->p2p, peer);
5240                 found = 1;
5241         }
5242
5243         wpas_p2p_stop_find(wpa_s);
5244
5245         for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) {
5246                 if (wpa_s == global->p2p_group_formation &&
5247                     (wpa_s->p2p_in_provisioning ||
5248                      wpa_s->parent->pending_interface_type ==
5249                      WPA_IF_P2P_CLIENT)) {
5250                         wpa_printf(MSG_DEBUG, "P2P: Interface %s in group "
5251                                    "formation found - cancelling",
5252                                    wpa_s->ifname);
5253                         found = 1;
5254                         eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
5255                                              wpa_s->parent, NULL);
5256                         if (wpa_s->p2p_in_provisioning) {
5257                                 wpas_group_formation_completed(wpa_s, 0);
5258                                 break;
5259                         }
5260                         wpas_p2p_group_delete(wpa_s,
5261                                               P2P_GROUP_REMOVAL_REQUESTED);
5262                         break;
5263                 }
5264         }
5265
5266         if (!found) {
5267                 wpa_printf(MSG_DEBUG, "P2P: No ongoing group formation found");
5268                 return -1;
5269         }
5270
5271         return 0;
5272 }
5273
5274
5275 void wpas_p2p_interface_unavailable(struct wpa_supplicant *wpa_s)
5276 {
5277         if (wpa_s->current_ssid == NULL || !wpa_s->current_ssid->p2p_group)
5278                 return;
5279
5280         wpa_printf(MSG_DEBUG, "P2P: Remove group due to driver resource not "
5281                    "being available anymore");
5282         wpas_p2p_group_delete(wpa_s, P2P_GROUP_REMOVAL_UNAVAILABLE);
5283 }
5284
5285
5286 void wpas_p2p_update_best_channels(struct wpa_supplicant *wpa_s,
5287                                    int freq_24, int freq_5, int freq_overall)
5288 {
5289         struct p2p_data *p2p = wpa_s->global->p2p;
5290         if (p2p == NULL || (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT))
5291                 return;
5292         p2p_set_best_channels(p2p, freq_24, freq_5, freq_overall);
5293 }
5294
5295
5296 int wpas_p2p_unauthorize(struct wpa_supplicant *wpa_s, const char *addr)
5297 {
5298         u8 peer[ETH_ALEN];
5299         struct p2p_data *p2p = wpa_s->global->p2p;
5300
5301         if (p2p == NULL || (wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_MGMT))
5302                 return -1;
5303
5304         if (hwaddr_aton(addr, peer))
5305                 return -1;
5306
5307         return p2p_unauthorize(p2p, peer);
5308 }
5309
5310
5311 /**
5312  * wpas_p2p_disconnect - Disconnect from a P2P Group
5313  * @wpa_s: Pointer to wpa_supplicant data
5314  * Returns: 0 on success, -1 on failure
5315  *
5316  * This can be used to disconnect from a group in which the local end is a P2P
5317  * Client or to end a P2P Group in case the local end is the Group Owner. If a
5318  * virtual network interface was created for this group, that interface will be
5319  * removed. Otherwise, only the configured P2P group network will be removed
5320  * from the interface.
5321  */
5322 int wpas_p2p_disconnect(struct wpa_supplicant *wpa_s)
5323 {
5324
5325         if (wpa_s == NULL)
5326                 return -1;
5327
5328         return wpas_p2p_group_delete(wpa_s, P2P_GROUP_REMOVAL_REQUESTED) < 0 ?
5329                 -1 : 0;
5330 }
5331
5332
5333 int wpas_p2p_in_progress(struct wpa_supplicant *wpa_s)
5334 {
5335         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5336                 return 0;
5337
5338         return p2p_in_progress(wpa_s->global->p2p);
5339 }
5340
5341
5342 void wpas_p2p_network_removed(struct wpa_supplicant *wpa_s,
5343                               struct wpa_ssid *ssid)
5344 {
5345         if (wpa_s->p2p_in_provisioning && ssid->p2p_group &&
5346             eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
5347                                  wpa_s->parent, NULL) > 0) {
5348                 /**
5349                  * Remove the network by scheduling the group formation
5350                  * timeout to happen immediately. The teardown code
5351                  * needs to be scheduled to run asynch later so that we
5352                  * don't delete data from under ourselves unexpectedly.
5353                  * Calling wpas_p2p_group_formation_timeout directly
5354                  * causes a series of crashes in WPS failure scenarios.
5355                  */
5356                 wpa_printf(MSG_DEBUG, "P2P: Canceled group formation due to "
5357                            "P2P group network getting removed");
5358                 eloop_register_timeout(0, 0, wpas_p2p_group_formation_timeout,
5359                                        wpa_s->parent, NULL);
5360         }
5361 }
5362
5363
5364 struct wpa_ssid * wpas_p2p_get_persistent(struct wpa_supplicant *wpa_s,
5365                                           const u8 *addr, const u8 *ssid,
5366                                           size_t ssid_len)
5367 {
5368         struct wpa_ssid *s;
5369         size_t i;
5370
5371         for (s = wpa_s->conf->ssid; s; s = s->next) {
5372                 if (s->disabled != 2)
5373                         continue;
5374                 if (ssid &&
5375                     (ssid_len != s->ssid_len ||
5376                      os_memcmp(ssid, s->ssid, ssid_len) != 0))
5377                         continue;
5378                 if (os_memcmp(s->bssid, addr, ETH_ALEN) == 0)
5379                         return s; /* peer is GO in the persistent group */
5380                 if (s->mode != WPAS_MODE_P2P_GO || s->p2p_client_list == NULL)
5381                         continue;
5382                 for (i = 0; i < s->num_p2p_clients; i++) {
5383                         if (os_memcmp(s->p2p_client_list + i * ETH_ALEN,
5384                                       addr, ETH_ALEN) == 0)
5385                                 return s; /* peer is P2P client in persistent
5386                                            * group */
5387                 }
5388         }
5389
5390         return NULL;
5391 }
5392
5393
5394 void wpas_p2p_notify_ap_sta_authorized(struct wpa_supplicant *wpa_s,
5395                                        const u8 *addr)
5396 {
5397         if (addr == NULL)
5398                 return;
5399         wpas_p2p_add_persistent_group_client(wpa_s, addr);
5400 }
5401
5402
5403 static void wpas_p2p_fallback_to_go_neg(struct wpa_supplicant *wpa_s,
5404                                         int group_added)
5405 {
5406         struct wpa_supplicant *group = wpa_s;
5407         eloop_cancel_timeout(wpas_p2p_pd_before_join_timeout, wpa_s, NULL);
5408         if (wpa_s->global->p2p_group_formation)
5409                 group = wpa_s->global->p2p_group_formation;
5410         wpa_s = wpa_s->parent;
5411         offchannel_send_action_done(wpa_s);
5412         if (group_added)
5413                 wpas_p2p_group_delete(group, P2P_GROUP_REMOVAL_SILENT);
5414         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Fall back to GO Negotiation");
5415         wpas_p2p_connect(wpa_s, wpa_s->pending_join_dev_addr, wpa_s->p2p_pin,
5416                          wpa_s->p2p_wps_method, wpa_s->p2p_persistent_group, 0,
5417                          0, 0, wpa_s->p2p_go_intent, wpa_s->p2p_connect_freq,
5418                          wpa_s->p2p_persistent_id,
5419                          wpa_s->p2p_pd_before_go_neg,
5420                          wpa_s->p2p_go_ht40);
5421 }
5422
5423
5424 int wpas_p2p_scan_no_go_seen(struct wpa_supplicant *wpa_s)
5425 {
5426         if (!wpa_s->p2p_fallback_to_go_neg ||
5427             wpa_s->p2p_in_provisioning <= 5)
5428                 return 0;
5429
5430         if (wpas_p2p_peer_go(wpa_s, wpa_s->pending_join_dev_addr) > 0)
5431                 return 0; /* peer operating as a GO */
5432
5433         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: GO not found for p2p_connect-auto - "
5434                 "fallback to GO Negotiation");
5435         wpas_p2p_fallback_to_go_neg(wpa_s, 1);
5436
5437         return 1;
5438 }
5439
5440
5441 unsigned int wpas_p2p_search_delay(struct wpa_supplicant *wpa_s)
5442 {
5443         const char *rn, *rn2;
5444         struct wpa_supplicant *ifs;
5445
5446         if (wpa_s->wpa_state > WPA_SCANNING) {
5447                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Use %u ms search delay due to "
5448                         "concurrent operation",
5449                         P2P_CONCURRENT_SEARCH_DELAY);
5450                 return P2P_CONCURRENT_SEARCH_DELAY;
5451         }
5452
5453         if (!wpa_s->driver->get_radio_name)
5454                 return 0;
5455         rn = wpa_s->driver->get_radio_name(wpa_s->drv_priv);
5456         if (rn == NULL || rn[0] == '\0')
5457                 return 0;
5458
5459         for (ifs = wpa_s->global->ifaces; ifs; ifs = ifs->next) {
5460                 if (ifs == wpa_s || !ifs->driver->get_radio_name)
5461                         continue;
5462
5463                 rn2 = ifs->driver->get_radio_name(ifs->drv_priv);
5464                 if (!rn2 || os_strcmp(rn, rn2) != 0)
5465                         continue;
5466                 if (ifs->wpa_state > WPA_SCANNING) {
5467                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Use %u ms search "
5468                                 "delay due to concurrent operation on "
5469                                 "interface %s",
5470                                 P2P_CONCURRENT_SEARCH_DELAY, ifs->ifname);
5471                         return P2P_CONCURRENT_SEARCH_DELAY;
5472                 }
5473         }
5474
5475         return 0;
5476 }