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