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