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