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