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