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