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