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