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