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