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