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