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