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