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