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