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