P2P: Add a function to compute the group common freqs
[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 static void wpas_p2p_go_update_common_freqs(struct wpa_supplicant *wpa_s)
2610 {
2611         unsigned int num = P2P_MAX_CHANNELS;
2612         int *common_freqs;
2613         int ret;
2614
2615         p2p_go_dump_common_freqs(wpa_s);
2616         common_freqs = os_calloc(num, sizeof(int));
2617         if (!common_freqs)
2618                 return;
2619
2620         ret = p2p_group_get_common_freqs(wpa_s->p2p_group, common_freqs, &num);
2621         if (ret < 0) {
2622                 wpa_dbg(wpa_s, MSG_DEBUG,
2623                         "P2P: Failed to get group common freqs");
2624                 os_free(common_freqs);
2625                 return;
2626         }
2627
2628         os_free(wpa_s->p2p_group_common_freqs);
2629         wpa_s->p2p_group_common_freqs = common_freqs;
2630         wpa_s->p2p_group_common_freqs_num = num;
2631         p2p_go_dump_common_freqs(wpa_s);
2632 }
2633
2634
2635 /*
2636  * Check if the given frequency is one of the possible operating frequencies
2637  * set after the completion of the GO Negotiation.
2638  */
2639 static int wpas_p2p_go_is_peer_freq(struct wpa_supplicant *wpa_s, int freq)
2640 {
2641         unsigned int i;
2642
2643         p2p_go_dump_common_freqs(wpa_s);
2644
2645         /* assume no restrictions */
2646         if (!wpa_s->p2p_group_common_freqs_num)
2647                 return 1;
2648
2649         for (i = 0; i < wpa_s->p2p_group_common_freqs_num; i++) {
2650                 if (wpa_s->p2p_group_common_freqs[i] == freq)
2651                         return 1;
2652         }
2653         return 0;
2654 }
2655
2656
2657 /**
2658  * Pick the best frequency to use from all the currently used frequencies.
2659  */
2660 static int wpas_p2p_pick_best_used_freq(struct wpa_supplicant *wpa_s,
2661                                         struct wpa_used_freq_data *freqs,
2662                                         unsigned int num)
2663 {
2664         unsigned int i, c;
2665
2666         /* find a candidate freq that is supported by P2P */
2667         for (c = 0; c < num; c++)
2668                 if (p2p_supported_freq(wpa_s->global->p2p, freqs[c].freq))
2669                         break;
2670
2671         if (c == num)
2672                 return 0;
2673
2674         /* once we have a candidate, try to find a 'better' one */
2675         for (i = c + 1; i < num; i++) {
2676                 if (!p2p_supported_freq(wpa_s->global->p2p, freqs[i].freq))
2677                         continue;
2678
2679                 /*
2680                  * 1. Infrastructure station interfaces have higher preference.
2681                  * 2. P2P Clients have higher preference.
2682                  * 3. All others.
2683                  */
2684                 if (freqs[i].flags & WPA_FREQ_USED_BY_INFRA_STATION) {
2685                         c = i;
2686                         break;
2687                 }
2688
2689                 if ((freqs[i].flags & WPA_FREQ_USED_BY_P2P_CLIENT))
2690                         c = i;
2691         }
2692         return freqs[c].freq;
2693 }
2694
2695
2696 static u8 wpas_invitation_process(void *ctx, const u8 *sa, const u8 *bssid,
2697                                   const u8 *go_dev_addr, const u8 *ssid,
2698                                   size_t ssid_len, int *go, u8 *group_bssid,
2699                                   int *force_freq, int persistent_group,
2700                                   const struct p2p_channels *channels,
2701                                   int dev_pw_id)
2702 {
2703         struct wpa_supplicant *wpa_s = ctx;
2704         struct wpa_ssid *s;
2705         struct wpa_used_freq_data *freqs;
2706         struct wpa_supplicant *grp;
2707         int best_freq;
2708
2709         if (!persistent_group) {
2710                 wpa_printf(MSG_DEBUG, "P2P: Invitation from " MACSTR
2711                            " to join an active group (SSID: %s)",
2712                            MAC2STR(sa), wpa_ssid_txt(ssid, ssid_len));
2713                 if (!is_zero_ether_addr(wpa_s->p2p_auth_invite) &&
2714                     (os_memcmp(go_dev_addr, wpa_s->p2p_auth_invite, ETH_ALEN)
2715                      == 0 ||
2716                      os_memcmp(sa, wpa_s->p2p_auth_invite, ETH_ALEN) == 0)) {
2717                         wpa_printf(MSG_DEBUG, "P2P: Accept previously "
2718                                    "authorized invitation");
2719                         goto accept_inv;
2720                 }
2721
2722 #ifdef CONFIG_WPS_NFC
2723                 if (dev_pw_id >= 0 && wpa_s->p2p_nfc_tag_enabled &&
2724                     dev_pw_id == wpa_s->p2p_oob_dev_pw_id) {
2725                         wpa_printf(MSG_DEBUG, "P2P: Accept invitation based on local enabled NFC Tag");
2726                         wpa_s->p2p_wps_method = WPS_NFC;
2727                         wpa_s->pending_join_wps_method = WPS_NFC;
2728                         os_memcpy(wpa_s->pending_join_dev_addr,
2729                                   go_dev_addr, ETH_ALEN);
2730                         os_memcpy(wpa_s->pending_join_iface_addr,
2731                                   bssid, ETH_ALEN);
2732                         goto accept_inv;
2733                 }
2734 #endif /* CONFIG_WPS_NFC */
2735
2736                 /*
2737                  * Do not accept the invitation automatically; notify user and
2738                  * request approval.
2739                  */
2740                 return P2P_SC_FAIL_INFO_CURRENTLY_UNAVAILABLE;
2741         }
2742
2743         grp = wpas_get_p2p_group(wpa_s, ssid, ssid_len, go);
2744         if (grp) {
2745                 wpa_printf(MSG_DEBUG, "P2P: Accept invitation to already "
2746                            "running persistent group");
2747                 if (*go)
2748                         os_memcpy(group_bssid, grp->own_addr, ETH_ALEN);
2749                 goto accept_inv;
2750         }
2751
2752         if (!is_zero_ether_addr(wpa_s->p2p_auth_invite) &&
2753             os_memcmp(sa, wpa_s->p2p_auth_invite, ETH_ALEN) == 0) {
2754                 wpa_printf(MSG_DEBUG, "P2P: Accept previously initiated "
2755                            "invitation to re-invoke a persistent group");
2756                 os_memset(wpa_s->p2p_auth_invite, 0, ETH_ALEN);
2757         } else if (!wpa_s->conf->persistent_reconnect)
2758                 return P2P_SC_FAIL_INFO_CURRENTLY_UNAVAILABLE;
2759
2760         for (s = wpa_s->conf->ssid; s; s = s->next) {
2761                 if (s->disabled == 2 &&
2762                     os_memcmp(s->bssid, go_dev_addr, ETH_ALEN) == 0 &&
2763                     s->ssid_len == ssid_len &&
2764                     os_memcmp(ssid, s->ssid, ssid_len) == 0)
2765                         break;
2766         }
2767
2768         if (!s) {
2769                 wpa_printf(MSG_DEBUG, "P2P: Invitation from " MACSTR
2770                            " requested reinvocation of an unknown group",
2771                            MAC2STR(sa));
2772                 return P2P_SC_FAIL_UNKNOWN_GROUP;
2773         }
2774
2775         if (s->mode == WPAS_MODE_P2P_GO && !wpas_p2p_create_iface(wpa_s)) {
2776                 *go = 1;
2777                 if (wpa_s->wpa_state >= WPA_AUTHENTICATING) {
2778                         wpa_printf(MSG_DEBUG, "P2P: The only available "
2779                                    "interface is already in use - reject "
2780                                    "invitation");
2781                         return P2P_SC_FAIL_UNABLE_TO_ACCOMMODATE;
2782                 }
2783                 os_memcpy(group_bssid, wpa_s->own_addr, ETH_ALEN);
2784         } else if (s->mode == WPAS_MODE_P2P_GO) {
2785                 *go = 1;
2786                 if (wpas_p2p_add_group_interface(wpa_s, WPA_IF_P2P_GO) < 0)
2787                 {
2788                         wpa_printf(MSG_ERROR, "P2P: Failed to allocate a new "
2789                                    "interface address for the group");
2790                         return P2P_SC_FAIL_UNABLE_TO_ACCOMMODATE;
2791                 }
2792                 os_memcpy(group_bssid, wpa_s->pending_interface_addr,
2793                           ETH_ALEN);
2794         }
2795
2796 accept_inv:
2797         wpas_p2p_set_own_freq_preference(wpa_s, 0);
2798
2799         best_freq = 0;
2800         freqs = os_calloc(wpa_s->num_multichan_concurrent,
2801                           sizeof(struct wpa_used_freq_data));
2802         if (freqs) {
2803                 int num_channels = wpa_s->num_multichan_concurrent;
2804                 int num = wpas_p2p_valid_oper_freqs(wpa_s, freqs, num_channels);
2805                 best_freq = wpas_p2p_pick_best_used_freq(wpa_s, freqs, num);
2806                 os_free(freqs);
2807         }
2808
2809         /* Get one of the frequencies currently in use */
2810         if (best_freq > 0) {
2811                 wpa_printf(MSG_DEBUG, "P2P: Trying to prefer a channel already used by one of the interfaces");
2812                 wpas_p2p_set_own_freq_preference(wpa_s, best_freq);
2813
2814                 if (wpa_s->num_multichan_concurrent < 2 ||
2815                     wpas_p2p_num_unused_channels(wpa_s) < 1) {
2816                         wpa_printf(MSG_DEBUG, "P2P: No extra channels available - trying to force channel to match a channel already used by one of the interfaces");
2817                         *force_freq = best_freq;
2818                 }
2819         }
2820
2821         if (*force_freq > 0 && wpa_s->num_multichan_concurrent > 1 &&
2822             wpas_p2p_num_unused_channels(wpa_s) > 0) {
2823                 if (*go == 0) {
2824                         /* We are the client */
2825                         wpa_printf(MSG_DEBUG, "P2P: Peer was found to be "
2826                                    "running a GO but we are capable of MCC, "
2827                                    "figure out the best channel to use");
2828                         *force_freq = 0;
2829                 } else if (!freq_included(channels, *force_freq)) {
2830                         /* We are the GO, and *force_freq is not in the
2831                          * intersection */
2832                         wpa_printf(MSG_DEBUG, "P2P: Forced GO freq %d MHz not "
2833                                    "in intersection but we are capable of MCC, "
2834                                    "figure out the best channel to use",
2835                                    *force_freq);
2836                         *force_freq = 0;
2837                 }
2838         }
2839
2840         return P2P_SC_SUCCESS;
2841 }
2842
2843
2844 static void wpas_invitation_received(void *ctx, const u8 *sa, const u8 *bssid,
2845                                      const u8 *ssid, size_t ssid_len,
2846                                      const u8 *go_dev_addr, u8 status,
2847                                      int op_freq)
2848 {
2849         struct wpa_supplicant *wpa_s = ctx;
2850         struct wpa_ssid *s;
2851
2852         for (s = wpa_s->conf->ssid; s; s = s->next) {
2853                 if (s->disabled == 2 &&
2854                     s->ssid_len == ssid_len &&
2855                     os_memcmp(ssid, s->ssid, ssid_len) == 0)
2856                         break;
2857         }
2858
2859         if (status == P2P_SC_SUCCESS) {
2860                 wpa_printf(MSG_DEBUG, "P2P: Invitation from peer " MACSTR
2861                            " was accepted; op_freq=%d MHz, SSID=%s",
2862                            MAC2STR(sa), op_freq, wpa_ssid_txt(ssid, ssid_len));
2863                 if (s) {
2864                         int go = s->mode == WPAS_MODE_P2P_GO;
2865                         wpas_p2p_group_add_persistent(
2866                                 wpa_s, s, go, 0, op_freq, 0, 0, NULL,
2867                                 go ? P2P_MAX_INITIAL_CONN_WAIT_GO_REINVOKE : 0);
2868                 } else if (bssid) {
2869                         wpa_s->user_initiated_pd = 0;
2870                         wpas_p2p_join(wpa_s, bssid, go_dev_addr,
2871                                       wpa_s->p2p_wps_method, 0, op_freq,
2872                                       ssid, ssid_len);
2873                 }
2874                 return;
2875         }
2876
2877         if (status != P2P_SC_FAIL_INFO_CURRENTLY_UNAVAILABLE) {
2878                 wpa_printf(MSG_DEBUG, "P2P: Invitation from peer " MACSTR
2879                            " was rejected (status %u)", MAC2STR(sa), status);
2880                 return;
2881         }
2882
2883         if (!s) {
2884                 if (bssid) {
2885                         wpa_msg_global(wpa_s, MSG_INFO,
2886                                        P2P_EVENT_INVITATION_RECEIVED
2887                                        "sa=" MACSTR " go_dev_addr=" MACSTR
2888                                        " bssid=" MACSTR " unknown-network",
2889                                        MAC2STR(sa), MAC2STR(go_dev_addr),
2890                                        MAC2STR(bssid));
2891                 } else {
2892                         wpa_msg_global(wpa_s, MSG_INFO,
2893                                        P2P_EVENT_INVITATION_RECEIVED
2894                                        "sa=" MACSTR " go_dev_addr=" MACSTR
2895                                        " unknown-network",
2896                                        MAC2STR(sa), MAC2STR(go_dev_addr));
2897                 }
2898                 return;
2899         }
2900
2901         if (s->mode == WPAS_MODE_P2P_GO && op_freq) {
2902                 wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_INVITATION_RECEIVED
2903                                "sa=" MACSTR " persistent=%d freq=%d",
2904                                MAC2STR(sa), s->id, op_freq);
2905         } else {
2906                 wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_INVITATION_RECEIVED
2907                                "sa=" MACSTR " persistent=%d",
2908                                MAC2STR(sa), s->id);
2909         }
2910 }
2911
2912
2913 static void wpas_remove_persistent_peer(struct wpa_supplicant *wpa_s,
2914                                         struct wpa_ssid *ssid,
2915                                         const u8 *peer, int inv)
2916 {
2917         size_t i;
2918         struct wpa_supplicant *p2p_wpa_s = wpa_s->global->p2p_init_wpa_s;
2919
2920         if (ssid == NULL)
2921                 return;
2922
2923         for (i = 0; ssid->p2p_client_list && i < ssid->num_p2p_clients; i++) {
2924                 if (os_memcmp(ssid->p2p_client_list + i * 2 * ETH_ALEN, peer,
2925                               ETH_ALEN) == 0)
2926                         break;
2927         }
2928         if (i >= ssid->num_p2p_clients || !ssid->p2p_client_list) {
2929                 if (ssid->mode != WPAS_MODE_P2P_GO &&
2930                     os_memcmp(ssid->bssid, peer, ETH_ALEN) == 0) {
2931                         wpa_printf(MSG_DEBUG, "P2P: Remove persistent group %d "
2932                                    "due to invitation result", ssid->id);
2933                         wpas_notify_network_removed(wpa_s, ssid);
2934                         wpa_config_remove_network(wpa_s->conf, ssid->id);
2935                         return;
2936                 }
2937                 return; /* Peer not found in client list */
2938         }
2939
2940         wpa_printf(MSG_DEBUG, "P2P: Remove peer " MACSTR " from persistent "
2941                    "group %d client list%s",
2942                    MAC2STR(peer), ssid->id,
2943                    inv ? " due to invitation result" : "");
2944         os_memmove(ssid->p2p_client_list + i * 2 * ETH_ALEN,
2945                    ssid->p2p_client_list + (i + 1) * 2 * ETH_ALEN,
2946                    (ssid->num_p2p_clients - i - 1) * 2 * ETH_ALEN);
2947         ssid->num_p2p_clients--;
2948         if (p2p_wpa_s->conf->update_config &&
2949             wpa_config_write(p2p_wpa_s->confname, p2p_wpa_s->conf))
2950                 wpa_printf(MSG_DEBUG, "P2P: Failed to update configuration");
2951 }
2952
2953
2954 static void wpas_remove_persistent_client(struct wpa_supplicant *wpa_s,
2955                                           const u8 *peer)
2956 {
2957         struct wpa_ssid *ssid;
2958
2959         wpa_s = wpa_s->global->p2p_invite_group;
2960         if (wpa_s == NULL)
2961                 return; /* No known invitation group */
2962         ssid = wpa_s->current_ssid;
2963         if (ssid == NULL || ssid->mode != WPAS_MODE_P2P_GO ||
2964             !ssid->p2p_persistent_group)
2965                 return; /* Not operating as a GO in persistent group */
2966         ssid = wpas_p2p_get_persistent(wpa_s->parent, peer,
2967                                        ssid->ssid, ssid->ssid_len);
2968         wpas_remove_persistent_peer(wpa_s, ssid, peer, 1);
2969 }
2970
2971
2972 static void wpas_invitation_result(void *ctx, int status, const u8 *bssid,
2973                                    const struct p2p_channels *channels,
2974                                    const u8 *peer, int neg_freq,
2975                                    int peer_oper_freq)
2976 {
2977         struct wpa_supplicant *wpa_s = ctx;
2978         struct wpa_ssid *ssid;
2979         int freq;
2980
2981         if (bssid) {
2982                 wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_INVITATION_RESULT
2983                                "status=%d " MACSTR,
2984                                status, MAC2STR(bssid));
2985         } else {
2986                 wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_INVITATION_RESULT
2987                                "status=%d ", status);
2988         }
2989         wpas_notify_p2p_invitation_result(wpa_s, status, bssid);
2990
2991         wpa_printf(MSG_DEBUG, "P2P: Invitation result - status=%d peer=" MACSTR,
2992                    status, MAC2STR(peer));
2993         if (wpa_s->pending_invite_ssid_id == -1) {
2994                 if (status == P2P_SC_FAIL_UNKNOWN_GROUP)
2995                         wpas_remove_persistent_client(wpa_s, peer);
2996                 return; /* Invitation to active group */
2997         }
2998
2999         if (status == P2P_SC_FAIL_INFO_CURRENTLY_UNAVAILABLE) {
3000                 wpa_printf(MSG_DEBUG, "P2P: Waiting for peer to start another "
3001                            "invitation exchange to indicate readiness for "
3002                            "re-invocation");
3003         }
3004
3005         if (status != P2P_SC_SUCCESS) {
3006                 if (status == P2P_SC_FAIL_UNKNOWN_GROUP) {
3007                         ssid = wpa_config_get_network(
3008                                 wpa_s->conf, wpa_s->pending_invite_ssid_id);
3009                         wpas_remove_persistent_peer(wpa_s, ssid, peer, 1);
3010                 }
3011                 wpas_p2p_remove_pending_group_interface(wpa_s);
3012                 return;
3013         }
3014
3015         ssid = wpa_config_get_network(wpa_s->conf,
3016                                       wpa_s->pending_invite_ssid_id);
3017         if (ssid == NULL) {
3018                 wpa_printf(MSG_ERROR, "P2P: Could not find persistent group "
3019                            "data matching with invitation");
3020                 return;
3021         }
3022
3023         /*
3024          * The peer could have missed our ctrl::ack frame for Invitation
3025          * Response and continue retransmitting the frame. To reduce the
3026          * likelihood of the peer not getting successful TX status for the
3027          * Invitation Response frame, wait a short time here before starting
3028          * the persistent group so that we will remain on the current channel to
3029          * acknowledge any possible retransmission from the peer.
3030          */
3031         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: 50 ms wait on current channel before "
3032                 "starting persistent group");
3033         os_sleep(0, 50000);
3034
3035         if (neg_freq > 0 && ssid->mode == WPAS_MODE_P2P_GO &&
3036             freq_included(channels, neg_freq))
3037                 freq = neg_freq;
3038         else if (peer_oper_freq > 0 && ssid->mode != WPAS_MODE_P2P_GO &&
3039                  freq_included(channels, peer_oper_freq))
3040                 freq = peer_oper_freq;
3041         else
3042                 freq = 0;
3043
3044         wpa_printf(MSG_DEBUG, "P2P: Persistent group invitation success - op_freq=%d MHz SSID=%s",
3045                    freq, wpa_ssid_txt(ssid->ssid, ssid->ssid_len));
3046         wpas_p2p_group_add_persistent(wpa_s, ssid,
3047                                       ssid->mode == WPAS_MODE_P2P_GO,
3048                                       wpa_s->p2p_persistent_go_freq,
3049                                       freq,
3050                                       wpa_s->p2p_go_ht40, wpa_s->p2p_go_vht,
3051                                       channels,
3052                                       ssid->mode == WPAS_MODE_P2P_GO ?
3053                                       P2P_MAX_INITIAL_CONN_WAIT_GO_REINVOKE :
3054                                       0);
3055 }
3056
3057
3058 static int wpas_p2p_disallowed_freq(struct wpa_global *global,
3059                                     unsigned int freq)
3060 {
3061         if (freq_range_list_includes(&global->p2p_go_avoid_freq, freq))
3062                 return 1;
3063         return freq_range_list_includes(&global->p2p_disallow_freq, freq);
3064 }
3065
3066
3067 static void wpas_p2p_add_chan(struct p2p_reg_class *reg, u8 chan)
3068 {
3069         reg->channel[reg->channels] = chan;
3070         reg->channels++;
3071 }
3072
3073
3074 static int wpas_p2p_default_channels(struct wpa_supplicant *wpa_s,
3075                                      struct p2p_channels *chan,
3076                                      struct p2p_channels *cli_chan)
3077 {
3078         int i, cla = 0;
3079
3080         wpa_s->global->p2p_24ghz_social_channels = 1;
3081
3082         os_memset(cli_chan, 0, sizeof(*cli_chan));
3083
3084         wpa_printf(MSG_DEBUG, "P2P: Enable operating classes for 2.4 GHz "
3085                    "band");
3086
3087         /* Operating class 81 - 2.4 GHz band channels 1..13 */
3088         chan->reg_class[cla].reg_class = 81;
3089         chan->reg_class[cla].channels = 0;
3090         for (i = 0; i < 11; i++) {
3091                 if (!wpas_p2p_disallowed_freq(wpa_s->global, 2412 + i * 5))
3092                         wpas_p2p_add_chan(&chan->reg_class[cla], i + 1);
3093         }
3094         if (chan->reg_class[cla].channels)
3095                 cla++;
3096
3097         wpa_printf(MSG_DEBUG, "P2P: Enable operating classes for lower 5 GHz "
3098                    "band");
3099
3100         /* Operating class 115 - 5 GHz, channels 36-48 */
3101         chan->reg_class[cla].reg_class = 115;
3102         chan->reg_class[cla].channels = 0;
3103         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 36 * 5))
3104                 wpas_p2p_add_chan(&chan->reg_class[cla], 36);
3105         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 40 * 5))
3106                 wpas_p2p_add_chan(&chan->reg_class[cla], 40);
3107         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 44 * 5))
3108                 wpas_p2p_add_chan(&chan->reg_class[cla], 44);
3109         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 48 * 5))
3110                 wpas_p2p_add_chan(&chan->reg_class[cla], 48);
3111         if (chan->reg_class[cla].channels)
3112                 cla++;
3113
3114         wpa_printf(MSG_DEBUG, "P2P: Enable operating classes for higher 5 GHz "
3115                    "band");
3116
3117         /* Operating class 124 - 5 GHz, channels 149,153,157,161 */
3118         chan->reg_class[cla].reg_class = 124;
3119         chan->reg_class[cla].channels = 0;
3120         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 149 * 5))
3121                 wpas_p2p_add_chan(&chan->reg_class[cla], 149);
3122         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 153 * 5))
3123                 wpas_p2p_add_chan(&chan->reg_class[cla], 153);
3124         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 156 * 5))
3125                 wpas_p2p_add_chan(&chan->reg_class[cla], 157);
3126         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 161 * 5))
3127                 wpas_p2p_add_chan(&chan->reg_class[cla], 161);
3128         if (chan->reg_class[cla].channels)
3129                 cla++;
3130
3131         chan->reg_classes = cla;
3132         return 0;
3133 }
3134
3135
3136 static struct hostapd_hw_modes * get_mode(struct hostapd_hw_modes *modes,
3137                                           u16 num_modes,
3138                                           enum hostapd_hw_mode mode)
3139 {
3140         u16 i;
3141
3142         for (i = 0; i < num_modes; i++) {
3143                 if (modes[i].mode == mode)
3144                         return &modes[i];
3145         }
3146
3147         return NULL;
3148 }
3149
3150
3151 enum chan_allowed {
3152         NOT_ALLOWED, NO_IR, ALLOWED
3153 };
3154
3155 static int has_channel(struct wpa_global *global,
3156                        struct hostapd_hw_modes *mode, u8 chan, int *flags)
3157 {
3158         int i;
3159         unsigned int freq;
3160
3161         freq = (mode->mode == HOSTAPD_MODE_IEEE80211A ? 5000 : 2407) +
3162                 chan * 5;
3163         if (wpas_p2p_disallowed_freq(global, freq))
3164                 return NOT_ALLOWED;
3165
3166         for (i = 0; i < mode->num_channels; i++) {
3167                 if (mode->channels[i].chan == chan) {
3168                         if (flags)
3169                                 *flags = mode->channels[i].flag;
3170                         if (mode->channels[i].flag &
3171                             (HOSTAPD_CHAN_DISABLED |
3172                              HOSTAPD_CHAN_RADAR))
3173                                 return NOT_ALLOWED;
3174                         if (mode->channels[i].flag & HOSTAPD_CHAN_NO_IR)
3175                                 return NO_IR;
3176                         return ALLOWED;
3177                 }
3178         }
3179
3180         return NOT_ALLOWED;
3181 }
3182
3183
3184 struct p2p_oper_class_map {
3185         enum hostapd_hw_mode mode;
3186         u8 op_class;
3187         u8 min_chan;
3188         u8 max_chan;
3189         u8 inc;
3190         enum { BW20, BW40PLUS, BW40MINUS, BW80, BW2160 } bw;
3191 };
3192
3193 static const struct p2p_oper_class_map op_class[] = {
3194         { HOSTAPD_MODE_IEEE80211G, 81, 1, 13, 1, BW20 },
3195 #if 0 /* Do not enable HT40 on 2 GHz for now */
3196         { HOSTAPD_MODE_IEEE80211G, 83, 1, 9, 1, BW40PLUS },
3197         { HOSTAPD_MODE_IEEE80211G, 84, 5, 13, 1, BW40MINUS },
3198 #endif
3199         { HOSTAPD_MODE_IEEE80211A, 115, 36, 48, 4, BW20 },
3200         { HOSTAPD_MODE_IEEE80211A, 124, 149, 161, 4, BW20 },
3201         { HOSTAPD_MODE_IEEE80211A, 125, 149, 169, 4, BW20 },
3202         { HOSTAPD_MODE_IEEE80211A, 116, 36, 44, 8, BW40PLUS },
3203         { HOSTAPD_MODE_IEEE80211A, 117, 40, 48, 8, BW40MINUS },
3204         { HOSTAPD_MODE_IEEE80211A, 126, 149, 157, 8, BW40PLUS },
3205         { HOSTAPD_MODE_IEEE80211A, 127, 153, 161, 8, BW40MINUS },
3206
3207         /*
3208          * IEEE P802.11ac/D7.0 Table E-4 actually talks about channel center
3209          * frequency index 42, 58, 106, 122, 138, 155 with channel spacing of
3210          * 80 MHz, but currently use the following definition for simplicity
3211          * (these center frequencies are not actual channels, which makes
3212          * has_channel() fail). wpas_p2p_verify_80mhz() should take care of
3213          * removing invalid channels.
3214          */
3215         { HOSTAPD_MODE_IEEE80211A, 128, 36, 161, 4, BW80 },
3216         { HOSTAPD_MODE_IEEE80211AD, 180, 1, 4, 1, BW2160 },
3217         { -1, 0, 0, 0, 0, BW20 }
3218 };
3219
3220
3221 static int wpas_p2p_get_center_80mhz(struct wpa_supplicant *wpa_s,
3222                                      struct hostapd_hw_modes *mode,
3223                                      u8 channel)
3224 {
3225         u8 center_channels[] = { 42, 58, 106, 122, 138, 155 };
3226         unsigned int i;
3227
3228         if (mode->mode != HOSTAPD_MODE_IEEE80211A)
3229                 return 0;
3230
3231         for (i = 0; i < ARRAY_SIZE(center_channels); i++)
3232                 /*
3233                  * In 80 MHz, the bandwidth "spans" 12 channels (e.g., 36-48),
3234                  * so the center channel is 6 channels away from the start/end.
3235                  */
3236                 if (channel >= center_channels[i] - 6 &&
3237                     channel <= center_channels[i] + 6)
3238                         return center_channels[i];
3239
3240         return 0;
3241 }
3242
3243
3244 static enum chan_allowed wpas_p2p_verify_80mhz(struct wpa_supplicant *wpa_s,
3245                                                struct hostapd_hw_modes *mode,
3246                                                u8 channel, u8 bw)
3247 {
3248         u8 center_chan;
3249         int i, flags;
3250         enum chan_allowed res, ret = ALLOWED;
3251
3252         center_chan = wpas_p2p_get_center_80mhz(wpa_s, mode, channel);
3253         if (!center_chan)
3254                 return NOT_ALLOWED;
3255         if (center_chan >= 58 && center_chan <= 138)
3256                 return NOT_ALLOWED; /* Do not allow DFS channels for P2P */
3257
3258         /* check all the channels are available */
3259         for (i = 0; i < 4; i++) {
3260                 int adj_chan = center_chan - 6 + i * 4;
3261
3262                 res = has_channel(wpa_s->global, mode, adj_chan, &flags);
3263                 if (res == NOT_ALLOWED)
3264                         return NOT_ALLOWED;
3265                 if (res == NO_IR)
3266                         ret = NO_IR;
3267
3268                 if (i == 0 && !(flags & HOSTAPD_CHAN_VHT_10_70))
3269                         return NOT_ALLOWED;
3270                 if (i == 1 && !(flags & HOSTAPD_CHAN_VHT_30_50))
3271                         return NOT_ALLOWED;
3272                 if (i == 2 && !(flags & HOSTAPD_CHAN_VHT_50_30))
3273                         return NOT_ALLOWED;
3274                 if (i == 3 && !(flags & HOSTAPD_CHAN_VHT_70_10))
3275                         return NOT_ALLOWED;
3276         }
3277
3278         return ret;
3279 }
3280
3281
3282 static enum chan_allowed wpas_p2p_verify_channel(struct wpa_supplicant *wpa_s,
3283                                                  struct hostapd_hw_modes *mode,
3284                                                  u8 channel, u8 bw)
3285 {
3286         int flag = 0;
3287         enum chan_allowed res, res2;
3288
3289         res2 = res = has_channel(wpa_s->global, mode, channel, &flag);
3290         if (bw == BW40MINUS) {
3291                 if (!(flag & HOSTAPD_CHAN_HT40MINUS))
3292                         return NOT_ALLOWED;
3293                 res2 = has_channel(wpa_s->global, mode, channel - 4, NULL);
3294         } else if (bw == BW40PLUS) {
3295                 if (!(flag & HOSTAPD_CHAN_HT40PLUS))
3296                         return NOT_ALLOWED;
3297                 res2 = has_channel(wpa_s->global, mode, channel + 4, NULL);
3298         } else if (bw == BW80) {
3299                 res2 = wpas_p2p_verify_80mhz(wpa_s, mode, channel, bw);
3300         }
3301
3302         if (res == NOT_ALLOWED || res2 == NOT_ALLOWED)
3303                 return NOT_ALLOWED;
3304         if (res == NO_IR || res2 == NO_IR)
3305                 return NO_IR;
3306         return res;
3307 }
3308
3309
3310 static int wpas_p2p_setup_channels(struct wpa_supplicant *wpa_s,
3311                                    struct p2p_channels *chan,
3312                                    struct p2p_channels *cli_chan)
3313 {
3314         struct hostapd_hw_modes *mode;
3315         int cla, op, cli_cla;
3316
3317         if (wpa_s->hw.modes == NULL) {
3318                 wpa_printf(MSG_DEBUG, "P2P: Driver did not support fetching "
3319                            "of all supported channels; assume dualband "
3320                            "support");
3321                 return wpas_p2p_default_channels(wpa_s, chan, cli_chan);
3322         }
3323
3324         cla = cli_cla = 0;
3325
3326         for (op = 0; op_class[op].op_class; op++) {
3327                 const struct p2p_oper_class_map *o = &op_class[op];
3328                 u8 ch;
3329                 struct p2p_reg_class *reg = NULL, *cli_reg = NULL;
3330
3331                 mode = get_mode(wpa_s->hw.modes, wpa_s->hw.num_modes, o->mode);
3332                 if (mode == NULL)
3333                         continue;
3334                 if (mode->mode == HOSTAPD_MODE_IEEE80211G)
3335                         wpa_s->global->p2p_24ghz_social_channels = 1;
3336                 for (ch = o->min_chan; ch <= o->max_chan; ch += o->inc) {
3337                         enum chan_allowed res;
3338                         res = wpas_p2p_verify_channel(wpa_s, mode, ch, o->bw);
3339                         if (res == ALLOWED) {
3340                                 if (reg == NULL) {
3341                                         wpa_printf(MSG_DEBUG, "P2P: Add operating class %u",
3342                                                    o->op_class);
3343                                         reg = &chan->reg_class[cla];
3344                                         cla++;
3345                                         reg->reg_class = o->op_class;
3346                                 }
3347                                 reg->channel[reg->channels] = ch;
3348                                 reg->channels++;
3349                         } else if (res == NO_IR &&
3350                                    wpa_s->conf->p2p_add_cli_chan) {
3351                                 if (cli_reg == NULL) {
3352                                         wpa_printf(MSG_DEBUG, "P2P: Add operating class %u (client only)",
3353                                                    o->op_class);
3354                                         cli_reg = &cli_chan->reg_class[cli_cla];
3355                                         cli_cla++;
3356                                         cli_reg->reg_class = o->op_class;
3357                                 }
3358                                 cli_reg->channel[cli_reg->channels] = ch;
3359                                 cli_reg->channels++;
3360                         }
3361                 }
3362                 if (reg) {
3363                         wpa_hexdump(MSG_DEBUG, "P2P: Channels",
3364                                     reg->channel, reg->channels);
3365                 }
3366                 if (cli_reg) {
3367                         wpa_hexdump(MSG_DEBUG, "P2P: Channels (client only)",
3368                                     cli_reg->channel, cli_reg->channels);
3369                 }
3370         }
3371
3372         chan->reg_classes = cla;
3373         cli_chan->reg_classes = cli_cla;
3374
3375         return 0;
3376 }
3377
3378
3379 int wpas_p2p_get_ht40_mode(struct wpa_supplicant *wpa_s,
3380                            struct hostapd_hw_modes *mode, u8 channel)
3381 {
3382         int op;
3383         enum chan_allowed ret;
3384
3385         for (op = 0; op_class[op].op_class; op++) {
3386                 const struct p2p_oper_class_map *o = &op_class[op];
3387                 u8 ch;
3388
3389                 for (ch = o->min_chan; ch <= o->max_chan; ch += o->inc) {
3390                         if (o->mode != HOSTAPD_MODE_IEEE80211A ||
3391                             (o->bw != BW40PLUS && o->bw != BW40MINUS) ||
3392                             ch != channel)
3393                                 continue;
3394                         ret = wpas_p2p_verify_channel(wpa_s, mode, ch, o->bw);
3395                         if (ret == ALLOWED)
3396                                 return (o->bw == BW40MINUS) ? -1 : 1;
3397                 }
3398         }
3399         return 0;
3400 }
3401
3402
3403 int wpas_p2p_get_vht80_center(struct wpa_supplicant *wpa_s,
3404                               struct hostapd_hw_modes *mode, u8 channel)
3405 {
3406         if (!wpas_p2p_verify_channel(wpa_s, mode, channel, BW80))
3407                 return 0;
3408
3409         return wpas_p2p_get_center_80mhz(wpa_s, mode, channel);
3410 }
3411
3412
3413 static int wpas_get_noa(void *ctx, const u8 *interface_addr, u8 *buf,
3414                         size_t buf_len)
3415 {
3416         struct wpa_supplicant *wpa_s = ctx;
3417
3418         for (wpa_s = wpa_s->global->ifaces; wpa_s; wpa_s = wpa_s->next) {
3419                 if (os_memcmp(wpa_s->own_addr, interface_addr, ETH_ALEN) == 0)
3420                         break;
3421         }
3422         if (wpa_s == NULL)
3423                 return -1;
3424
3425         return wpa_drv_get_noa(wpa_s, buf, buf_len);
3426 }
3427
3428
3429 struct wpa_supplicant * wpas_get_p2p_go_iface(struct wpa_supplicant *wpa_s,
3430                                               const u8 *ssid, size_t ssid_len)
3431 {
3432         for (wpa_s = wpa_s->global->ifaces; wpa_s; wpa_s = wpa_s->next) {
3433                 struct wpa_ssid *s = wpa_s->current_ssid;
3434                 if (s == NULL)
3435                         continue;
3436                 if (s->mode != WPAS_MODE_P2P_GO &&
3437                     s->mode != WPAS_MODE_AP &&
3438                     s->mode != WPAS_MODE_P2P_GROUP_FORMATION)
3439                         continue;
3440                 if (s->ssid_len != ssid_len ||
3441                     os_memcmp(ssid, s->ssid, ssid_len) != 0)
3442                         continue;
3443                 return wpa_s;
3444         }
3445
3446         return NULL;
3447
3448 }
3449
3450
3451 struct wpa_supplicant * wpas_get_p2p_client_iface(struct wpa_supplicant *wpa_s,
3452                                                   const u8 *peer_dev_addr)
3453 {
3454         for (wpa_s = wpa_s->global->ifaces; wpa_s; wpa_s = wpa_s->next) {
3455                 struct wpa_ssid *ssid = wpa_s->current_ssid;
3456                 if (ssid && (ssid->mode != WPAS_MODE_INFRA || !ssid->p2p_group))
3457                         continue;
3458                 if (os_memcmp(wpa_s->go_dev_addr, peer_dev_addr, ETH_ALEN) == 0)
3459                         return wpa_s;
3460         }
3461
3462         return NULL;
3463 }
3464
3465
3466 static int wpas_go_connected(void *ctx, const u8 *dev_addr)
3467 {
3468         struct wpa_supplicant *wpa_s = ctx;
3469
3470         return wpas_get_p2p_client_iface(wpa_s, dev_addr) != NULL;
3471 }
3472
3473
3474 static int wpas_is_concurrent_session_active(void *ctx)
3475 {
3476         struct wpa_supplicant *wpa_s = ctx;
3477         struct wpa_supplicant *ifs;
3478
3479         for (ifs = wpa_s->global->ifaces; ifs; ifs = ifs->next) {
3480                 if (ifs == wpa_s)
3481                         continue;
3482                 if (ifs->wpa_state > WPA_ASSOCIATED)
3483                         return 1;
3484         }
3485         return 0;
3486 }
3487
3488
3489 static void wpas_p2p_debug_print(void *ctx, int level, const char *msg)
3490 {
3491         struct wpa_supplicant *wpa_s = ctx;
3492         wpa_msg_global(wpa_s, level, "P2P: %s", msg);
3493 }
3494
3495
3496 int wpas_p2p_add_p2pdev_interface(struct wpa_supplicant *wpa_s,
3497                                   const char *conf_p2p_dev)
3498 {
3499         struct wpa_interface iface;
3500         struct wpa_supplicant *p2pdev_wpa_s;
3501         char ifname[100];
3502         char force_name[100];
3503         int ret;
3504
3505         ret = os_snprintf(ifname, sizeof(ifname), P2P_MGMT_DEVICE_PREFIX "%s",
3506                           wpa_s->ifname);
3507         if (os_snprintf_error(sizeof(ifname), ret))
3508                 return -1;
3509         force_name[0] = '\0';
3510         wpa_s->pending_interface_type = WPA_IF_P2P_DEVICE;
3511         ret = wpa_drv_if_add(wpa_s, WPA_IF_P2P_DEVICE, ifname, NULL, NULL,
3512                              force_name, wpa_s->pending_interface_addr, NULL);
3513         if (ret < 0) {
3514                 wpa_printf(MSG_DEBUG, "P2P: Failed to create P2P Device interface");
3515                 return ret;
3516         }
3517         os_strlcpy(wpa_s->pending_interface_name, ifname,
3518                    sizeof(wpa_s->pending_interface_name));
3519
3520         os_memset(&iface, 0, sizeof(iface));
3521         iface.p2p_mgmt = 1;
3522         iface.ifname = wpa_s->pending_interface_name;
3523         iface.driver = wpa_s->driver->name;
3524         iface.driver_param = wpa_s->conf->driver_param;
3525
3526         /*
3527          * If a P2P Device configuration file was given, use it as the interface
3528          * configuration file (instead of using parent's configuration file.
3529          */
3530         if (conf_p2p_dev) {
3531                 iface.confname = conf_p2p_dev;
3532                 iface.ctrl_interface = NULL;
3533         } else {
3534                 iface.confname = wpa_s->confname;
3535                 iface.ctrl_interface = wpa_s->conf->ctrl_interface;
3536         }
3537
3538         p2pdev_wpa_s = wpa_supplicant_add_iface(wpa_s->global, &iface, wpa_s);
3539         if (!p2pdev_wpa_s) {
3540                 wpa_printf(MSG_DEBUG, "P2P: Failed to add P2P Device interface");
3541                 return -1;
3542         }
3543
3544         wpa_s->pending_interface_name[0] = '\0';
3545         return 0;
3546 }
3547
3548
3549 static void wpas_presence_resp(void *ctx, const u8 *src, u8 status,
3550                                const u8 *noa, size_t noa_len)
3551 {
3552         struct wpa_supplicant *wpa_s, *intf = ctx;
3553         char hex[100];
3554
3555         for (wpa_s = intf->global->ifaces; wpa_s; wpa_s = wpa_s->next) {
3556                 if (wpa_s->waiting_presence_resp)
3557                         break;
3558         }
3559         if (!wpa_s) {
3560                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: No group interface was waiting for presence response");
3561                 return;
3562         }
3563         wpa_s->waiting_presence_resp = 0;
3564
3565         wpa_snprintf_hex(hex, sizeof(hex), noa, noa_len);
3566         wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_PRESENCE_RESPONSE "src=" MACSTR
3567                 " status=%u noa=%s", MAC2STR(src), status, hex);
3568 }
3569
3570
3571 static int wpas_get_persistent_group(void *ctx, const u8 *addr, const u8 *ssid,
3572                                      size_t ssid_len, u8 *go_dev_addr,
3573                                      u8 *ret_ssid, size_t *ret_ssid_len,
3574                                      u8 *intended_iface_addr)
3575 {
3576         struct wpa_supplicant *wpa_s = ctx;
3577         struct wpa_ssid *s;
3578
3579         s = wpas_p2p_get_persistent(wpa_s, addr, ssid, ssid_len);
3580         if (s) {
3581                 os_memcpy(ret_ssid, s->ssid, s->ssid_len);
3582                 *ret_ssid_len = s->ssid_len;
3583                 os_memcpy(go_dev_addr, s->bssid, ETH_ALEN);
3584
3585                 if (s->mode != WPAS_MODE_P2P_GO) {
3586                         os_memset(intended_iface_addr, 0, ETH_ALEN);
3587                 } else if (wpas_p2p_create_iface(wpa_s)) {
3588                         if (wpas_p2p_add_group_interface(wpa_s, WPA_IF_P2P_GO))
3589                                 return 0;
3590
3591                         os_memcpy(intended_iface_addr,
3592                                   wpa_s->pending_interface_addr, ETH_ALEN);
3593                 } else {
3594                         os_memcpy(intended_iface_addr, wpa_s->own_addr,
3595                                   ETH_ALEN);
3596                 }
3597                 return 1;
3598         }
3599
3600         return 0;
3601 }
3602
3603
3604 static int wpas_get_go_info(void *ctx, u8 *intended_addr,
3605                             u8 *ssid, size_t *ssid_len, int *group_iface)
3606 {
3607         struct wpa_supplicant *wpa_s = ctx;
3608         struct wpa_ssid *s;
3609         u8 bssid[ETH_ALEN];
3610
3611         /*
3612          * group_iface will be set to 1 only if a dedicated interface for P2P
3613          * role is required. First, we try to reuse an active GO. However,
3614          * if it is not present, we will try to reactivate an existing
3615          * persistent group and set group_iface to 1, so the caller will know
3616          * that the pending interface should be used.
3617          */
3618         *group_iface = 0;
3619         s = wpas_p2p_group_go_ssid(wpa_s, bssid);
3620         if (!s) {
3621                 s = wpas_p2p_get_persistent_go(wpa_s);
3622                 *group_iface = wpas_p2p_create_iface(wpa_s);
3623                 if (s)
3624                         os_memcpy(bssid, s->bssid, ETH_ALEN);
3625                 else
3626                         return 0;
3627         }
3628
3629         os_memcpy(intended_addr, bssid, ETH_ALEN);
3630         os_memcpy(ssid, s->ssid, s->ssid_len);
3631         *ssid_len = s->ssid_len;
3632
3633         return 1;
3634 }
3635
3636
3637 static int wpas_remove_stale_groups(void *ctx, const u8 *peer, const u8 *go,
3638                                     const u8 *ssid, size_t ssid_len)
3639 {
3640         struct wpa_supplicant *wpa_s = ctx;
3641         struct wpa_ssid *s;
3642         int save_config = 0;
3643         size_t i;
3644
3645         /* Start with our first choice of Persistent Groups */
3646         while ((s = wpas_p2p_get_persistent(wpa_s, peer, NULL, 0))) {
3647                 if (go && ssid && ssid_len &&
3648                     s->ssid_len == ssid_len &&
3649                     os_memcmp(go, s->bssid, ETH_ALEN) == 0 &&
3650                     os_memcmp(ssid, s->ssid, ssid_len) == 0)
3651                         break;
3652
3653                 /* Remove stale persistent group */
3654                 if (s->mode != WPAS_MODE_P2P_GO || s->num_p2p_clients <= 1) {
3655                         wpa_config_remove_network(wpa_s->conf, s->id);
3656                         save_config = 1;
3657                         continue;
3658                 }
3659
3660                 for (i = 0; i < s->num_p2p_clients; i++) {
3661                         if (os_memcmp(s->p2p_client_list + i * 2 * ETH_ALEN,
3662                                       peer, ETH_ALEN) != 0)
3663                                 continue;
3664
3665                         os_memmove(s->p2p_client_list + i * 2 * ETH_ALEN,
3666                                    s->p2p_client_list + (i + 1) * 2 * ETH_ALEN,
3667                                    (s->num_p2p_clients - i - 1) * 2 * ETH_ALEN);
3668                         break;
3669                 }
3670                 s->num_p2p_clients--;
3671                 save_config = 1;
3672         }
3673
3674         if (save_config)
3675                 p2p_config_write(wpa_s);
3676
3677         /* Return TRUE if valid SSID remains */
3678         return s != NULL;
3679 }
3680
3681
3682 static void wpas_p2ps_get_feat_cap_str(char *buf, size_t buf_len,
3683                                        const u8 *feat_cap, size_t feat_cap_len)
3684 {
3685         static const char pref[] = " feature_cap=";
3686         int ret;
3687
3688         buf[0] = '\0';
3689
3690         /*
3691          * We expect a feature capability to contain at least one byte to be
3692          * reported. The string buffer provided by the caller function is
3693          * expected to be big enough to contain all bytes of the attribute for
3694          * known specifications. This function truncates the reported bytes if
3695          * the feature capability data exceeds the string buffer size.
3696          */
3697         if (!feat_cap || !feat_cap_len || buf_len < sizeof(pref) + 2)
3698                 return;
3699
3700         os_memcpy(buf, pref, sizeof(pref));
3701         ret = wpa_snprintf_hex(&buf[sizeof(pref) - 1],
3702                                buf_len - sizeof(pref) + 1,
3703                                feat_cap, feat_cap_len);
3704
3705         if (ret != (2 * (int) feat_cap_len))
3706                 wpa_printf(MSG_WARNING, "P2PS feature_cap bytes truncated");
3707 }
3708
3709
3710 static void wpas_p2ps_prov_complete(void *ctx, u8 status, const u8 *dev,
3711                                     const u8 *adv_mac, const u8 *ses_mac,
3712                                     const u8 *grp_mac, u32 adv_id, u32 ses_id,
3713                                     u8 conncap, int passwd_id,
3714                                     const u8 *persist_ssid,
3715                                     size_t persist_ssid_size, int response_done,
3716                                     int prov_start, const char *session_info,
3717                                     const u8 *feat_cap, size_t feat_cap_len)
3718 {
3719         struct wpa_supplicant *wpa_s = ctx;
3720         u8 mac[ETH_ALEN];
3721         struct wpa_ssid *persistent_go, *stale, *s;
3722         int save_config = 0;
3723         struct wpa_supplicant *go_wpa_s;
3724         char feat_cap_str[256];
3725
3726         if (!dev)
3727                 return;
3728
3729         os_memset(mac, 0, ETH_ALEN);
3730         if (!adv_mac)
3731                 adv_mac = mac;
3732         if (!ses_mac)
3733                 ses_mac = mac;
3734         if (!grp_mac)
3735                 grp_mac = mac;
3736
3737         wpas_p2ps_get_feat_cap_str(feat_cap_str, sizeof(feat_cap_str),
3738                                    feat_cap, feat_cap_len);
3739
3740         if (prov_start) {
3741                 if (session_info == NULL) {
3742                         wpa_msg_global(wpa_s, MSG_INFO,
3743                                        P2P_EVENT_P2PS_PROVISION_START MACSTR
3744                                        " adv_id=%x conncap=%x"
3745                                        " adv_mac=" MACSTR
3746                                        " session=%x mac=" MACSTR
3747                                        " dev_passwd_id=%d%s",
3748                                        MAC2STR(dev), adv_id, conncap,
3749                                        MAC2STR(adv_mac),
3750                                        ses_id, MAC2STR(ses_mac),
3751                                        passwd_id, feat_cap_str);
3752                 } else {
3753                         wpa_msg_global(wpa_s, MSG_INFO,
3754                                        P2P_EVENT_P2PS_PROVISION_START MACSTR
3755                                        " adv_id=%x conncap=%x"
3756                                        " adv_mac=" MACSTR
3757                                        " session=%x mac=" MACSTR
3758                                        " dev_passwd_id=%d info='%s'%s",
3759                                        MAC2STR(dev), adv_id, conncap,
3760                                        MAC2STR(adv_mac),
3761                                        ses_id, MAC2STR(ses_mac),
3762                                        passwd_id, session_info, feat_cap_str);
3763                 }
3764                 return;
3765         }
3766
3767         go_wpa_s = wpas_p2p_get_go_group(wpa_s);
3768         persistent_go = wpas_p2p_get_persistent_go(wpa_s);
3769
3770         if (status && status != P2P_SC_SUCCESS_DEFERRED) {
3771                 if (go_wpa_s && !p2p_group_go_member_count(wpa_s))
3772                         wpas_p2p_group_remove(wpa_s, go_wpa_s->ifname);
3773
3774                 if (persistent_go && !persistent_go->num_p2p_clients) {
3775                         /* remove empty persistent GO */
3776                         wpa_config_remove_network(wpa_s->conf,
3777                                                   persistent_go->id);
3778                 }
3779
3780                 wpa_msg_global(wpa_s, MSG_INFO,
3781                                P2P_EVENT_P2PS_PROVISION_DONE MACSTR
3782                                " status=%d"
3783                                " adv_id=%x adv_mac=" MACSTR
3784                                " session=%x mac=" MACSTR "%s",
3785                                MAC2STR(dev), status,
3786                                adv_id, MAC2STR(adv_mac),
3787                                ses_id, MAC2STR(ses_mac), feat_cap_str);
3788                 return;
3789         }
3790
3791         /* Clean up stale persistent groups with this device */
3792         s = wpas_p2p_get_persistent(wpa_s, dev, persist_ssid,
3793                                     persist_ssid_size);
3794
3795         if (persist_ssid && s && s->mode != WPAS_MODE_P2P_GO &&
3796             os_memcmp(grp_mac, mac, ETH_ALEN) == 0) {
3797                 wpa_dbg(wpa_s, MSG_ERROR,
3798                         "P2P: Peer device is a GO in a persistent group, but it did not provide the intended MAC address");
3799                 return;
3800         }
3801
3802         for (;;) {
3803                 stale = wpas_p2p_get_persistent(wpa_s, dev, NULL, 0);
3804                 if (!stale)
3805                         break;
3806
3807                 if (s && s->ssid_len == stale->ssid_len &&
3808                     os_memcmp(stale->bssid, s->bssid, ETH_ALEN) == 0 &&
3809                     os_memcmp(stale->ssid, s->ssid, s->ssid_len) == 0)
3810                         break;
3811
3812                 /* Remove stale persistent group */
3813                 if (stale->mode != WPAS_MODE_P2P_GO ||
3814                     stale->num_p2p_clients <= 1) {
3815                         wpa_config_remove_network(wpa_s->conf, stale->id);
3816                 } else {
3817                         size_t i;
3818
3819                         for (i = 0; i < stale->num_p2p_clients; i++) {
3820                                 if (os_memcmp(stale->p2p_client_list +
3821                                               i * ETH_ALEN,
3822                                               dev, ETH_ALEN) == 0) {
3823                                         os_memmove(stale->p2p_client_list +
3824                                                    i * ETH_ALEN,
3825                                                    stale->p2p_client_list +
3826                                                    (i + 1) * ETH_ALEN,
3827                                                    (stale->num_p2p_clients -
3828                                                     i - 1) * ETH_ALEN);
3829                                         break;
3830                                 }
3831                         }
3832                         stale->num_p2p_clients--;
3833                 }
3834                 save_config = 1;
3835         }
3836
3837         if (save_config)
3838                 p2p_config_write(wpa_s);
3839
3840         if (s) {
3841                 if (go_wpa_s && !p2p_group_go_member_count(wpa_s))
3842                         wpas_p2p_group_remove(wpa_s, go_wpa_s->ifname);
3843
3844                 if (persistent_go && s != persistent_go &&
3845                     !persistent_go->num_p2p_clients) {
3846                         /* remove empty persistent GO */
3847                         wpa_config_remove_network(wpa_s->conf,
3848                                                   persistent_go->id);
3849                         /* Save config */
3850                 }
3851
3852                 wpa_msg_global(wpa_s, MSG_INFO,
3853                                P2P_EVENT_P2PS_PROVISION_DONE MACSTR
3854                                " status=%d"
3855                                " adv_id=%x adv_mac=" MACSTR
3856                                " session=%x mac=" MACSTR
3857                                " persist=%d%s",
3858                                MAC2STR(dev), status,
3859                                adv_id, MAC2STR(adv_mac),
3860                                ses_id, MAC2STR(ses_mac), s->id, feat_cap_str);
3861                 return;
3862         }
3863
3864         if (conncap == P2PS_SETUP_GROUP_OWNER) {
3865                 /*
3866                  * We need to copy the interface name. Simply saving a
3867                  * pointer isn't enough, since if we use pending_interface_name
3868                  * it will be overwritten when the group is added.
3869                  */
3870                 char go_ifname[100];
3871
3872                 go_ifname[0] = '\0';
3873                 if (!go_wpa_s) {
3874                         wpa_s->global->pending_p2ps_group = 1;
3875
3876                         if (!wpas_p2p_create_iface(wpa_s))
3877                                 os_memcpy(go_ifname, wpa_s->ifname,
3878                                           sizeof(go_ifname));
3879                         else if (wpa_s->pending_interface_name[0])
3880                                 os_memcpy(go_ifname,
3881                                           wpa_s->pending_interface_name,
3882                                           sizeof(go_ifname));
3883
3884                         if (!go_ifname[0]) {
3885                                 wpas_p2ps_prov_complete(
3886                                         wpa_s, P2P_SC_FAIL_UNKNOWN_GROUP,
3887                                         dev, adv_mac, ses_mac,
3888                                         NULL, adv_id, ses_id, 0, 0,
3889                                         NULL, 0, 0, 0, NULL, NULL, 0);
3890                                 return;
3891                         }
3892
3893                         /* If PD Resp complete, start up the GO */
3894                         if (response_done && persistent_go) {
3895                                 wpas_p2p_group_add_persistent(
3896                                         wpa_s, persistent_go,
3897                                         0, 0, 0, 0, 0, NULL,
3898                                         persistent_go->mode ==
3899                                         WPAS_MODE_P2P_GO ?
3900                                         P2P_MAX_INITIAL_CONN_WAIT_GO_REINVOKE :
3901                                         0);
3902                         } else if (response_done) {
3903                                 wpas_p2p_group_add(wpa_s, 1, 0, 0, 0);
3904                         }
3905
3906                         if (passwd_id == DEV_PW_P2PS_DEFAULT) {
3907                                 os_memcpy(wpa_s->p2ps_join_addr, dev, ETH_ALEN);
3908                                 wpa_s->p2ps_join_addr_valid = 1;
3909                                 wpa_dbg(wpa_s, MSG_DEBUG,
3910                                         "P2PS: Saving PIN for " MACSTR,
3911                                         MAC2STR(dev));
3912                         }
3913                 } else if (passwd_id == DEV_PW_P2PS_DEFAULT) {
3914                         os_memcpy(go_ifname, go_wpa_s->ifname,
3915                                   sizeof(go_ifname));
3916
3917                         wpa_dbg(go_wpa_s, MSG_DEBUG,
3918                                 "P2P: Setting PIN-1 For " MACSTR, MAC2STR(dev));
3919                         wpa_supplicant_ap_wps_pin(go_wpa_s, dev, "12345670",
3920                                                   NULL, 0, 0);
3921
3922                         os_memcpy(wpa_s->p2ps_join_addr, dev, ETH_ALEN);
3923                         wpa_s->p2ps_join_addr_valid = 1;
3924                         wpa_dbg(wpa_s, MSG_DEBUG,
3925                                 "P2PS: Saving PIN for " MACSTR, MAC2STR(dev));
3926                 }
3927
3928                 wpa_msg_global(wpa_s, MSG_INFO,
3929                                P2P_EVENT_P2PS_PROVISION_DONE MACSTR
3930                                " status=%d conncap=%x"
3931                                " adv_id=%x adv_mac=" MACSTR
3932                                " session=%x mac=" MACSTR
3933                                " dev_passwd_id=%d go=%s%s",
3934                                MAC2STR(dev), status, conncap,
3935                                adv_id, MAC2STR(adv_mac),
3936                                ses_id, MAC2STR(ses_mac),
3937                                passwd_id, go_ifname, feat_cap_str);
3938                 return;
3939         }
3940
3941         if (go_wpa_s && !p2p_group_go_member_count(wpa_s))
3942                 wpas_p2p_group_remove(wpa_s, go_wpa_s->ifname);
3943
3944         if (persistent_go && !persistent_go->num_p2p_clients) {
3945                 /* remove empty persistent GO */
3946                 wpa_config_remove_network(wpa_s->conf, persistent_go->id);
3947         }
3948
3949         if (conncap == P2PS_SETUP_CLIENT) {
3950                 wpa_msg_global(wpa_s, MSG_INFO,
3951                                P2P_EVENT_P2PS_PROVISION_DONE MACSTR
3952                                " status=%d conncap=%x"
3953                                " adv_id=%x adv_mac=" MACSTR
3954                                " session=%x mac=" MACSTR
3955                                " dev_passwd_id=%d join=" MACSTR "%s",
3956                                MAC2STR(dev), status, conncap,
3957                                adv_id, MAC2STR(adv_mac),
3958                                ses_id, MAC2STR(ses_mac),
3959                                passwd_id, MAC2STR(grp_mac), feat_cap_str);
3960         } else {
3961                 wpa_msg_global(wpa_s, MSG_INFO,
3962                                P2P_EVENT_P2PS_PROVISION_DONE MACSTR
3963                                " status=%d conncap=%x"
3964                                " adv_id=%x adv_mac=" MACSTR
3965                                " session=%x mac=" MACSTR
3966                                " dev_passwd_id=%d%s",
3967                                MAC2STR(dev), status, conncap,
3968                                adv_id, MAC2STR(adv_mac),
3969                                ses_id, MAC2STR(ses_mac),
3970                                passwd_id, feat_cap_str);
3971         }
3972 }
3973
3974
3975 static int _wpas_p2p_in_progress(void *ctx)
3976 {
3977         struct wpa_supplicant *wpa_s = ctx;
3978         return wpas_p2p_in_progress(wpa_s);
3979 }
3980
3981
3982 static int wpas_prov_disc_resp_cb(void *ctx)
3983 {
3984         struct wpa_supplicant *wpa_s = ctx;
3985         struct wpa_ssid *persistent_go;
3986
3987         if (!wpa_s->global->pending_p2ps_group)
3988                 return 0;
3989
3990         wpa_s->global->pending_p2ps_group = 0;
3991
3992         if (wpas_p2p_get_go_group(wpa_s))
3993                 return 0;
3994         persistent_go = wpas_p2p_get_persistent_go(wpa_s);
3995
3996         if (persistent_go) {
3997                 wpas_p2p_group_add_persistent(
3998                         wpa_s, persistent_go, 0, 0, 0, 0, 0, NULL,
3999                         persistent_go->mode == WPAS_MODE_P2P_GO ?
4000                         P2P_MAX_INITIAL_CONN_WAIT_GO_REINVOKE : 0);
4001         } else {
4002                 wpas_p2p_group_add(wpa_s, 1, 0, 0, 0);
4003         }
4004
4005         return 1;
4006 }
4007
4008
4009 static int wpas_p2p_get_pref_freq_list(void *ctx, int go,
4010                                        unsigned int *len,
4011                                        unsigned int *freq_list)
4012 {
4013         struct wpa_supplicant *wpa_s = ctx;
4014
4015         return wpa_drv_get_pref_freq_list(wpa_s, go ? WPA_IF_P2P_GO :
4016                                           WPA_IF_P2P_CLIENT, len, freq_list);
4017 }
4018
4019
4020 /**
4021  * wpas_p2p_init - Initialize P2P module for %wpa_supplicant
4022  * @global: Pointer to global data from wpa_supplicant_init()
4023  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
4024  * Returns: 0 on success, -1 on failure
4025  */
4026 int wpas_p2p_init(struct wpa_global *global, struct wpa_supplicant *wpa_s)
4027 {
4028         struct p2p_config p2p;
4029         int i;
4030
4031         if (wpa_s->conf->p2p_disabled)
4032                 return 0;
4033
4034         if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_CAPABLE))
4035                 return 0;
4036
4037         if (global->p2p)
4038                 return 0;
4039
4040         os_memset(&p2p, 0, sizeof(p2p));
4041         p2p.cb_ctx = wpa_s;
4042         p2p.debug_print = wpas_p2p_debug_print;
4043         p2p.p2p_scan = wpas_p2p_scan;
4044         p2p.send_action = wpas_send_action;
4045         p2p.send_action_done = wpas_send_action_done;
4046         p2p.go_neg_completed = wpas_go_neg_completed;
4047         p2p.go_neg_req_rx = wpas_go_neg_req_rx;
4048         p2p.dev_found = wpas_dev_found;
4049         p2p.dev_lost = wpas_dev_lost;
4050         p2p.find_stopped = wpas_find_stopped;
4051         p2p.start_listen = wpas_start_listen;
4052         p2p.stop_listen = wpas_stop_listen;
4053         p2p.send_probe_resp = wpas_send_probe_resp;
4054         p2p.sd_request = wpas_sd_request;
4055         p2p.sd_response = wpas_sd_response;
4056         p2p.prov_disc_req = wpas_prov_disc_req;
4057         p2p.prov_disc_resp = wpas_prov_disc_resp;
4058         p2p.prov_disc_fail = wpas_prov_disc_fail;
4059         p2p.invitation_process = wpas_invitation_process;
4060         p2p.invitation_received = wpas_invitation_received;
4061         p2p.invitation_result = wpas_invitation_result;
4062         p2p.get_noa = wpas_get_noa;
4063         p2p.go_connected = wpas_go_connected;
4064         p2p.presence_resp = wpas_presence_resp;
4065         p2p.is_concurrent_session_active = wpas_is_concurrent_session_active;
4066         p2p.is_p2p_in_progress = _wpas_p2p_in_progress;
4067         p2p.get_persistent_group = wpas_get_persistent_group;
4068         p2p.get_go_info = wpas_get_go_info;
4069         p2p.remove_stale_groups = wpas_remove_stale_groups;
4070         p2p.p2ps_prov_complete = wpas_p2ps_prov_complete;
4071         p2p.prov_disc_resp_cb = wpas_prov_disc_resp_cb;
4072         p2p.p2ps_group_capability = p2ps_group_capability;
4073         p2p.get_pref_freq_list = wpas_p2p_get_pref_freq_list;
4074
4075         os_memcpy(wpa_s->global->p2p_dev_addr, wpa_s->own_addr, ETH_ALEN);
4076         os_memcpy(p2p.dev_addr, wpa_s->global->p2p_dev_addr, ETH_ALEN);
4077         p2p.dev_name = wpa_s->conf->device_name;
4078         p2p.manufacturer = wpa_s->conf->manufacturer;
4079         p2p.model_name = wpa_s->conf->model_name;
4080         p2p.model_number = wpa_s->conf->model_number;
4081         p2p.serial_number = wpa_s->conf->serial_number;
4082         if (wpa_s->wps) {
4083                 os_memcpy(p2p.uuid, wpa_s->wps->uuid, 16);
4084                 p2p.config_methods = wpa_s->wps->config_methods;
4085         }
4086
4087         if (wpas_p2p_setup_channels(wpa_s, &p2p.channels, &p2p.cli_channels)) {
4088                 wpa_printf(MSG_ERROR,
4089                            "P2P: Failed to configure supported channel list");
4090                 return -1;
4091         }
4092
4093         if (wpa_s->conf->p2p_listen_reg_class &&
4094             wpa_s->conf->p2p_listen_channel) {
4095                 p2p.reg_class = wpa_s->conf->p2p_listen_reg_class;
4096                 p2p.channel = wpa_s->conf->p2p_listen_channel;
4097                 p2p.channel_forced = 1;
4098         } else {
4099                 /*
4100                  * Pick one of the social channels randomly as the listen
4101                  * channel.
4102                  */
4103                 if (p2p_config_get_random_social(&p2p, &p2p.reg_class,
4104                                                  &p2p.channel) != 0) {
4105                         wpa_printf(MSG_INFO,
4106                                    "P2P: No social channels supported by the driver - do not enable P2P");
4107                         return 0;
4108                 }
4109                 p2p.channel_forced = 0;
4110         }
4111         wpa_printf(MSG_DEBUG, "P2P: Own listen channel: %d:%d",
4112                    p2p.reg_class, p2p.channel);
4113
4114         if (wpa_s->conf->p2p_oper_reg_class &&
4115             wpa_s->conf->p2p_oper_channel) {
4116                 p2p.op_reg_class = wpa_s->conf->p2p_oper_reg_class;
4117                 p2p.op_channel = wpa_s->conf->p2p_oper_channel;
4118                 p2p.cfg_op_channel = 1;
4119                 wpa_printf(MSG_DEBUG, "P2P: Configured operating channel: "
4120                            "%d:%d", p2p.op_reg_class, p2p.op_channel);
4121
4122         } else {
4123                 /*
4124                  * Use random operation channel from 2.4 GHz band social
4125                  * channels (1, 6, 11) or band 60 GHz social channel (2) if no
4126                  * other preference is indicated.
4127                  */
4128                 if (p2p_config_get_random_social(&p2p, &p2p.op_reg_class,
4129                                                  &p2p.op_channel) != 0) {
4130                         wpa_printf(MSG_ERROR,
4131                                    "P2P: Failed to select random social channel as operation channel");
4132                         return -1;
4133                 }
4134                 p2p.cfg_op_channel = 0;
4135                 wpa_printf(MSG_DEBUG, "P2P: Random operating channel: "
4136                            "%d:%d", p2p.op_reg_class, p2p.op_channel);
4137         }
4138
4139         if (wpa_s->conf->p2p_pref_chan && wpa_s->conf->num_p2p_pref_chan) {
4140                 p2p.pref_chan = wpa_s->conf->p2p_pref_chan;
4141                 p2p.num_pref_chan = wpa_s->conf->num_p2p_pref_chan;
4142         }
4143
4144         if (wpa_s->conf->country[0] && wpa_s->conf->country[1]) {
4145                 os_memcpy(p2p.country, wpa_s->conf->country, 2);
4146                 p2p.country[2] = 0x04;
4147         } else
4148                 os_memcpy(p2p.country, "XX\x04", 3);
4149
4150         os_memcpy(p2p.pri_dev_type, wpa_s->conf->device_type,
4151                   WPS_DEV_TYPE_LEN);
4152
4153         p2p.num_sec_dev_types = wpa_s->conf->num_sec_device_types;
4154         os_memcpy(p2p.sec_dev_type, wpa_s->conf->sec_device_type,
4155                   p2p.num_sec_dev_types * WPS_DEV_TYPE_LEN);
4156
4157         p2p.concurrent_operations = !!(wpa_s->drv_flags &
4158                                        WPA_DRIVER_FLAGS_P2P_CONCURRENT);
4159
4160         p2p.max_peers = 100;
4161
4162         if (wpa_s->conf->p2p_ssid_postfix) {
4163                 p2p.ssid_postfix_len =
4164                         os_strlen(wpa_s->conf->p2p_ssid_postfix);
4165                 if (p2p.ssid_postfix_len > sizeof(p2p.ssid_postfix))
4166                         p2p.ssid_postfix_len = sizeof(p2p.ssid_postfix);
4167                 os_memcpy(p2p.ssid_postfix, wpa_s->conf->p2p_ssid_postfix,
4168                           p2p.ssid_postfix_len);
4169         }
4170
4171         p2p.p2p_intra_bss = wpa_s->conf->p2p_intra_bss;
4172
4173         p2p.max_listen = wpa_s->max_remain_on_chan;
4174
4175         if (wpa_s->conf->p2p_passphrase_len >= 8 &&
4176             wpa_s->conf->p2p_passphrase_len <= 63)
4177                 p2p.passphrase_len = wpa_s->conf->p2p_passphrase_len;
4178         else
4179                 p2p.passphrase_len = 8;
4180
4181         global->p2p = p2p_init(&p2p);
4182         if (global->p2p == NULL)
4183                 return -1;
4184         global->p2p_init_wpa_s = wpa_s;
4185
4186         for (i = 0; i < MAX_WPS_VENDOR_EXT; i++) {
4187                 if (wpa_s->conf->wps_vendor_ext[i] == NULL)
4188                         continue;
4189                 p2p_add_wps_vendor_extension(
4190                         global->p2p, wpa_s->conf->wps_vendor_ext[i]);
4191         }
4192
4193         p2p_set_no_go_freq(global->p2p, &wpa_s->conf->p2p_no_go_freq);
4194
4195         return 0;
4196 }
4197
4198
4199 /**
4200  * wpas_p2p_deinit - Deinitialize per-interface P2P data
4201  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
4202  *
4203  * This function deinitialize per-interface P2P data.
4204  */
4205 void wpas_p2p_deinit(struct wpa_supplicant *wpa_s)
4206 {
4207         if (wpa_s->driver && wpa_s->drv_priv)
4208                 wpa_drv_probe_req_report(wpa_s, 0);
4209
4210         if (wpa_s->go_params) {
4211                 /* Clear any stored provisioning info */
4212                 p2p_clear_provisioning_info(
4213                         wpa_s->global->p2p,
4214                         wpa_s->go_params->peer_device_addr);
4215         }
4216
4217         os_free(wpa_s->go_params);
4218         wpa_s->go_params = NULL;
4219         eloop_cancel_timeout(wpas_p2p_psk_failure_removal, wpa_s, NULL);
4220         eloop_cancel_timeout(wpas_p2p_group_formation_timeout, wpa_s, NULL);
4221         eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
4222         wpa_s->p2p_long_listen = 0;
4223         eloop_cancel_timeout(wpas_p2p_long_listen_timeout, wpa_s, NULL);
4224         eloop_cancel_timeout(wpas_p2p_group_idle_timeout, wpa_s, NULL);
4225         wpas_p2p_remove_pending_group_interface(wpa_s);
4226         eloop_cancel_timeout(wpas_p2p_group_freq_conflict, wpa_s, NULL);
4227         wpas_p2p_listen_work_done(wpa_s);
4228         if (wpa_s->p2p_send_action_work) {
4229                 os_free(wpa_s->p2p_send_action_work->ctx);
4230                 radio_work_done(wpa_s->p2p_send_action_work);
4231                 wpa_s->p2p_send_action_work = NULL;
4232         }
4233         eloop_cancel_timeout(wpas_p2p_send_action_work_timeout, wpa_s, NULL);
4234
4235         wpabuf_free(wpa_s->p2p_oob_dev_pw);
4236         wpa_s->p2p_oob_dev_pw = NULL;
4237
4238         os_free(wpa_s->p2p_group_common_freqs);
4239         wpa_s->p2p_group_common_freqs = NULL;
4240         wpa_s->p2p_group_common_freqs_num = 0;
4241
4242         /* TODO: remove group interface from the driver if this wpa_s instance
4243          * is on top of a P2P group interface */
4244 }
4245
4246
4247 /**
4248  * wpas_p2p_deinit_global - Deinitialize global P2P module
4249  * @global: Pointer to global data from wpa_supplicant_init()
4250  *
4251  * This function deinitializes the global (per device) P2P module.
4252  */
4253 static void wpas_p2p_deinit_global(struct wpa_global *global)
4254 {
4255         struct wpa_supplicant *wpa_s, *tmp;
4256
4257         wpa_s = global->ifaces;
4258
4259         wpas_p2p_service_flush(global->p2p_init_wpa_s);
4260
4261         /* Remove remaining P2P group interfaces */
4262         while (wpa_s && wpa_s->p2p_group_interface != NOT_P2P_GROUP_INTERFACE)
4263                 wpa_s = wpa_s->next;
4264         while (wpa_s) {
4265                 tmp = global->ifaces;
4266                 while (tmp &&
4267                        (tmp == wpa_s ||
4268                         tmp->p2p_group_interface == NOT_P2P_GROUP_INTERFACE)) {
4269                         tmp = tmp->next;
4270                 }
4271                 if (tmp == NULL)
4272                         break;
4273                 /* Disconnect from the P2P group and deinit the interface */
4274                 wpas_p2p_disconnect(tmp);
4275         }
4276
4277         /*
4278          * Deinit GO data on any possibly remaining interface (if main
4279          * interface is used as GO).
4280          */
4281         for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) {
4282                 if (wpa_s->ap_iface)
4283                         wpas_p2p_group_deinit(wpa_s);
4284         }
4285
4286         p2p_deinit(global->p2p);
4287         global->p2p = NULL;
4288         global->p2p_init_wpa_s = NULL;
4289 }
4290
4291
4292 static int wpas_p2p_create_iface(struct wpa_supplicant *wpa_s)
4293 {
4294         if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_DEDICATED_P2P_DEVICE) &&
4295             wpa_s->conf->p2p_no_group_iface)
4296                 return 0; /* separate interface disabled per configuration */
4297         if (wpa_s->drv_flags &
4298             (WPA_DRIVER_FLAGS_P2P_DEDICATED_INTERFACE |
4299              WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P))
4300                 return 1; /* P2P group requires a new interface in every case
4301                            */
4302         if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_CONCURRENT))
4303                 return 0; /* driver does not support concurrent operations */
4304         if (wpa_s->global->ifaces->next)
4305                 return 1; /* more that one interface already in use */
4306         if (wpa_s->wpa_state >= WPA_AUTHENTICATING)
4307                 return 1; /* this interface is already in use */
4308         return 0;
4309 }
4310
4311
4312 static int wpas_p2p_start_go_neg(struct wpa_supplicant *wpa_s,
4313                                  const u8 *peer_addr,
4314                                  enum p2p_wps_method wps_method,
4315                                  int go_intent, const u8 *own_interface_addr,
4316                                  unsigned int force_freq, int persistent_group,
4317                                  struct wpa_ssid *ssid, unsigned int pref_freq)
4318 {
4319         if (persistent_group && wpa_s->conf->persistent_reconnect)
4320                 persistent_group = 2;
4321
4322         /*
4323          * Increase GO config timeout if HT40 is used since it takes some time
4324          * to scan channels for coex purposes before the BSS can be started.
4325          */
4326         p2p_set_config_timeout(wpa_s->global->p2p,
4327                                wpa_s->p2p_go_ht40 ? 255 : 100, 20);
4328
4329         return p2p_connect(wpa_s->global->p2p, peer_addr, wps_method,
4330                            go_intent, own_interface_addr, force_freq,
4331                            persistent_group, ssid ? ssid->ssid : NULL,
4332                            ssid ? ssid->ssid_len : 0,
4333                            wpa_s->p2p_pd_before_go_neg, pref_freq,
4334                            wps_method == WPS_NFC ? wpa_s->p2p_oob_dev_pw_id :
4335                            0);
4336 }
4337
4338
4339 static int wpas_p2p_auth_go_neg(struct wpa_supplicant *wpa_s,
4340                                 const u8 *peer_addr,
4341                                 enum p2p_wps_method wps_method,
4342                                 int go_intent, const u8 *own_interface_addr,
4343                                 unsigned int force_freq, int persistent_group,
4344                                 struct wpa_ssid *ssid, unsigned int pref_freq)
4345 {
4346         if (persistent_group && wpa_s->conf->persistent_reconnect)
4347                 persistent_group = 2;
4348
4349         return p2p_authorize(wpa_s->global->p2p, peer_addr, wps_method,
4350                              go_intent, own_interface_addr, force_freq,
4351                              persistent_group, ssid ? ssid->ssid : NULL,
4352                              ssid ? ssid->ssid_len : 0, pref_freq,
4353                              wps_method == WPS_NFC ? wpa_s->p2p_oob_dev_pw_id :
4354                              0);
4355 }
4356
4357
4358 static void wpas_p2p_check_join_scan_limit(struct wpa_supplicant *wpa_s)
4359 {
4360         wpa_s->p2p_join_scan_count++;
4361         wpa_printf(MSG_DEBUG, "P2P: Join scan attempt %d",
4362                    wpa_s->p2p_join_scan_count);
4363         if (wpa_s->p2p_join_scan_count > P2P_MAX_JOIN_SCAN_ATTEMPTS) {
4364                 wpa_printf(MSG_DEBUG, "P2P: Failed to find GO " MACSTR
4365                            " for join operationg - stop join attempt",
4366                            MAC2STR(wpa_s->pending_join_iface_addr));
4367                 eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
4368                 if (wpa_s->p2p_auto_pd) {
4369                         wpa_s->p2p_auto_pd = 0;
4370                         wpa_msg_global(wpa_s, MSG_INFO,
4371                                        P2P_EVENT_PROV_DISC_FAILURE
4372                                        " p2p_dev_addr=" MACSTR " status=N/A",
4373                                        MAC2STR(wpa_s->pending_join_dev_addr));
4374                         return;
4375                 }
4376                 wpa_msg_global(wpa_s->parent, MSG_INFO,
4377                                P2P_EVENT_GROUP_FORMATION_FAILURE);
4378         }
4379 }
4380
4381
4382 static int wpas_check_freq_conflict(struct wpa_supplicant *wpa_s, int freq)
4383 {
4384         int res;
4385         unsigned int num, i;
4386         struct wpa_used_freq_data *freqs;
4387
4388         if (wpas_p2p_num_unused_channels(wpa_s) > 0) {
4389                 /* Multiple channels are supported and not all are in use */
4390                 return 0;
4391         }
4392
4393         freqs = os_calloc(wpa_s->num_multichan_concurrent,
4394                           sizeof(struct wpa_used_freq_data));
4395         if (!freqs)
4396                 return 1;
4397
4398         num = wpas_p2p_valid_oper_freqs(wpa_s, freqs,
4399                                         wpa_s->num_multichan_concurrent);
4400
4401         for (i = 0; i < num; i++) {
4402                 if (freqs[i].freq == freq) {
4403                         wpa_printf(MSG_DEBUG, "P2P: Frequency %d MHz in use by another virtual interface and can be used",
4404                                    freq);
4405                         res = 0;
4406                         goto exit_free;
4407                 }
4408         }
4409
4410         wpa_printf(MSG_DEBUG, "P2P: No valid operating frequencies");
4411         res = 1;
4412
4413 exit_free:
4414         os_free(freqs);
4415         return res;
4416 }
4417
4418
4419 static int wpas_p2p_peer_go(struct wpa_supplicant *wpa_s,
4420                             const u8 *peer_dev_addr)
4421 {
4422         struct wpa_bss *bss;
4423         int updated;
4424
4425         bss = wpa_bss_get_p2p_dev_addr(wpa_s, peer_dev_addr);
4426         if (bss == NULL)
4427                 return -1;
4428         if (bss->last_update_idx < wpa_s->bss_update_idx) {
4429                 wpa_printf(MSG_DEBUG, "P2P: Peer BSS entry not updated in the "
4430                            "last scan");
4431                 return 0;
4432         }
4433
4434         updated = os_reltime_before(&wpa_s->p2p_auto_started,
4435                                     &bss->last_update);
4436         wpa_printf(MSG_DEBUG, "P2P: Current BSS entry for peer updated at "
4437                    "%ld.%06ld (%supdated in last scan)",
4438                    bss->last_update.sec, bss->last_update.usec,
4439                    updated ? "": "not ");
4440
4441         return updated;
4442 }
4443
4444
4445 static void wpas_p2p_scan_res_join(struct wpa_supplicant *wpa_s,
4446                                    struct wpa_scan_results *scan_res)
4447 {
4448         struct wpa_bss *bss = NULL;
4449         int freq;
4450         u8 iface_addr[ETH_ALEN];
4451
4452         eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
4453
4454         if (wpa_s->global->p2p_disabled)
4455                 return;
4456
4457         wpa_printf(MSG_DEBUG, "P2P: Scan results received (%d BSS) for %sjoin",
4458                    scan_res ? (int) scan_res->num : -1,
4459                    wpa_s->p2p_auto_join ? "auto_" : "");
4460
4461         if (scan_res)
4462                 wpas_p2p_scan_res_handler(wpa_s, scan_res);
4463
4464         if (wpa_s->p2p_auto_pd) {
4465                 int join = wpas_p2p_peer_go(wpa_s,
4466                                             wpa_s->pending_join_dev_addr);
4467                 if (join == 0 &&
4468                     wpa_s->auto_pd_scan_retry < P2P_AUTO_PD_SCAN_ATTEMPTS) {
4469                         wpa_s->auto_pd_scan_retry++;
4470                         bss = wpa_bss_get_bssid_latest(
4471                                 wpa_s, wpa_s->pending_join_dev_addr);
4472                         if (bss) {
4473                                 freq = bss->freq;
4474                                 wpa_printf(MSG_DEBUG, "P2P: Scan retry %d for "
4475                                            "the peer " MACSTR " at %d MHz",
4476                                            wpa_s->auto_pd_scan_retry,
4477                                            MAC2STR(wpa_s->
4478                                                    pending_join_dev_addr),
4479                                            freq);
4480                                 wpas_p2p_join_scan_req(wpa_s, freq, NULL, 0);
4481                                 return;
4482                         }
4483                 }
4484
4485                 if (join < 0)
4486                         join = 0;
4487
4488                 wpa_s->p2p_auto_pd = 0;
4489                 wpa_s->pending_pd_use = join ? AUTO_PD_JOIN : AUTO_PD_GO_NEG;
4490                 wpa_printf(MSG_DEBUG, "P2P: Auto PD with " MACSTR " join=%d",
4491                            MAC2STR(wpa_s->pending_join_dev_addr), join);
4492                 if (p2p_prov_disc_req(wpa_s->global->p2p,
4493                                       wpa_s->pending_join_dev_addr, NULL,
4494                                       wpa_s->pending_pd_config_methods, join,
4495                                       0, wpa_s->user_initiated_pd) < 0) {
4496                         wpa_s->p2p_auto_pd = 0;
4497                         wpa_msg_global(wpa_s, MSG_INFO,
4498                                        P2P_EVENT_PROV_DISC_FAILURE
4499                                        " p2p_dev_addr=" MACSTR " status=N/A",
4500                                        MAC2STR(wpa_s->pending_join_dev_addr));
4501                 }
4502                 return;
4503         }
4504
4505         if (wpa_s->p2p_auto_join) {
4506                 int join = wpas_p2p_peer_go(wpa_s,
4507                                             wpa_s->pending_join_dev_addr);
4508                 if (join < 0) {
4509                         wpa_printf(MSG_DEBUG, "P2P: Peer was not found to be "
4510                                    "running a GO -> use GO Negotiation");
4511                         wpa_msg_global(wpa_s->parent, MSG_INFO,
4512                                        P2P_EVENT_FALLBACK_TO_GO_NEG
4513                                        "reason=peer-not-running-GO");
4514                         wpas_p2p_connect(wpa_s, wpa_s->pending_join_dev_addr,
4515                                          wpa_s->p2p_pin, wpa_s->p2p_wps_method,
4516                                          wpa_s->p2p_persistent_group, 0, 0, 0,
4517                                          wpa_s->p2p_go_intent,
4518                                          wpa_s->p2p_connect_freq,
4519                                          wpa_s->p2p_persistent_id,
4520                                          wpa_s->p2p_pd_before_go_neg,
4521                                          wpa_s->p2p_go_ht40,
4522                                          wpa_s->p2p_go_vht);
4523                         return;
4524                 }
4525
4526                 wpa_printf(MSG_DEBUG, "P2P: Peer was found running GO%s -> "
4527                            "try to join the group", join ? "" :
4528                            " in older scan");
4529                 if (!join) {
4530                         wpa_msg_global(wpa_s->parent, MSG_INFO,
4531                                        P2P_EVENT_FALLBACK_TO_GO_NEG_ENABLED);
4532                         wpa_s->p2p_fallback_to_go_neg = 1;
4533                 }
4534         }
4535
4536         freq = p2p_get_oper_freq(wpa_s->global->p2p,
4537                                  wpa_s->pending_join_iface_addr);
4538         if (freq < 0 &&
4539             p2p_get_interface_addr(wpa_s->global->p2p,
4540                                    wpa_s->pending_join_dev_addr,
4541                                    iface_addr) == 0 &&
4542             os_memcmp(iface_addr, wpa_s->pending_join_dev_addr, ETH_ALEN) != 0
4543             && !wpa_bss_get_bssid(wpa_s, wpa_s->pending_join_iface_addr)) {
4544                 wpa_printf(MSG_DEBUG, "P2P: Overwrite pending interface "
4545                            "address for join from " MACSTR " to " MACSTR
4546                            " based on newly discovered P2P peer entry",
4547                            MAC2STR(wpa_s->pending_join_iface_addr),
4548                            MAC2STR(iface_addr));
4549                 os_memcpy(wpa_s->pending_join_iface_addr, iface_addr,
4550                           ETH_ALEN);
4551
4552                 freq = p2p_get_oper_freq(wpa_s->global->p2p,
4553                                          wpa_s->pending_join_iface_addr);
4554         }
4555         if (freq >= 0) {
4556                 wpa_printf(MSG_DEBUG, "P2P: Target GO operating frequency "
4557                            "from P2P peer table: %d MHz", freq);
4558         }
4559         if (wpa_s->p2p_join_ssid_len) {
4560                 wpa_printf(MSG_DEBUG, "P2P: Trying to find target GO BSS entry based on BSSID "
4561                            MACSTR " and SSID %s",
4562                            MAC2STR(wpa_s->pending_join_iface_addr),
4563                            wpa_ssid_txt(wpa_s->p2p_join_ssid,
4564                                         wpa_s->p2p_join_ssid_len));
4565                 bss = wpa_bss_get(wpa_s, wpa_s->pending_join_iface_addr,
4566                                   wpa_s->p2p_join_ssid,
4567                                   wpa_s->p2p_join_ssid_len);
4568         }
4569         if (!bss) {
4570                 wpa_printf(MSG_DEBUG, "P2P: Trying to find target GO BSS entry based on BSSID "
4571                            MACSTR, MAC2STR(wpa_s->pending_join_iface_addr));
4572                 bss = wpa_bss_get_bssid_latest(wpa_s,
4573                                                wpa_s->pending_join_iface_addr);
4574         }
4575         if (bss) {
4576                 u8 dev_addr[ETH_ALEN];
4577
4578                 freq = bss->freq;
4579                 wpa_printf(MSG_DEBUG, "P2P: Target GO operating frequency "
4580                            "from BSS table: %d MHz (SSID %s)", freq,
4581                            wpa_ssid_txt(bss->ssid, bss->ssid_len));
4582                 if (p2p_parse_dev_addr((const u8 *) (bss + 1), bss->ie_len,
4583                                        dev_addr) == 0 &&
4584                     os_memcmp(wpa_s->pending_join_dev_addr,
4585                               wpa_s->pending_join_iface_addr, ETH_ALEN) == 0 &&
4586                     os_memcmp(dev_addr, wpa_s->pending_join_dev_addr,
4587                               ETH_ALEN) != 0) {
4588                         wpa_printf(MSG_DEBUG,
4589                                    "P2P: Update target GO device address based on BSS entry: " MACSTR " (was " MACSTR ")",
4590                                    MAC2STR(dev_addr),
4591                                    MAC2STR(wpa_s->pending_join_dev_addr));
4592                         os_memcpy(wpa_s->pending_join_dev_addr, dev_addr,
4593                                   ETH_ALEN);
4594                 }
4595         }
4596         if (freq > 0) {
4597                 u16 method;
4598
4599                 if (wpas_check_freq_conflict(wpa_s, freq) > 0) {
4600                         wpa_msg_global(wpa_s->parent, MSG_INFO,
4601                                        P2P_EVENT_GROUP_FORMATION_FAILURE
4602                                        "reason=FREQ_CONFLICT");
4603                         return;
4604                 }
4605
4606                 wpa_printf(MSG_DEBUG, "P2P: Send Provision Discovery Request "
4607                            "prior to joining an existing group (GO " MACSTR
4608                            " freq=%u MHz)",
4609                            MAC2STR(wpa_s->pending_join_dev_addr), freq);
4610                 wpa_s->pending_pd_before_join = 1;
4611
4612                 switch (wpa_s->pending_join_wps_method) {
4613                 case WPS_PIN_DISPLAY:
4614                         method = WPS_CONFIG_KEYPAD;
4615                         break;
4616                 case WPS_PIN_KEYPAD:
4617                         method = WPS_CONFIG_DISPLAY;
4618                         break;
4619                 case WPS_PBC:
4620                         method = WPS_CONFIG_PUSHBUTTON;
4621                         break;
4622                 default:
4623                         method = 0;
4624                         break;
4625                 }
4626
4627                 if ((p2p_get_provisioning_info(wpa_s->global->p2p,
4628                                                wpa_s->pending_join_dev_addr) ==
4629                      method)) {
4630                         /*
4631                          * We have already performed provision discovery for
4632                          * joining the group. Proceed directly to join
4633                          * operation without duplicated provision discovery. */
4634                         wpa_printf(MSG_DEBUG, "P2P: Provision discovery "
4635                                    "with " MACSTR " already done - proceed to "
4636                                    "join",
4637                                    MAC2STR(wpa_s->pending_join_dev_addr));
4638                         wpa_s->pending_pd_before_join = 0;
4639                         goto start;
4640                 }
4641
4642                 if (p2p_prov_disc_req(wpa_s->global->p2p,
4643                                       wpa_s->pending_join_dev_addr,
4644                                       NULL, method, 1,
4645                                       freq, wpa_s->user_initiated_pd) < 0) {
4646                         wpa_printf(MSG_DEBUG, "P2P: Failed to send Provision "
4647                                    "Discovery Request before joining an "
4648                                    "existing group");
4649                         wpa_s->pending_pd_before_join = 0;
4650                         goto start;
4651                 }
4652                 return;
4653         }
4654
4655         wpa_printf(MSG_DEBUG, "P2P: Failed to find BSS/GO - try again later");
4656         eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
4657         eloop_register_timeout(1, 0, wpas_p2p_join_scan, wpa_s, NULL);
4658         wpas_p2p_check_join_scan_limit(wpa_s);
4659         return;
4660
4661 start:
4662         /* Start join operation immediately */
4663         wpas_p2p_join_start(wpa_s, 0, NULL, 0);
4664 }
4665
4666
4667 static void wpas_p2p_join_scan_req(struct wpa_supplicant *wpa_s, int freq,
4668                                    const u8 *ssid, size_t ssid_len)
4669 {
4670         int ret;
4671         struct wpa_driver_scan_params params;
4672         struct wpabuf *wps_ie, *ies;
4673         size_t ielen;
4674         int freqs[2] = { 0, 0 };
4675
4676         os_memset(&params, 0, sizeof(params));
4677
4678         /* P2P Wildcard SSID */
4679         params.num_ssids = 1;
4680         if (ssid && ssid_len) {
4681                 params.ssids[0].ssid = ssid;
4682                 params.ssids[0].ssid_len = ssid_len;
4683                 os_memcpy(wpa_s->p2p_join_ssid, ssid, ssid_len);
4684                 wpa_s->p2p_join_ssid_len = ssid_len;
4685         } else {
4686                 params.ssids[0].ssid = (u8 *) P2P_WILDCARD_SSID;
4687                 params.ssids[0].ssid_len = P2P_WILDCARD_SSID_LEN;
4688                 wpa_s->p2p_join_ssid_len = 0;
4689         }
4690
4691         wpa_s->wps->dev.p2p = 1;
4692         wps_ie = wps_build_probe_req_ie(DEV_PW_DEFAULT, &wpa_s->wps->dev,
4693                                         wpa_s->wps->uuid, WPS_REQ_ENROLLEE, 0,
4694                                         NULL);
4695         if (wps_ie == NULL) {
4696                 wpas_p2p_scan_res_join(wpa_s, NULL);
4697                 return;
4698         }
4699
4700         ielen = p2p_scan_ie_buf_len(wpa_s->global->p2p);
4701         ies = wpabuf_alloc(wpabuf_len(wps_ie) + ielen);
4702         if (ies == NULL) {
4703                 wpabuf_free(wps_ie);
4704                 wpas_p2p_scan_res_join(wpa_s, NULL);
4705                 return;
4706         }
4707         wpabuf_put_buf(ies, wps_ie);
4708         wpabuf_free(wps_ie);
4709
4710         p2p_scan_ie(wpa_s->global->p2p, ies, NULL);
4711
4712         params.p2p_probe = 1;
4713         params.extra_ies = wpabuf_head(ies);
4714         params.extra_ies_len = wpabuf_len(ies);
4715
4716         if (!freq) {
4717                 int oper_freq;
4718                 /*
4719                  * If freq is not provided, check the operating freq of the GO
4720                  * and use a single channel scan on if possible.
4721                  */
4722                 oper_freq = p2p_get_oper_freq(wpa_s->global->p2p,
4723                                               wpa_s->pending_join_iface_addr);
4724                 if (oper_freq > 0)
4725                         freq = oper_freq;
4726         }
4727         if (freq > 0) {
4728                 freqs[0] = freq;
4729                 params.freqs = freqs;
4730         }
4731
4732         /*
4733          * Run a scan to update BSS table and start Provision Discovery once
4734          * the new scan results become available.
4735          */
4736         ret = wpa_drv_scan(wpa_s, &params);
4737         if (!ret) {
4738                 os_get_reltime(&wpa_s->scan_trigger_time);
4739                 wpa_s->scan_res_handler = wpas_p2p_scan_res_join;
4740                 wpa_s->own_scan_requested = 1;
4741         }
4742
4743         wpabuf_free(ies);
4744
4745         if (ret) {
4746                 wpa_printf(MSG_DEBUG, "P2P: Failed to start scan for join - "
4747                            "try again later");
4748                 eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
4749                 eloop_register_timeout(1, 0, wpas_p2p_join_scan, wpa_s, NULL);
4750                 wpas_p2p_check_join_scan_limit(wpa_s);
4751         }
4752 }
4753
4754
4755 static void wpas_p2p_join_scan(void *eloop_ctx, void *timeout_ctx)
4756 {
4757         struct wpa_supplicant *wpa_s = eloop_ctx;
4758         wpas_p2p_join_scan_req(wpa_s, 0, NULL, 0);
4759 }
4760
4761
4762 static int wpas_p2p_join(struct wpa_supplicant *wpa_s, const u8 *iface_addr,
4763                          const u8 *dev_addr, enum p2p_wps_method wps_method,
4764                          int auto_join, int op_freq,
4765                          const u8 *ssid, size_t ssid_len)
4766 {
4767         wpa_printf(MSG_DEBUG, "P2P: Request to join existing group (iface "
4768                    MACSTR " dev " MACSTR " op_freq=%d)%s",
4769                    MAC2STR(iface_addr), MAC2STR(dev_addr), op_freq,
4770                    auto_join ? " (auto_join)" : "");
4771         if (ssid && ssid_len) {
4772                 wpa_printf(MSG_DEBUG, "P2P: Group SSID specified: %s",
4773                            wpa_ssid_txt(ssid, ssid_len));
4774         }
4775
4776         wpa_s->p2p_auto_pd = 0;
4777         wpa_s->p2p_auto_join = !!auto_join;
4778         os_memcpy(wpa_s->pending_join_iface_addr, iface_addr, ETH_ALEN);
4779         os_memcpy(wpa_s->pending_join_dev_addr, dev_addr, ETH_ALEN);
4780         wpa_s->pending_join_wps_method = wps_method;
4781
4782         /* Make sure we are not running find during connection establishment */
4783         wpas_p2p_stop_find(wpa_s);
4784
4785         wpa_s->p2p_join_scan_count = 0;
4786         wpas_p2p_join_scan_req(wpa_s, op_freq, ssid, ssid_len);
4787         return 0;
4788 }
4789
4790
4791 static int wpas_p2p_join_start(struct wpa_supplicant *wpa_s, int freq,
4792                                const u8 *ssid, size_t ssid_len)
4793 {
4794         struct wpa_supplicant *group;
4795         struct p2p_go_neg_results res;
4796         struct wpa_bss *bss;
4797
4798         group = wpas_p2p_get_group_iface(wpa_s, 0, 0);
4799         if (group == NULL)
4800                 return -1;
4801         if (group != wpa_s) {
4802                 os_memcpy(group->p2p_pin, wpa_s->p2p_pin,
4803                           sizeof(group->p2p_pin));
4804                 group->p2p_wps_method = wpa_s->p2p_wps_method;
4805         } else {
4806                 /*
4807                  * Need to mark the current interface for p2p_group_formation
4808                  * when a separate group interface is not used. This is needed
4809                  * to allow p2p_cancel stop a pending p2p_connect-join.
4810                  * wpas_p2p_init_group_interface() addresses this for the case
4811                  * where a separate group interface is used.
4812                  */
4813                 wpa_s->global->p2p_group_formation = wpa_s;
4814         }
4815
4816         group->p2p_in_provisioning = 1;
4817         group->p2p_fallback_to_go_neg = wpa_s->p2p_fallback_to_go_neg;
4818
4819         os_memset(&res, 0, sizeof(res));
4820         os_memcpy(res.peer_device_addr, wpa_s->pending_join_dev_addr, ETH_ALEN);
4821         os_memcpy(res.peer_interface_addr, wpa_s->pending_join_iface_addr,
4822                   ETH_ALEN);
4823         res.wps_method = wpa_s->pending_join_wps_method;
4824         if (freq && ssid && ssid_len) {
4825                 res.freq = freq;
4826                 res.ssid_len = ssid_len;
4827                 os_memcpy(res.ssid, ssid, ssid_len);
4828         } else {
4829                 bss = wpa_bss_get_bssid_latest(wpa_s,
4830                                                wpa_s->pending_join_iface_addr);
4831                 if (bss) {
4832                         res.freq = bss->freq;
4833                         res.ssid_len = bss->ssid_len;
4834                         os_memcpy(res.ssid, bss->ssid, bss->ssid_len);
4835                         wpa_printf(MSG_DEBUG, "P2P: Join target GO operating frequency from BSS table: %d MHz (SSID %s)",
4836                                    bss->freq,
4837                                    wpa_ssid_txt(bss->ssid, bss->ssid_len));
4838                 }
4839         }
4840
4841         if (wpa_s->off_channel_freq || wpa_s->roc_waiting_drv_freq) {
4842                 wpa_printf(MSG_DEBUG, "P2P: Cancel remain-on-channel prior to "
4843                            "starting client");
4844                 wpa_drv_cancel_remain_on_channel(wpa_s);
4845                 wpa_s->off_channel_freq = 0;
4846                 wpa_s->roc_waiting_drv_freq = 0;
4847         }
4848         wpas_start_wps_enrollee(group, &res);
4849
4850         /*
4851          * Allow a longer timeout for join-a-running-group than normal 15
4852          * second group formation timeout since the GO may not have authorized
4853          * our connection yet.
4854          */
4855         eloop_cancel_timeout(wpas_p2p_group_formation_timeout, wpa_s, NULL);
4856         eloop_register_timeout(60, 0, wpas_p2p_group_formation_timeout,
4857                                wpa_s, NULL);
4858
4859         return 0;
4860 }
4861
4862
4863 static int wpas_p2p_setup_freqs(struct wpa_supplicant *wpa_s, int freq,
4864                                 int *force_freq, int *pref_freq, int go,
4865                                 unsigned int *pref_freq_list,
4866                                 unsigned int *num_pref_freq)
4867 {
4868         struct wpa_used_freq_data *freqs;
4869         int res, best_freq, num_unused;
4870         unsigned int freq_in_use = 0, num, i, max_pref_freq;
4871
4872         max_pref_freq = *num_pref_freq;
4873         *num_pref_freq = 0;
4874
4875         freqs = os_calloc(wpa_s->num_multichan_concurrent,
4876                           sizeof(struct wpa_used_freq_data));
4877         if (!freqs)
4878                 return -1;
4879
4880         num = wpas_p2p_valid_oper_freqs(wpa_s, freqs,
4881                                         wpa_s->num_multichan_concurrent);
4882
4883         /*
4884          * It is possible that the total number of used frequencies is bigger
4885          * than the number of frequencies used for P2P, so get the system wide
4886          * number of unused frequencies.
4887          */
4888         num_unused = wpas_p2p_num_unused_channels(wpa_s);
4889
4890         wpa_printf(MSG_DEBUG,
4891                    "P2P: Setup freqs: freq=%d num_MCC=%d shared_freqs=%u num_unused=%d",
4892                    freq, wpa_s->num_multichan_concurrent, num, num_unused);
4893
4894         if (freq > 0) {
4895                 int ret;
4896                 if (go)
4897                         ret = p2p_supported_freq(wpa_s->global->p2p, freq);
4898                 else
4899                         ret = p2p_supported_freq_cli(wpa_s->global->p2p, freq);
4900                 if (!ret) {
4901                         if ((wpa_s->drv_flags & WPA_DRIVER_FLAGS_DFS_OFFLOAD) &&
4902                             ieee80211_is_dfs(freq)) {
4903                                 /*
4904                                  * If freq is a DFS channel and DFS is offloaded
4905                                  * to the driver, allow P2P GO to use it.
4906                                  */
4907                                 wpa_printf(MSG_DEBUG,
4908                                            "P2P: The forced channel for GO (%u MHz) is DFS, and DFS is offloaded to the driver",
4909                                            freq);
4910                         } else {
4911                                 wpa_printf(MSG_DEBUG,
4912                                            "P2P: The forced channel (%u MHz) is not supported for P2P uses",
4913                                            freq);
4914                                 res = -3;
4915                                 goto exit_free;
4916                         }
4917                 }
4918
4919                 for (i = 0; i < num; i++) {
4920                         if (freqs[i].freq == freq)
4921                                 freq_in_use = 1;
4922                 }
4923
4924                 if (num_unused <= 0 && !freq_in_use) {
4925                         wpa_printf(MSG_DEBUG, "P2P: Cannot start P2P group on %u MHz as there are no available channels",
4926                                    freq);
4927                         res = -2;
4928                         goto exit_free;
4929                 }
4930                 wpa_printf(MSG_DEBUG, "P2P: Trying to force us to use the "
4931                            "requested channel (%u MHz)", freq);
4932                 *force_freq = freq;
4933                 goto exit_ok;
4934         }
4935
4936         best_freq = wpas_p2p_pick_best_used_freq(wpa_s, freqs, num);
4937
4938         if (!wpa_s->conf->num_p2p_pref_chan && *pref_freq == 0) {
4939                 enum wpa_driver_if_type iface_type;
4940
4941                 if (go)
4942                         iface_type = WPA_IF_P2P_GO;
4943                 else
4944                         iface_type = WPA_IF_P2P_CLIENT;
4945
4946                 wpa_printf(MSG_DEBUG, "P2P: best_freq=%d, go=%d",
4947                            best_freq, go);
4948
4949                 res = wpa_drv_get_pref_freq_list(wpa_s, iface_type,
4950                                                  &max_pref_freq,
4951                                                  pref_freq_list);
4952                 if (!res && max_pref_freq > 0) {
4953                         *num_pref_freq = max_pref_freq;
4954                         i = 0;
4955                         while (wpas_p2p_disallowed_freq(wpa_s->global,
4956                                                         pref_freq_list[i]) &&
4957                                i < *num_pref_freq) {
4958                                 wpa_printf(MSG_DEBUG,
4959                                            "P2P: preferred_freq_list[%d]=%d is disallowed",
4960                                            i, pref_freq_list[i]);
4961                                 i++;
4962                         }
4963                         if (i != *num_pref_freq) {
4964                                 best_freq = pref_freq_list[i];
4965                                 wpa_printf(MSG_DEBUG,
4966                                            "P2P: Using preferred_freq_list[%d]=%d",
4967                                            i, best_freq);
4968                         } else {
4969                                 wpa_printf(MSG_DEBUG,
4970                                            "P2P: All driver preferred frequencies are disallowed for P2P use");
4971                                 *num_pref_freq = 0;
4972                         }
4973                 } else {
4974                         wpa_printf(MSG_DEBUG,
4975                                    "P2P: No preferred frequency list available");
4976                 }
4977         }
4978
4979         /* We have a candidate frequency to use */
4980         if (best_freq > 0) {
4981                 if (*pref_freq == 0 && num_unused > 0) {
4982                         wpa_printf(MSG_DEBUG, "P2P: Try to prefer a frequency (%u MHz) we are already using",
4983                                    best_freq);
4984                         *pref_freq = best_freq;
4985                 } else {
4986                         wpa_printf(MSG_DEBUG, "P2P: Try to force us to use frequency (%u MHz) which is already in use",
4987                                    best_freq);
4988                         *force_freq = best_freq;
4989                 }
4990         } else if (num_unused > 0) {
4991                 wpa_printf(MSG_DEBUG,
4992                            "P2P: Current operating channels are not available for P2P. Try to use another channel");
4993                 *force_freq = 0;
4994         } else {
4995                 wpa_printf(MSG_DEBUG,
4996                            "P2P: All channels are in use and none of them are P2P enabled. Cannot start P2P group");
4997                 res = -2;
4998                 goto exit_free;
4999         }
5000
5001 exit_ok:
5002         res = 0;
5003 exit_free:
5004         os_free(freqs);
5005         return res;
5006 }
5007
5008
5009 /**
5010  * wpas_p2p_connect - Request P2P Group Formation to be started
5011  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
5012  * @peer_addr: Address of the peer P2P Device
5013  * @pin: PIN to use during provisioning or %NULL to indicate PBC mode
5014  * @persistent_group: Whether to create a persistent group
5015  * @auto_join: Whether to select join vs. GO Negotiation automatically
5016  * @join: Whether to join an existing group (as a client) instead of starting
5017  *      Group Owner negotiation; @peer_addr is BSSID in that case
5018  * @auth: Whether to only authorize the connection instead of doing that and
5019  *      initiating Group Owner negotiation
5020  * @go_intent: GO Intent or -1 to use default
5021  * @freq: Frequency for the group or 0 for auto-selection
5022  * @persistent_id: Persistent group credentials to use for forcing GO
5023  *      parameters or -1 to generate new values (SSID/passphrase)
5024  * @pd: Whether to send Provision Discovery prior to GO Negotiation as an
5025  *      interoperability workaround when initiating group formation
5026  * @ht40: Start GO with 40 MHz channel width
5027  * @vht:  Start GO with VHT support
5028  * Returns: 0 or new PIN (if pin was %NULL) on success, -1 on unspecified
5029  *      failure, -2 on failure due to channel not currently available,
5030  *      -3 if forced channel is not supported
5031  */
5032 int wpas_p2p_connect(struct wpa_supplicant *wpa_s, const u8 *peer_addr,
5033                      const char *pin, enum p2p_wps_method wps_method,
5034                      int persistent_group, int auto_join, int join, int auth,
5035                      int go_intent, int freq, int persistent_id, int pd,
5036                      int ht40, int vht)
5037 {
5038         int force_freq = 0, pref_freq = 0;
5039         int ret = 0, res;
5040         enum wpa_driver_if_type iftype;
5041         const u8 *if_addr;
5042         struct wpa_ssid *ssid = NULL;
5043         unsigned int pref_freq_list[P2P_MAX_PREF_CHANNELS], size;
5044
5045         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5046                 return -1;
5047
5048         if (persistent_id >= 0) {
5049                 ssid = wpa_config_get_network(wpa_s->conf, persistent_id);
5050                 if (ssid == NULL || ssid->disabled != 2 ||
5051                     ssid->mode != WPAS_MODE_P2P_GO)
5052                         return -1;
5053         }
5054
5055         os_free(wpa_s->global->add_psk);
5056         wpa_s->global->add_psk = NULL;
5057
5058         wpa_s->global->p2p_fail_on_wps_complete = 0;
5059         wpa_s->global->pending_p2ps_group = 0;
5060
5061         if (go_intent < 0)
5062                 go_intent = wpa_s->conf->p2p_go_intent;
5063
5064         if (!auth)
5065                 wpa_s->p2p_long_listen = 0;
5066
5067         wpa_s->p2p_wps_method = wps_method;
5068         wpa_s->p2p_persistent_group = !!persistent_group;
5069         wpa_s->p2p_persistent_id = persistent_id;
5070         wpa_s->p2p_go_intent = go_intent;
5071         wpa_s->p2p_connect_freq = freq;
5072         wpa_s->p2p_fallback_to_go_neg = 0;
5073         wpa_s->p2p_pd_before_go_neg = !!pd;
5074         wpa_s->p2p_go_ht40 = !!ht40;
5075         wpa_s->p2p_go_vht = !!vht;
5076
5077         if (pin)
5078                 os_strlcpy(wpa_s->p2p_pin, pin, sizeof(wpa_s->p2p_pin));
5079         else if (wps_method == WPS_PIN_DISPLAY) {
5080                 ret = wps_generate_pin();
5081                 res = os_snprintf(wpa_s->p2p_pin, sizeof(wpa_s->p2p_pin),
5082                                   "%08d", ret);
5083                 if (os_snprintf_error(sizeof(wpa_s->p2p_pin), res))
5084                         wpa_s->p2p_pin[sizeof(wpa_s->p2p_pin) - 1] = '\0';
5085                 wpa_printf(MSG_DEBUG, "P2P: Randomly generated PIN: %s",
5086                            wpa_s->p2p_pin);
5087         } else
5088                 wpa_s->p2p_pin[0] = '\0';
5089
5090         if (join || auto_join) {
5091                 u8 iface_addr[ETH_ALEN], dev_addr[ETH_ALEN];
5092                 if (auth) {
5093                         wpa_printf(MSG_DEBUG, "P2P: Authorize invitation to "
5094                                    "connect a running group from " MACSTR,
5095                                    MAC2STR(peer_addr));
5096                         os_memcpy(wpa_s->p2p_auth_invite, peer_addr, ETH_ALEN);
5097                         return ret;
5098                 }
5099                 os_memcpy(dev_addr, peer_addr, ETH_ALEN);
5100                 if (p2p_get_interface_addr(wpa_s->global->p2p, peer_addr,
5101                                            iface_addr) < 0) {
5102                         os_memcpy(iface_addr, peer_addr, ETH_ALEN);
5103                         p2p_get_dev_addr(wpa_s->global->p2p, peer_addr,
5104                                          dev_addr);
5105                 }
5106                 if (auto_join) {
5107                         os_get_reltime(&wpa_s->p2p_auto_started);
5108                         wpa_printf(MSG_DEBUG, "P2P: Auto join started at "
5109                                    "%ld.%06ld",
5110                                    wpa_s->p2p_auto_started.sec,
5111                                    wpa_s->p2p_auto_started.usec);
5112                 }
5113                 wpa_s->user_initiated_pd = 1;
5114                 if (wpas_p2p_join(wpa_s, iface_addr, dev_addr, wps_method,
5115                                   auto_join, freq, NULL, 0) < 0)
5116                         return -1;
5117                 return ret;
5118         }
5119
5120         size = P2P_MAX_PREF_CHANNELS;
5121         res = wpas_p2p_setup_freqs(wpa_s, freq, &force_freq, &pref_freq,
5122                                    go_intent == 15, pref_freq_list, &size);
5123         if (res)
5124                 return res;
5125         wpas_p2p_set_own_freq_preference(wpa_s,
5126                                          force_freq ? force_freq : pref_freq);
5127
5128         p2p_set_own_pref_freq_list(wpa_s->global->p2p, pref_freq_list, size);
5129
5130         wpa_s->create_p2p_iface = wpas_p2p_create_iface(wpa_s);
5131
5132         if (wpa_s->create_p2p_iface) {
5133                 /* Prepare to add a new interface for the group */
5134                 iftype = WPA_IF_P2P_GROUP;
5135                 if (go_intent == 15)
5136                         iftype = WPA_IF_P2P_GO;
5137                 if (wpas_p2p_add_group_interface(wpa_s, iftype) < 0) {
5138                         wpa_printf(MSG_ERROR, "P2P: Failed to allocate a new "
5139                                    "interface for the group");
5140                         return -1;
5141                 }
5142
5143                 if_addr = wpa_s->pending_interface_addr;
5144         } else {
5145                 if_addr = wpa_s->own_addr;
5146                 os_memset(wpa_s->go_dev_addr, 0, ETH_ALEN);
5147         }
5148
5149         if (auth) {
5150                 if (wpas_p2p_auth_go_neg(wpa_s, peer_addr, wps_method,
5151                                          go_intent, if_addr,
5152                                          force_freq, persistent_group, ssid,
5153                                          pref_freq) < 0)
5154                         return -1;
5155                 return ret;
5156         }
5157
5158         if (wpas_p2p_start_go_neg(wpa_s, peer_addr, wps_method,
5159                                   go_intent, if_addr, force_freq,
5160                                   persistent_group, ssid, pref_freq) < 0) {
5161                 if (wpa_s->create_p2p_iface)
5162                         wpas_p2p_remove_pending_group_interface(wpa_s);
5163                 return -1;
5164         }
5165         return ret;
5166 }
5167
5168
5169 /**
5170  * wpas_p2p_remain_on_channel_cb - Indication of remain-on-channel start
5171  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
5172  * @freq: Frequency of the channel in MHz
5173  * @duration: Duration of the stay on the channel in milliseconds
5174  *
5175  * This callback is called when the driver indicates that it has started the
5176  * requested remain-on-channel duration.
5177  */
5178 void wpas_p2p_remain_on_channel_cb(struct wpa_supplicant *wpa_s,
5179                                    unsigned int freq, unsigned int duration)
5180 {
5181         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5182                 return;
5183         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)",
5184                    wpa_s->off_channel_freq, wpa_s->pending_listen_freq,
5185                    wpa_s->roc_waiting_drv_freq, freq, duration);
5186         if (wpa_s->off_channel_freq &&
5187             wpa_s->off_channel_freq == wpa_s->pending_listen_freq) {
5188                 p2p_listen_cb(wpa_s->global->p2p, wpa_s->pending_listen_freq,
5189                               wpa_s->pending_listen_duration);
5190                 wpa_s->pending_listen_freq = 0;
5191         } else {
5192                 wpa_printf(MSG_DEBUG, "P2P: Ignore remain-on-channel callback (off_channel_freq=%u pending_listen_freq=%d freq=%u duration=%u)",
5193                            wpa_s->off_channel_freq, wpa_s->pending_listen_freq,
5194                            freq, duration);
5195         }
5196 }
5197
5198
5199 int wpas_p2p_listen_start(struct wpa_supplicant *wpa_s, unsigned int timeout)
5200 {
5201         /* Limit maximum Listen state time based on driver limitation. */
5202         if (timeout > wpa_s->max_remain_on_chan)
5203                 timeout = wpa_s->max_remain_on_chan;
5204
5205         return p2p_listen(wpa_s->global->p2p, timeout);
5206 }
5207
5208
5209 /**
5210  * wpas_p2p_cancel_remain_on_channel_cb - Remain-on-channel timeout
5211  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
5212  * @freq: Frequency of the channel in MHz
5213  *
5214  * This callback is called when the driver indicates that a remain-on-channel
5215  * operation has been completed, i.e., the duration on the requested channel
5216  * has timed out.
5217  */
5218 void wpas_p2p_cancel_remain_on_channel_cb(struct wpa_supplicant *wpa_s,
5219                                           unsigned int freq)
5220 {
5221         wpa_printf(MSG_DEBUG, "P2P: Cancel remain-on-channel callback "
5222                    "(p2p_long_listen=%d ms pending_action_tx=%p)",
5223                    wpa_s->p2p_long_listen, offchannel_pending_action_tx(wpa_s));
5224         wpas_p2p_listen_work_done(wpa_s);
5225         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5226                 return;
5227         if (wpa_s->p2p_long_listen > 0)
5228                 wpa_s->p2p_long_listen -= wpa_s->max_remain_on_chan;
5229         if (p2p_listen_end(wpa_s->global->p2p, freq) > 0)
5230                 return; /* P2P module started a new operation */
5231         if (offchannel_pending_action_tx(wpa_s))
5232                 return;
5233         if (wpa_s->p2p_long_listen > 0) {
5234                 wpa_printf(MSG_DEBUG, "P2P: Continuing long Listen state");
5235                 wpas_p2p_listen_start(wpa_s, wpa_s->p2p_long_listen);
5236         } else {
5237                 /*
5238                  * When listen duration is over, stop listen & update p2p_state
5239                  * to IDLE.
5240                  */
5241                 p2p_stop_listen(wpa_s->global->p2p);
5242         }
5243 }
5244
5245
5246 /**
5247  * wpas_p2p_group_remove - Remove a P2P group
5248  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
5249  * @ifname: Network interface name of the group interface or "*" to remove all
5250  *      groups
5251  * Returns: 0 on success, -1 on failure
5252  *
5253  * This function is used to remove a P2P group. This can be used to disconnect
5254  * from a group in which the local end is a P2P Client or to end a P2P Group in
5255  * case the local end is the Group Owner. If a virtual network interface was
5256  * created for this group, that interface will be removed. Otherwise, only the
5257  * configured P2P group network will be removed from the interface.
5258  */
5259 int wpas_p2p_group_remove(struct wpa_supplicant *wpa_s, const char *ifname)
5260 {
5261         struct wpa_global *global = wpa_s->global;
5262         struct wpa_supplicant *calling_wpa_s = wpa_s;
5263
5264         if (os_strcmp(ifname, "*") == 0) {
5265                 struct wpa_supplicant *prev;
5266                 wpa_s = global->ifaces;
5267                 while (wpa_s) {
5268                         prev = wpa_s;
5269                         wpa_s = wpa_s->next;
5270                         if (prev->p2p_group_interface !=
5271                             NOT_P2P_GROUP_INTERFACE ||
5272                             (prev->current_ssid &&
5273                              prev->current_ssid->p2p_group))
5274                                 wpas_p2p_disconnect_safely(prev, calling_wpa_s);
5275                 }
5276                 return 0;
5277         }
5278
5279         for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) {
5280                 if (os_strcmp(wpa_s->ifname, ifname) == 0)
5281                         break;
5282         }
5283
5284         return wpas_p2p_disconnect_safely(wpa_s, calling_wpa_s);
5285 }
5286
5287
5288 static int wpas_p2p_select_go_freq(struct wpa_supplicant *wpa_s, int freq)
5289 {
5290         unsigned int r;
5291
5292         if (freq == 2) {
5293                 wpa_printf(MSG_DEBUG, "P2P: Request to start GO on 2.4 GHz "
5294                            "band");
5295                 if (wpa_s->best_24_freq > 0 &&
5296                     p2p_supported_freq_go(wpa_s->global->p2p,
5297                                           wpa_s->best_24_freq)) {
5298                         freq = wpa_s->best_24_freq;
5299                         wpa_printf(MSG_DEBUG, "P2P: Use best 2.4 GHz band "
5300                                    "channel: %d MHz", freq);
5301                 } else {
5302                         if (os_get_random((u8 *) &r, sizeof(r)) < 0)
5303                                 return -1;
5304                         freq = 2412 + (r % 3) * 25;
5305                         wpa_printf(MSG_DEBUG, "P2P: Use random 2.4 GHz band "
5306                                    "channel: %d MHz", freq);
5307                 }
5308         }
5309
5310         if (freq == 5) {
5311                 wpa_printf(MSG_DEBUG, "P2P: Request to start GO on 5 GHz "
5312                            "band");
5313                 if (wpa_s->best_5_freq > 0 &&
5314                     p2p_supported_freq_go(wpa_s->global->p2p,
5315                                        wpa_s->best_5_freq)) {
5316                         freq = wpa_s->best_5_freq;
5317                         wpa_printf(MSG_DEBUG, "P2P: Use best 5 GHz band "
5318                                    "channel: %d MHz", freq);
5319                 } else {
5320                         if (os_get_random((u8 *) &r, sizeof(r)) < 0)
5321                                 return -1;
5322                         freq = 5180 + (r % 4) * 20;
5323                         if (!p2p_supported_freq_go(wpa_s->global->p2p, freq)) {
5324                                 wpa_printf(MSG_DEBUG, "P2P: Could not select "
5325                                            "5 GHz channel for P2P group");
5326                                 return -1;
5327                         }
5328                         wpa_printf(MSG_DEBUG, "P2P: Use random 5 GHz band "
5329                                    "channel: %d MHz", freq);
5330                 }
5331         }
5332
5333         if (freq > 0 && !p2p_supported_freq_go(wpa_s->global->p2p, freq)) {
5334                 if ((wpa_s->drv_flags & WPA_DRIVER_FLAGS_DFS_OFFLOAD) &&
5335                     ieee80211_is_dfs(freq)) {
5336                         /*
5337                          * If freq is a DFS channel and DFS is offloaded to the
5338                          * driver, allow P2P GO to use it.
5339                          */
5340                         wpa_printf(MSG_DEBUG, "P2P: "
5341                                    "%s: The forced channel for GO (%u MHz) is DFS, and DFS is offloaded",
5342                                    __func__, freq);
5343                         return freq;
5344                 }
5345                 wpa_printf(MSG_DEBUG, "P2P: The forced channel for GO "
5346                            "(%u MHz) is not supported for P2P uses",
5347                            freq);
5348                 return -1;
5349         }
5350
5351         return freq;
5352 }
5353
5354
5355 static int wpas_p2p_select_freq_no_pref(struct wpa_supplicant *wpa_s,
5356                                         struct p2p_go_neg_results *params,
5357                                         const struct p2p_channels *channels)
5358 {
5359         unsigned int i, r;
5360
5361         /* first try some random selection of the social channels */
5362         if (os_get_random((u8 *) &r, sizeof(r)) < 0)
5363                 return -1;
5364
5365         for (i = 0; i < 3; i++) {
5366                 params->freq = 2412 + ((r + i) % 3) * 25;
5367                 if (!wpas_p2p_disallowed_freq(wpa_s->global, params->freq) &&
5368                     freq_included(channels, params->freq) &&
5369                     p2p_supported_freq(wpa_s->global->p2p, params->freq))
5370                         goto out;
5371         }
5372
5373         /* try all channels in reg. class 81 */
5374         for (i = 0; i < 11; i++) {
5375                 params->freq = 2412 + i * 5;
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
5382         /* try all channels in operating class 115 */
5383         for (i = 0; i < 4; i++) {
5384                 params->freq = 5180 + i * 20;
5385                 if (!wpas_p2p_disallowed_freq(wpa_s->global, params->freq) &&
5386                     freq_included(channels, params->freq) &&
5387                     p2p_supported_freq(wpa_s->global->p2p, params->freq))
5388                         goto out;
5389         }
5390
5391         /* try all channels in operating class 124 */
5392         for (i = 0; i < 4; i++) {
5393                 params->freq = 5745 + i * 20;
5394                 if (!wpas_p2p_disallowed_freq(wpa_s->global, params->freq) &&
5395                     freq_included(channels, params->freq) &&
5396                     p2p_supported_freq(wpa_s->global->p2p, params->freq))
5397                         goto out;
5398         }
5399
5400         /* try social channel class 180 channel 2 */
5401         params->freq = 58320 + 1 * 2160;
5402         if (!wpas_p2p_disallowed_freq(wpa_s->global, params->freq) &&
5403             freq_included(channels, params->freq) &&
5404             p2p_supported_freq(wpa_s->global->p2p, params->freq))
5405                 goto out;
5406
5407         /* try all channels in reg. class 180 */
5408         for (i = 0; i < 4; i++) {
5409                 params->freq = 58320 + i * 2160;
5410                 if (!wpas_p2p_disallowed_freq(wpa_s->global, params->freq) &&
5411                     freq_included(channels, params->freq) &&
5412                     p2p_supported_freq(wpa_s->global->p2p, params->freq))
5413                         goto out;
5414         }
5415
5416         wpa_printf(MSG_DEBUG, "P2P: No 2.4, 5, or 60 GHz channel allowed");
5417         return -1;
5418 out:
5419         wpa_printf(MSG_DEBUG, "P2P: Set GO freq %d MHz (no preference known)",
5420                    params->freq);
5421         return 0;
5422 }
5423
5424
5425 static int wpas_p2p_init_go_params(struct wpa_supplicant *wpa_s,
5426                                    struct p2p_go_neg_results *params,
5427                                    int freq, int ht40, int vht,
5428                                    const struct p2p_channels *channels)
5429 {
5430         struct wpa_used_freq_data *freqs;
5431         unsigned int pref_freq, cand_freq;
5432         unsigned int num, i;
5433
5434         os_memset(params, 0, sizeof(*params));
5435         params->role_go = 1;
5436         params->ht40 = ht40;
5437         params->vht = vht;
5438         if (freq) {
5439                 if (!freq_included(channels, freq)) {
5440                         wpa_printf(MSG_DEBUG, "P2P: Forced GO freq %d MHz not "
5441                                    "accepted", freq);
5442                         return -1;
5443                 }
5444                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on forced "
5445                            "frequency %d MHz", freq);
5446                 params->freq = freq;
5447         } else if (wpa_s->conf->p2p_oper_reg_class == 81 &&
5448                    wpa_s->conf->p2p_oper_channel >= 1 &&
5449                    wpa_s->conf->p2p_oper_channel <= 11 &&
5450                    freq_included(channels,
5451                                  2407 + 5 * wpa_s->conf->p2p_oper_channel)) {
5452                 params->freq = 2407 + 5 * wpa_s->conf->p2p_oper_channel;
5453                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on configured "
5454                            "frequency %d MHz", params->freq);
5455         } else if ((wpa_s->conf->p2p_oper_reg_class == 115 ||
5456                     wpa_s->conf->p2p_oper_reg_class == 116 ||
5457                     wpa_s->conf->p2p_oper_reg_class == 117 ||
5458                     wpa_s->conf->p2p_oper_reg_class == 124 ||
5459                     wpa_s->conf->p2p_oper_reg_class == 125 ||
5460                     wpa_s->conf->p2p_oper_reg_class == 126 ||
5461                     wpa_s->conf->p2p_oper_reg_class == 127) &&
5462                    freq_included(channels,
5463                                  5000 + 5 * wpa_s->conf->p2p_oper_channel)) {
5464                 params->freq = 5000 + 5 * wpa_s->conf->p2p_oper_channel;
5465                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on configured "
5466                            "frequency %d MHz", params->freq);
5467         } else if (wpa_s->conf->p2p_oper_channel == 0 &&
5468                    wpa_s->best_overall_freq > 0 &&
5469                    p2p_supported_freq_go(wpa_s->global->p2p,
5470                                          wpa_s->best_overall_freq) &&
5471                    freq_included(channels, wpa_s->best_overall_freq)) {
5472                 params->freq = wpa_s->best_overall_freq;
5473                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on best overall "
5474                            "channel %d MHz", params->freq);
5475         } else if (wpa_s->conf->p2p_oper_channel == 0 &&
5476                    wpa_s->best_24_freq > 0 &&
5477                    p2p_supported_freq_go(wpa_s->global->p2p,
5478                                          wpa_s->best_24_freq) &&
5479                    freq_included(channels, wpa_s->best_24_freq)) {
5480                 params->freq = wpa_s->best_24_freq;
5481                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on best 2.4 GHz "
5482                            "channel %d MHz", params->freq);
5483         } else if (wpa_s->conf->p2p_oper_channel == 0 &&
5484                    wpa_s->best_5_freq > 0 &&
5485                    p2p_supported_freq_go(wpa_s->global->p2p,
5486                                          wpa_s->best_5_freq) &&
5487                    freq_included(channels, wpa_s->best_5_freq)) {
5488                 params->freq = wpa_s->best_5_freq;
5489                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on best 5 GHz "
5490                            "channel %d MHz", params->freq);
5491         } else if ((pref_freq = p2p_get_pref_freq(wpa_s->global->p2p,
5492                                                   channels))) {
5493                 params->freq = pref_freq;
5494                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq %d MHz from preferred "
5495                            "channels", params->freq);
5496         } else {
5497                 /* no preference, select some channel */
5498                 if (wpas_p2p_select_freq_no_pref(wpa_s, params, channels) < 0)
5499                         return -1;
5500         }
5501
5502         freqs = os_calloc(wpa_s->num_multichan_concurrent,
5503                           sizeof(struct wpa_used_freq_data));
5504         if (!freqs)
5505                 return -1;
5506
5507         num = wpas_p2p_valid_oper_freqs(wpa_s, freqs,
5508                                         wpa_s->num_multichan_concurrent);
5509
5510         cand_freq = wpas_p2p_pick_best_used_freq(wpa_s, freqs, num);
5511
5512         /* First try the best used frequency if possible */
5513         if (!freq && cand_freq > 0 && freq_included(channels, cand_freq)) {
5514                 params->freq = cand_freq;
5515         } else if (!freq) {
5516                 /* Try any of the used frequencies */
5517                 for (i = 0; i < num; i++) {
5518                         if (freq_included(channels, freqs[i].freq)) {
5519                                 wpa_printf(MSG_DEBUG, "P2P: Force GO on a channel we are already using (%u MHz)",
5520                                            freqs[i].freq);
5521                                 params->freq = freqs[i].freq;
5522                                 break;
5523                         }
5524                 }
5525
5526                 if (i == num) {
5527                         if (wpas_p2p_num_unused_channels(wpa_s) <= 0) {
5528                                 wpa_printf(MSG_DEBUG, "P2P: Cannot force GO on any of the channels we are already using");
5529                                 os_free(freqs);
5530                                 return -1;
5531                         } else {
5532                                 wpa_printf(MSG_DEBUG, "P2P: Cannot force GO on any of the channels we are already using. Use one of the free channels");
5533                         }
5534                 }
5535         } else {
5536                 for (i = 0; i < num; i++) {
5537                         if (freqs[i].freq == freq)
5538                                 break;
5539                 }
5540
5541                 if (i == num) {
5542                         if (wpas_p2p_num_unused_channels(wpa_s) <= 0) {
5543                                 if (freq)
5544                                         wpa_printf(MSG_DEBUG, "P2P: Cannot force GO on freq (%u MHz) as all the channels are in use", freq);
5545                                 os_free(freqs);
5546                                 return -1;
5547                         } else {
5548                                 wpa_printf(MSG_DEBUG, "P2P: Use one of the free channels");
5549                         }
5550                 }
5551         }
5552
5553         os_free(freqs);
5554         return 0;
5555 }
5556
5557
5558 static struct wpa_supplicant *
5559 wpas_p2p_get_group_iface(struct wpa_supplicant *wpa_s, int addr_allocated,
5560                          int go)
5561 {
5562         struct wpa_supplicant *group_wpa_s;
5563
5564         if (!wpas_p2p_create_iface(wpa_s)) {
5565                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Use same interface for group "
5566                         "operations");
5567                 wpa_s->p2p_first_connection_timeout = 0;
5568                 return wpa_s;
5569         }
5570
5571         if (wpas_p2p_add_group_interface(wpa_s, go ? WPA_IF_P2P_GO :
5572                                          WPA_IF_P2P_CLIENT) < 0) {
5573                 wpa_msg_global(wpa_s, MSG_ERROR,
5574                                "P2P: Failed to add group interface");
5575                 return NULL;
5576         }
5577         group_wpa_s = wpas_p2p_init_group_interface(wpa_s, go);
5578         if (group_wpa_s == NULL) {
5579                 wpa_msg_global(wpa_s, MSG_ERROR,
5580                                "P2P: Failed to initialize group interface");
5581                 wpas_p2p_remove_pending_group_interface(wpa_s);
5582                 return NULL;
5583         }
5584
5585         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Use separate group interface %s",
5586                 group_wpa_s->ifname);
5587         group_wpa_s->p2p_first_connection_timeout = 0;
5588         return group_wpa_s;
5589 }
5590
5591
5592 /**
5593  * wpas_p2p_group_add - Add a new P2P group with local end as Group Owner
5594  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
5595  * @persistent_group: Whether to create a persistent group
5596  * @freq: Frequency for the group or 0 to indicate no hardcoding
5597  * @ht40: Start GO with 40 MHz channel width
5598  * @vht:  Start GO with VHT support
5599  * Returns: 0 on success, -1 on failure
5600  *
5601  * This function creates a new P2P group with the local end as the Group Owner,
5602  * i.e., without using Group Owner Negotiation.
5603  */
5604 int wpas_p2p_group_add(struct wpa_supplicant *wpa_s, int persistent_group,
5605                        int freq, int ht40, int vht)
5606 {
5607         struct p2p_go_neg_results params;
5608
5609         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5610                 return -1;
5611
5612         os_free(wpa_s->global->add_psk);
5613         wpa_s->global->add_psk = NULL;
5614
5615         /* Make sure we are not running find during connection establishment */
5616         wpa_printf(MSG_DEBUG, "P2P: Stop any on-going P2P FIND");
5617         wpas_p2p_stop_find_oper(wpa_s);
5618
5619         freq = wpas_p2p_select_go_freq(wpa_s, freq);
5620         if (freq < 0)
5621                 return -1;
5622
5623         if (wpas_p2p_init_go_params(wpa_s, &params, freq, ht40, vht, NULL))
5624                 return -1;
5625         if (params.freq &&
5626             !p2p_supported_freq_go(wpa_s->global->p2p, params.freq)) {
5627                 if ((wpa_s->drv_flags & WPA_DRIVER_FLAGS_DFS_OFFLOAD) &&
5628                     ieee80211_is_dfs(params.freq)) {
5629                         /*
5630                          * If freq is a DFS channel and DFS is offloaded to the
5631                          * driver, allow P2P GO to use it.
5632                          */
5633                         wpa_printf(MSG_DEBUG,
5634                                    "P2P: %s: The forced channel for GO (%u MHz) is DFS, and DFS is offloaded to driver",
5635                                 __func__, params.freq);
5636                 } else {
5637                         wpa_printf(MSG_DEBUG,
5638                                    "P2P: The selected channel for GO (%u MHz) is not supported for P2P uses",
5639                                    params.freq);
5640                         return -1;
5641                 }
5642         }
5643         p2p_go_params(wpa_s->global->p2p, &params);
5644         params.persistent_group = persistent_group;
5645
5646         wpa_s = wpas_p2p_get_group_iface(wpa_s, 0, 1);
5647         if (wpa_s == NULL)
5648                 return -1;
5649         wpas_start_wps_go(wpa_s, &params, 0);
5650
5651         return 0;
5652 }
5653
5654
5655 static int wpas_start_p2p_client(struct wpa_supplicant *wpa_s,
5656                                  struct wpa_ssid *params, int addr_allocated,
5657                                  int freq)
5658 {
5659         struct wpa_ssid *ssid;
5660
5661         wpa_s = wpas_p2p_get_group_iface(wpa_s, addr_allocated, 0);
5662         if (wpa_s == NULL)
5663                 return -1;
5664         wpa_s->p2p_last_4way_hs_fail = NULL;
5665
5666         wpa_supplicant_ap_deinit(wpa_s);
5667
5668         ssid = wpa_config_add_network(wpa_s->conf);
5669         if (ssid == NULL)
5670                 return -1;
5671         os_memset(wpa_s->go_dev_addr, 0, ETH_ALEN);
5672         wpa_config_set_network_defaults(ssid);
5673         ssid->temporary = 1;
5674         ssid->proto = WPA_PROTO_RSN;
5675         ssid->pairwise_cipher = WPA_CIPHER_CCMP;
5676         ssid->group_cipher = WPA_CIPHER_CCMP;
5677         ssid->key_mgmt = WPA_KEY_MGMT_PSK;
5678         ssid->ssid = os_malloc(params->ssid_len);
5679         if (ssid->ssid == NULL) {
5680                 wpa_config_remove_network(wpa_s->conf, ssid->id);
5681                 return -1;
5682         }
5683         os_memcpy(ssid->ssid, params->ssid, params->ssid_len);
5684         ssid->ssid_len = params->ssid_len;
5685         ssid->p2p_group = 1;
5686         ssid->export_keys = 1;
5687         if (params->psk_set) {
5688                 os_memcpy(ssid->psk, params->psk, 32);
5689                 ssid->psk_set = 1;
5690         }
5691         if (params->passphrase)
5692                 ssid->passphrase = os_strdup(params->passphrase);
5693
5694         wpa_s->show_group_started = 1;
5695         wpa_s->p2p_in_invitation = 1;
5696         wpa_s->p2p_invite_go_freq = freq;
5697
5698         eloop_cancel_timeout(wpas_p2p_group_formation_timeout, wpa_s->parent,
5699                              NULL);
5700         eloop_register_timeout(P2P_MAX_INITIAL_CONN_WAIT, 0,
5701                                wpas_p2p_group_formation_timeout,
5702                                wpa_s->parent, NULL);
5703         wpa_supplicant_select_network(wpa_s, ssid);
5704
5705         return 0;
5706 }
5707
5708
5709 int wpas_p2p_group_add_persistent(struct wpa_supplicant *wpa_s,
5710                                   struct wpa_ssid *ssid, int addr_allocated,
5711                                   int force_freq, int neg_freq, int ht40,
5712                                   int vht, const struct p2p_channels *channels,
5713                                   int connection_timeout)
5714 {
5715         struct p2p_go_neg_results params;
5716         int go = 0, freq;
5717
5718         if (ssid->disabled != 2 || ssid->ssid == NULL)
5719                 return -1;
5720
5721         if (wpas_get_p2p_group(wpa_s, ssid->ssid, ssid->ssid_len, &go) &&
5722             go == (ssid->mode == WPAS_MODE_P2P_GO)) {
5723                 wpa_printf(MSG_DEBUG, "P2P: Requested persistent group is "
5724                            "already running");
5725                 if (go == 0 &&
5726                     eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
5727                                          wpa_s->parent, NULL)) {
5728                         /*
5729                          * This can happen if Invitation Response frame was lost
5730                          * and the peer (GO of a persistent group) tries to
5731                          * invite us again. Reschedule the timeout to avoid
5732                          * terminating the wait for the connection too early
5733                          * since we now know that the peer is still trying to
5734                          * invite us instead of having already started the GO.
5735                          */
5736                         wpa_printf(MSG_DEBUG,
5737                                    "P2P: Reschedule group formation timeout since peer is still trying to invite us");
5738                         eloop_register_timeout(P2P_MAX_INITIAL_CONN_WAIT, 0,
5739                                                wpas_p2p_group_formation_timeout,
5740                                                wpa_s->parent, NULL);
5741                 }
5742                 return 0;
5743         }
5744
5745         os_free(wpa_s->global->add_psk);
5746         wpa_s->global->add_psk = NULL;
5747
5748         /* Make sure we are not running find during connection establishment */
5749         wpas_p2p_stop_find_oper(wpa_s);
5750
5751         wpa_s->p2p_fallback_to_go_neg = 0;
5752
5753         if (ssid->mode == WPAS_MODE_P2P_GO) {
5754                 if (force_freq > 0) {
5755                         freq = wpas_p2p_select_go_freq(wpa_s, force_freq);
5756                         if (freq < 0)
5757                                 return -1;
5758                 } else {
5759                         freq = wpas_p2p_select_go_freq(wpa_s, neg_freq);
5760                         if (freq < 0 ||
5761                             (freq > 0 && !freq_included(channels, freq)))
5762                                 freq = 0;
5763                 }
5764         } else if (ssid->mode == WPAS_MODE_INFRA) {
5765                 freq = neg_freq;
5766                 if (freq <= 0 || !freq_included(channels, freq)) {
5767                         struct os_reltime now;
5768                         struct wpa_bss *bss =
5769                                 wpa_bss_get_p2p_dev_addr(wpa_s, ssid->bssid);
5770
5771                         os_get_reltime(&now);
5772                         if (bss &&
5773                             !os_reltime_expired(&now, &bss->last_update, 5) &&
5774                             freq_included(channels, bss->freq))
5775                                 freq = bss->freq;
5776                         else
5777                                 freq = 0;
5778                 }
5779
5780                 return wpas_start_p2p_client(wpa_s, ssid, addr_allocated, freq);
5781         } else {
5782                 return -1;
5783         }
5784
5785         if (wpas_p2p_init_go_params(wpa_s, &params, freq, ht40, vht, channels))
5786                 return -1;
5787
5788         params.role_go = 1;
5789         params.psk_set = ssid->psk_set;
5790         if (params.psk_set)
5791                 os_memcpy(params.psk, ssid->psk, sizeof(params.psk));
5792         if (ssid->passphrase) {
5793                 if (os_strlen(ssid->passphrase) >= sizeof(params.passphrase)) {
5794                         wpa_printf(MSG_ERROR, "P2P: Invalid passphrase in "
5795                                    "persistent group");
5796                         return -1;
5797                 }
5798                 os_strlcpy(params.passphrase, ssid->passphrase,
5799                            sizeof(params.passphrase));
5800         }
5801         os_memcpy(params.ssid, ssid->ssid, ssid->ssid_len);
5802         params.ssid_len = ssid->ssid_len;
5803         params.persistent_group = 1;
5804
5805         wpa_s = wpas_p2p_get_group_iface(wpa_s, addr_allocated, 1);
5806         if (wpa_s == NULL)
5807                 return -1;
5808
5809         p2p_channels_to_freqs(channels, params.freq_list, P2P_MAX_CHANNELS);
5810
5811         wpa_s->p2p_first_connection_timeout = connection_timeout;
5812         wpas_start_wps_go(wpa_s, &params, 0);
5813
5814         return 0;
5815 }
5816
5817
5818 static void wpas_p2p_ie_update(void *ctx, struct wpabuf *beacon_ies,
5819                                struct wpabuf *proberesp_ies)
5820 {
5821         struct wpa_supplicant *wpa_s = ctx;
5822         if (wpa_s->ap_iface) {
5823                 struct hostapd_data *hapd = wpa_s->ap_iface->bss[0];
5824                 if (!(hapd->conf->p2p & P2P_GROUP_OWNER)) {
5825                         wpabuf_free(beacon_ies);
5826                         wpabuf_free(proberesp_ies);
5827                         return;
5828                 }
5829                 if (beacon_ies) {
5830                         wpabuf_free(hapd->p2p_beacon_ie);
5831                         hapd->p2p_beacon_ie = beacon_ies;
5832                 }
5833                 wpabuf_free(hapd->p2p_probe_resp_ie);
5834                 hapd->p2p_probe_resp_ie = proberesp_ies;
5835         } else {
5836                 wpabuf_free(beacon_ies);
5837                 wpabuf_free(proberesp_ies);
5838         }
5839         wpa_supplicant_ap_update_beacon(wpa_s);
5840 }
5841
5842
5843 static void wpas_p2p_idle_update(void *ctx, int idle)
5844 {
5845         struct wpa_supplicant *wpa_s = ctx;
5846         if (!wpa_s->ap_iface)
5847                 return;
5848         wpa_printf(MSG_DEBUG, "P2P: GO - group %sidle", idle ? "" : "not ");
5849         if (idle) {
5850                 if (wpa_s->global->p2p_fail_on_wps_complete &&
5851                     wpa_s->p2p_in_provisioning) {
5852                         wpas_p2p_grpform_fail_after_wps(wpa_s);
5853                         return;
5854                 }
5855                 wpas_p2p_set_group_idle_timeout(wpa_s);
5856         } else
5857                 eloop_cancel_timeout(wpas_p2p_group_idle_timeout, wpa_s, NULL);
5858 }
5859
5860
5861 struct p2p_group * wpas_p2p_group_init(struct wpa_supplicant *wpa_s,
5862                                        struct wpa_ssid *ssid)
5863 {
5864         struct p2p_group *group;
5865         struct p2p_group_config *cfg;
5866
5867         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5868                 return NULL;
5869
5870         cfg = os_zalloc(sizeof(*cfg));
5871         if (cfg == NULL)
5872                 return NULL;
5873
5874         if (ssid->p2p_persistent_group && wpa_s->conf->persistent_reconnect)
5875                 cfg->persistent_group = 2;
5876         else if (ssid->p2p_persistent_group)
5877                 cfg->persistent_group = 1;
5878         os_memcpy(cfg->interface_addr, wpa_s->own_addr, ETH_ALEN);
5879         if (wpa_s->max_stations &&
5880             wpa_s->max_stations < wpa_s->conf->max_num_sta)
5881                 cfg->max_clients = wpa_s->max_stations;
5882         else
5883                 cfg->max_clients = wpa_s->conf->max_num_sta;
5884         os_memcpy(cfg->ssid, ssid->ssid, ssid->ssid_len);
5885         cfg->ssid_len = ssid->ssid_len;
5886         cfg->freq = ssid->frequency;
5887         cfg->cb_ctx = wpa_s;
5888         cfg->ie_update = wpas_p2p_ie_update;
5889         cfg->idle_update = wpas_p2p_idle_update;
5890
5891         group = p2p_group_init(wpa_s->global->p2p, cfg);
5892         if (group == NULL)
5893                 os_free(cfg);
5894         if (ssid->mode != WPAS_MODE_P2P_GROUP_FORMATION)
5895                 p2p_group_notif_formation_done(group);
5896         wpa_s->p2p_group = group;
5897         return group;
5898 }
5899
5900
5901 void wpas_p2p_wps_success(struct wpa_supplicant *wpa_s, const u8 *peer_addr,
5902                           int registrar)
5903 {
5904         struct wpa_ssid *ssid = wpa_s->current_ssid;
5905
5906         if (!wpa_s->p2p_in_provisioning) {
5907                 wpa_printf(MSG_DEBUG, "P2P: Ignore WPS success event - P2P "
5908                            "provisioning not in progress");
5909                 return;
5910         }
5911
5912         if (ssid && ssid->mode == WPAS_MODE_INFRA) {
5913                 u8 go_dev_addr[ETH_ALEN];
5914                 os_memcpy(go_dev_addr, wpa_s->bssid, ETH_ALEN);
5915                 wpas_p2p_persistent_group(wpa_s, go_dev_addr, ssid->ssid,
5916                                           ssid->ssid_len);
5917                 /* Clear any stored provisioning info */
5918                 p2p_clear_provisioning_info(wpa_s->global->p2p, go_dev_addr);
5919         }
5920
5921         eloop_cancel_timeout(wpas_p2p_group_formation_timeout, wpa_s->parent,
5922                              NULL);
5923         wpa_s->p2p_go_group_formation_completed = 1;
5924         if (ssid && ssid->mode == WPAS_MODE_INFRA) {
5925                 /*
5926                  * Use a separate timeout for initial data connection to
5927                  * complete to allow the group to be removed automatically if
5928                  * something goes wrong in this step before the P2P group idle
5929                  * timeout mechanism is taken into use.
5930                  */
5931                 wpa_dbg(wpa_s, MSG_DEBUG,
5932                         "P2P: Re-start group formation timeout (%d seconds) as client for initial connection",
5933                         P2P_MAX_INITIAL_CONN_WAIT);
5934                 eloop_register_timeout(P2P_MAX_INITIAL_CONN_WAIT, 0,
5935                                        wpas_p2p_group_formation_timeout,
5936                                        wpa_s->parent, NULL);
5937         } else if (ssid) {
5938                 /*
5939                  * Use a separate timeout for initial data connection to
5940                  * complete to allow the group to be removed automatically if
5941                  * the client does not complete data connection successfully.
5942                  */
5943                 wpa_dbg(wpa_s, MSG_DEBUG,
5944                         "P2P: Re-start group formation timeout (%d seconds) as GO for initial connection",
5945                         P2P_MAX_INITIAL_CONN_WAIT_GO);
5946                 eloop_register_timeout(P2P_MAX_INITIAL_CONN_WAIT_GO, 0,
5947                                        wpas_p2p_group_formation_timeout,
5948                                        wpa_s->parent, NULL);
5949                 /*
5950                  * Complete group formation on first successful data connection
5951                  */
5952                 wpa_s->p2p_go_group_formation_completed = 0;
5953         }
5954         if (wpa_s->global->p2p)
5955                 p2p_wps_success_cb(wpa_s->global->p2p, peer_addr);
5956         wpas_group_formation_completed(wpa_s, 1, 0);
5957 }
5958
5959
5960 void wpas_p2p_wps_failed(struct wpa_supplicant *wpa_s,
5961                          struct wps_event_fail *fail)
5962 {
5963         if (!wpa_s->p2p_in_provisioning) {
5964                 wpa_printf(MSG_DEBUG, "P2P: Ignore WPS fail event - P2P "
5965                            "provisioning not in progress");
5966                 return;
5967         }
5968
5969         if (wpa_s->go_params) {
5970                 p2p_clear_provisioning_info(
5971                         wpa_s->global->p2p,
5972                         wpa_s->go_params->peer_device_addr);
5973         }
5974
5975         wpas_notify_p2p_wps_failed(wpa_s, fail);
5976
5977         if (wpa_s == wpa_s->global->p2p_group_formation) {
5978                 /*
5979                  * Allow some time for the failed WPS negotiation exchange to
5980                  * complete, but remove the group since group formation cannot
5981                  * succeed after provisioning failure.
5982                  */
5983                 wpa_printf(MSG_DEBUG, "P2P: WPS step failed during group formation - reject connection from timeout");
5984                 wpa_s->global->p2p_fail_on_wps_complete = 1;
5985                 eloop_deplete_timeout(0, 50000,
5986                                       wpas_p2p_group_formation_timeout,
5987                                       wpa_s->parent, NULL);
5988         }
5989 }
5990
5991
5992 int wpas_p2p_wps_eapol_cb(struct wpa_supplicant *wpa_s)
5993 {
5994         if (!wpa_s->global->p2p_fail_on_wps_complete ||
5995             !wpa_s->p2p_in_provisioning)
5996                 return 0;
5997
5998         wpas_p2p_grpform_fail_after_wps(wpa_s);
5999
6000         return 1;
6001 }
6002
6003
6004 int wpas_p2p_prov_disc(struct wpa_supplicant *wpa_s, const u8 *peer_addr,
6005                        const char *config_method,
6006                        enum wpas_p2p_prov_disc_use use,
6007                        struct p2ps_provision *p2ps_prov)
6008 {
6009         u16 config_methods;
6010
6011         wpa_s->global->pending_p2ps_group = 0;
6012         wpa_s->p2p_fallback_to_go_neg = 0;
6013         wpa_s->pending_pd_use = NORMAL_PD;
6014         if (p2ps_prov && use == WPAS_P2P_PD_FOR_ASP) {
6015                 p2ps_prov->conncap = p2ps_group_capability(
6016                         wpa_s, P2PS_SETUP_NONE, p2ps_prov->role);
6017                 wpa_printf(MSG_DEBUG,
6018                            "P2P: %s conncap: %d - ASP parsed: %x %x %d %s",
6019                            __func__, p2ps_prov->conncap,
6020                            p2ps_prov->adv_id, p2ps_prov->conncap,
6021                            p2ps_prov->status, p2ps_prov->info);
6022
6023                 config_methods = 0;
6024         } else if (os_strncmp(config_method, "display", 7) == 0)
6025                 config_methods = WPS_CONFIG_DISPLAY;
6026         else if (os_strncmp(config_method, "keypad", 6) == 0)
6027                 config_methods = WPS_CONFIG_KEYPAD;
6028         else if (os_strncmp(config_method, "pbc", 3) == 0 ||
6029                  os_strncmp(config_method, "pushbutton", 10) == 0)
6030                 config_methods = WPS_CONFIG_PUSHBUTTON;
6031         else {
6032                 wpa_printf(MSG_DEBUG, "P2P: Unknown config method");
6033                 os_free(p2ps_prov);
6034                 return -1;
6035         }
6036
6037         if (use == WPAS_P2P_PD_AUTO) {
6038                 os_memcpy(wpa_s->pending_join_dev_addr, peer_addr, ETH_ALEN);
6039                 wpa_s->pending_pd_config_methods = config_methods;
6040                 wpa_s->p2p_auto_pd = 1;
6041                 wpa_s->p2p_auto_join = 0;
6042                 wpa_s->pending_pd_before_join = 0;
6043                 wpa_s->auto_pd_scan_retry = 0;
6044                 wpas_p2p_stop_find(wpa_s);
6045                 wpa_s->p2p_join_scan_count = 0;
6046                 os_get_reltime(&wpa_s->p2p_auto_started);
6047                 wpa_printf(MSG_DEBUG, "P2P: Auto PD started at %ld.%06ld",
6048                            wpa_s->p2p_auto_started.sec,
6049                            wpa_s->p2p_auto_started.usec);
6050                 wpas_p2p_join_scan(wpa_s, NULL);
6051                 return 0;
6052         }
6053
6054         if (wpa_s->global->p2p == NULL || wpa_s->global->p2p_disabled) {
6055                 os_free(p2ps_prov);
6056                 return -1;
6057         }
6058
6059         return p2p_prov_disc_req(wpa_s->global->p2p, peer_addr, p2ps_prov,
6060                                  config_methods, use == WPAS_P2P_PD_FOR_JOIN,
6061                                  0, 1);
6062 }
6063
6064
6065 int wpas_p2p_scan_result_text(const u8 *ies, size_t ies_len, char *buf,
6066                               char *end)
6067 {
6068         return p2p_scan_result_text(ies, ies_len, buf, end);
6069 }
6070
6071
6072 static void wpas_p2p_clear_pending_action_tx(struct wpa_supplicant *wpa_s)
6073 {
6074         if (!offchannel_pending_action_tx(wpa_s))
6075                 return;
6076
6077         wpas_p2p_action_tx_clear(wpa_s);
6078
6079         wpa_printf(MSG_DEBUG, "P2P: Drop pending Action TX due to new "
6080                    "operation request");
6081         offchannel_clear_pending_action_tx(wpa_s);
6082 }
6083
6084
6085 int wpas_p2p_find(struct wpa_supplicant *wpa_s, unsigned int timeout,
6086                   enum p2p_discovery_type type,
6087                   unsigned int num_req_dev_types, const u8 *req_dev_types,
6088                   const u8 *dev_id, unsigned int search_delay,
6089                   u8 seek_cnt, const char **seek_string, int freq)
6090 {
6091         wpas_p2p_clear_pending_action_tx(wpa_s);
6092         wpa_s->p2p_long_listen = 0;
6093
6094         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL ||
6095             wpa_s->p2p_in_provisioning)
6096                 return -1;
6097
6098         wpa_supplicant_cancel_sched_scan(wpa_s);
6099
6100         return p2p_find(wpa_s->global->p2p, timeout, type,
6101                         num_req_dev_types, req_dev_types, dev_id,
6102                         search_delay, seek_cnt, seek_string, freq);
6103 }
6104
6105
6106 static void wpas_p2p_scan_res_ignore_search(struct wpa_supplicant *wpa_s,
6107                                             struct wpa_scan_results *scan_res)
6108 {
6109         wpa_printf(MSG_DEBUG, "P2P: Ignore scan results");
6110
6111         if (wpa_s->p2p_scan_work) {
6112                 struct wpa_radio_work *work = wpa_s->p2p_scan_work;
6113                 wpa_s->p2p_scan_work = NULL;
6114                 radio_work_done(work);
6115         }
6116
6117         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6118                 return;
6119
6120         /*
6121          * Indicate that results have been processed so that the P2P module can
6122          * continue pending tasks.
6123          */
6124         p2p_scan_res_handled(wpa_s->global->p2p);
6125 }
6126
6127
6128 static void wpas_p2p_stop_find_oper(struct wpa_supplicant *wpa_s)
6129 {
6130         wpas_p2p_clear_pending_action_tx(wpa_s);
6131         wpa_s->p2p_long_listen = 0;
6132         eloop_cancel_timeout(wpas_p2p_long_listen_timeout, wpa_s, NULL);
6133         eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
6134
6135         if (wpa_s->global->p2p)
6136                 p2p_stop_find(wpa_s->global->p2p);
6137
6138         if (wpa_s->scan_res_handler == wpas_p2p_scan_res_handler) {
6139                 wpa_printf(MSG_DEBUG,
6140                            "P2P: Do not consider the scan results after stop_find");
6141                 wpa_s->scan_res_handler = wpas_p2p_scan_res_ignore_search;
6142         }
6143 }
6144
6145
6146 void wpas_p2p_stop_find(struct wpa_supplicant *wpa_s)
6147 {
6148         wpas_p2p_stop_find_oper(wpa_s);
6149         if (!wpa_s->global->pending_group_iface_for_p2ps)
6150                 wpas_p2p_remove_pending_group_interface(wpa_s);
6151 }
6152
6153
6154 static void wpas_p2p_long_listen_timeout(void *eloop_ctx, void *timeout_ctx)
6155 {
6156         struct wpa_supplicant *wpa_s = eloop_ctx;
6157         wpa_s->p2p_long_listen = 0;
6158 }
6159
6160
6161 int wpas_p2p_listen(struct wpa_supplicant *wpa_s, unsigned int timeout)
6162 {
6163         int res;
6164
6165         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6166                 return -1;
6167
6168         wpa_supplicant_cancel_sched_scan(wpa_s);
6169         wpas_p2p_clear_pending_action_tx(wpa_s);
6170
6171         if (timeout == 0) {
6172                 /*
6173                  * This is a request for unlimited Listen state. However, at
6174                  * least for now, this is mapped to a Listen state for one
6175                  * hour.
6176                  */
6177                 timeout = 3600;
6178         }
6179         eloop_cancel_timeout(wpas_p2p_long_listen_timeout, wpa_s, NULL);
6180         wpa_s->p2p_long_listen = 0;
6181
6182         /*
6183          * Stop previous find/listen operation to avoid trying to request a new
6184          * remain-on-channel operation while the driver is still running the
6185          * previous one.
6186          */
6187         if (wpa_s->global->p2p)
6188                 p2p_stop_find(wpa_s->global->p2p);
6189
6190         res = wpas_p2p_listen_start(wpa_s, timeout * 1000);
6191         if (res == 0 && timeout * 1000 > wpa_s->max_remain_on_chan) {
6192                 wpa_s->p2p_long_listen = timeout * 1000;
6193                 eloop_register_timeout(timeout, 0,
6194                                        wpas_p2p_long_listen_timeout,
6195                                        wpa_s, NULL);
6196         }
6197
6198         return res;
6199 }
6200
6201
6202 int wpas_p2p_assoc_req_ie(struct wpa_supplicant *wpa_s, struct wpa_bss *bss,
6203                           u8 *buf, size_t len, int p2p_group)
6204 {
6205         struct wpabuf *p2p_ie;
6206         int ret;
6207
6208         if (wpa_s->global->p2p_disabled)
6209                 return -1;
6210         /*
6211          * Advertize mandatory cross connection capability even on
6212          * p2p_disabled=1 interface when associating with a P2P Manager WLAN AP.
6213          */
6214         if (wpa_s->conf->p2p_disabled && p2p_group)
6215                 return -1;
6216         if (wpa_s->global->p2p == NULL)
6217                 return -1;
6218         if (bss == NULL)
6219                 return -1;
6220
6221         p2p_ie = wpa_bss_get_vendor_ie_multi(bss, P2P_IE_VENDOR_TYPE);
6222         ret = p2p_assoc_req_ie(wpa_s->global->p2p, bss->bssid, buf, len,
6223                                p2p_group, p2p_ie);
6224         wpabuf_free(p2p_ie);
6225
6226         return ret;
6227 }
6228
6229
6230 int wpas_p2p_probe_req_rx(struct wpa_supplicant *wpa_s, const u8 *addr,
6231                           const u8 *dst, const u8 *bssid,
6232                           const u8 *ie, size_t ie_len,
6233                           unsigned int rx_freq, int ssi_signal)
6234 {
6235         if (wpa_s->global->p2p_disabled)
6236                 return 0;
6237         if (wpa_s->global->p2p == NULL)
6238                 return 0;
6239
6240         switch (p2p_probe_req_rx(wpa_s->global->p2p, addr, dst, bssid,
6241                                  ie, ie_len, rx_freq)) {
6242         case P2P_PREQ_NOT_P2P:
6243                 wpas_notify_preq(wpa_s, addr, dst, bssid, ie, ie_len,
6244                                  ssi_signal);
6245                 /* fall through */
6246         case P2P_PREQ_MALFORMED:
6247         case P2P_PREQ_NOT_LISTEN:
6248         case P2P_PREQ_NOT_PROCESSED:
6249         default: /* make gcc happy */
6250                 return 0;
6251         case P2P_PREQ_PROCESSED:
6252                 return 1;
6253         }
6254 }
6255
6256
6257 void wpas_p2p_rx_action(struct wpa_supplicant *wpa_s, const u8 *da,
6258                         const u8 *sa, const u8 *bssid,
6259                         u8 category, const u8 *data, size_t len, int freq)
6260 {
6261         if (wpa_s->global->p2p_disabled)
6262                 return;
6263         if (wpa_s->global->p2p == NULL)
6264                 return;
6265
6266         p2p_rx_action(wpa_s->global->p2p, da, sa, bssid, category, data, len,
6267                       freq);
6268 }
6269
6270
6271 void wpas_p2p_scan_ie(struct wpa_supplicant *wpa_s, struct wpabuf *ies)
6272 {
6273         if (wpa_s->global->p2p_disabled)
6274                 return;
6275         if (wpa_s->global->p2p == NULL)
6276                 return;
6277
6278         p2p_scan_ie(wpa_s->global->p2p, ies, NULL);
6279 }
6280
6281
6282 static void wpas_p2p_group_deinit(struct wpa_supplicant *wpa_s)
6283 {
6284         p2p_group_deinit(wpa_s->p2p_group);
6285         wpa_s->p2p_group = NULL;
6286
6287         wpa_s->ap_configured_cb = NULL;
6288         wpa_s->ap_configured_cb_ctx = NULL;
6289         wpa_s->ap_configured_cb_data = NULL;
6290         wpa_s->connect_without_scan = NULL;
6291 }
6292
6293
6294 int wpas_p2p_reject(struct wpa_supplicant *wpa_s, const u8 *addr)
6295 {
6296         wpa_s->p2p_long_listen = 0;
6297
6298         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6299                 return -1;
6300
6301         return p2p_reject(wpa_s->global->p2p, addr);
6302 }
6303
6304
6305 /* Invite to reinvoke a persistent group */
6306 int wpas_p2p_invite(struct wpa_supplicant *wpa_s, const u8 *peer_addr,
6307                     struct wpa_ssid *ssid, const u8 *go_dev_addr, int freq,
6308                     int ht40, int vht, int pref_freq)
6309 {
6310         enum p2p_invite_role role;
6311         u8 *bssid = NULL;
6312         int force_freq = 0;
6313         int res;
6314         int no_pref_freq_given = pref_freq == 0;
6315         unsigned int pref_freq_list[P2P_MAX_PREF_CHANNELS], size;
6316
6317         wpa_s->global->p2p_invite_group = NULL;
6318         if (peer_addr)
6319                 os_memcpy(wpa_s->p2p_auth_invite, peer_addr, ETH_ALEN);
6320         else
6321                 os_memset(wpa_s->p2p_auth_invite, 0, ETH_ALEN);
6322
6323         wpa_s->p2p_persistent_go_freq = freq;
6324         wpa_s->p2p_go_ht40 = !!ht40;
6325         if (ssid->mode == WPAS_MODE_P2P_GO) {
6326                 role = P2P_INVITE_ROLE_GO;
6327                 if (peer_addr == NULL) {
6328                         wpa_printf(MSG_DEBUG, "P2P: Missing peer "
6329                                    "address in invitation command");
6330                         return -1;
6331                 }
6332                 if (wpas_p2p_create_iface(wpa_s)) {
6333                         if (wpas_p2p_add_group_interface(wpa_s,
6334                                                          WPA_IF_P2P_GO) < 0) {
6335                                 wpa_printf(MSG_ERROR, "P2P: Failed to "
6336                                            "allocate a new interface for the "
6337                                            "group");
6338                                 return -1;
6339                         }
6340                         bssid = wpa_s->pending_interface_addr;
6341                 } else
6342                         bssid = wpa_s->own_addr;
6343         } else {
6344                 role = P2P_INVITE_ROLE_CLIENT;
6345                 peer_addr = ssid->bssid;
6346         }
6347         wpa_s->pending_invite_ssid_id = ssid->id;
6348
6349         size = P2P_MAX_PREF_CHANNELS;
6350         res = wpas_p2p_setup_freqs(wpa_s, freq, &force_freq, &pref_freq,
6351                                    role == P2P_INVITE_ROLE_GO,
6352                                    pref_freq_list, &size);
6353         if (res)
6354                 return res;
6355
6356         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6357                 return -1;
6358
6359         if (wpa_s->parent->conf->p2p_ignore_shared_freq &&
6360             no_pref_freq_given && pref_freq > 0 &&
6361             wpa_s->num_multichan_concurrent > 1 &&
6362             wpas_p2p_num_unused_channels(wpa_s) > 0) {
6363                 wpa_printf(MSG_DEBUG, "P2P: Ignore own channel preference %d MHz for invitation due to p2p_ignore_shared_freq=1 configuration",
6364                            pref_freq);
6365                 pref_freq = 0;
6366         }
6367
6368         /*
6369          * Stop any find/listen operations before invitation and possibly
6370          * connection establishment.
6371          */
6372         wpas_p2p_stop_find_oper(wpa_s);
6373
6374         return p2p_invite(wpa_s->global->p2p, peer_addr, role, bssid,
6375                           ssid->ssid, ssid->ssid_len, force_freq, go_dev_addr,
6376                           1, pref_freq, -1);
6377 }
6378
6379
6380 /* Invite to join an active group */
6381 int wpas_p2p_invite_group(struct wpa_supplicant *wpa_s, const char *ifname,
6382                           const u8 *peer_addr, const u8 *go_dev_addr)
6383 {
6384         struct wpa_global *global = wpa_s->global;
6385         enum p2p_invite_role role;
6386         u8 *bssid = NULL;
6387         struct wpa_ssid *ssid;
6388         int persistent;
6389         int freq = 0, force_freq = 0, pref_freq = 0;
6390         int res;
6391         unsigned int pref_freq_list[P2P_MAX_PREF_CHANNELS], size;
6392
6393         wpa_s->p2p_persistent_go_freq = 0;
6394         wpa_s->p2p_go_ht40 = 0;
6395         wpa_s->p2p_go_vht = 0;
6396
6397         for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) {
6398                 if (os_strcmp(wpa_s->ifname, ifname) == 0)
6399                         break;
6400         }
6401         if (wpa_s == NULL) {
6402                 wpa_printf(MSG_DEBUG, "P2P: Interface '%s' not found", ifname);
6403                 return -1;
6404         }
6405
6406         ssid = wpa_s->current_ssid;
6407         if (ssid == NULL) {
6408                 wpa_printf(MSG_DEBUG, "P2P: No current SSID to use for "
6409                            "invitation");
6410                 return -1;
6411         }
6412
6413         wpa_s->global->p2p_invite_group = wpa_s;
6414         persistent = ssid->p2p_persistent_group &&
6415                 wpas_p2p_get_persistent(wpa_s->parent, peer_addr,
6416                                         ssid->ssid, ssid->ssid_len);
6417
6418         if (ssid->mode == WPAS_MODE_P2P_GO) {
6419                 role = P2P_INVITE_ROLE_ACTIVE_GO;
6420                 bssid = wpa_s->own_addr;
6421                 if (go_dev_addr == NULL)
6422                         go_dev_addr = wpa_s->global->p2p_dev_addr;
6423                 freq = ssid->frequency;
6424         } else {
6425                 role = P2P_INVITE_ROLE_CLIENT;
6426                 if (wpa_s->wpa_state < WPA_ASSOCIATED) {
6427                         wpa_printf(MSG_DEBUG, "P2P: Not associated - cannot "
6428                                    "invite to current group");
6429                         return -1;
6430                 }
6431                 bssid = wpa_s->bssid;
6432                 if (go_dev_addr == NULL &&
6433                     !is_zero_ether_addr(wpa_s->go_dev_addr))
6434                         go_dev_addr = wpa_s->go_dev_addr;
6435                 freq = wpa_s->current_bss ? wpa_s->current_bss->freq :
6436                         (int) wpa_s->assoc_freq;
6437         }
6438         wpa_s->parent->pending_invite_ssid_id = -1;
6439
6440         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6441                 return -1;
6442
6443         size = P2P_MAX_PREF_CHANNELS;
6444         res = wpas_p2p_setup_freqs(wpa_s, freq, &force_freq, &pref_freq,
6445                                    role == P2P_INVITE_ROLE_ACTIVE_GO,
6446                                    pref_freq_list, &size);
6447         if (res)
6448                 return res;
6449         wpas_p2p_set_own_freq_preference(wpa_s, force_freq);
6450
6451         return p2p_invite(wpa_s->global->p2p, peer_addr, role, bssid,
6452                           ssid->ssid, ssid->ssid_len, force_freq,
6453                           go_dev_addr, persistent, pref_freq, -1);
6454 }
6455
6456
6457 void wpas_p2p_completed(struct wpa_supplicant *wpa_s)
6458 {
6459         struct wpa_ssid *ssid = wpa_s->current_ssid;
6460         u8 go_dev_addr[ETH_ALEN];
6461         int network_id = -1;
6462         int persistent;
6463         int freq;
6464         u8 ip[3 * 4];
6465         char ip_addr[100];
6466
6467         if (ssid == NULL || ssid->mode != WPAS_MODE_P2P_GROUP_FORMATION) {
6468                 eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
6469                                      wpa_s->parent, NULL);
6470         }
6471
6472         if (!wpa_s->show_group_started || !ssid)
6473                 return;
6474
6475         wpa_s->show_group_started = 0;
6476
6477         os_memset(go_dev_addr, 0, ETH_ALEN);
6478         if (ssid->bssid_set)
6479                 os_memcpy(go_dev_addr, ssid->bssid, ETH_ALEN);
6480         persistent = wpas_p2p_persistent_group(wpa_s, go_dev_addr, ssid->ssid,
6481                                                ssid->ssid_len);
6482         os_memcpy(wpa_s->go_dev_addr, go_dev_addr, ETH_ALEN);
6483
6484         if (wpa_s->global->p2p_group_formation == wpa_s)
6485                 wpa_s->global->p2p_group_formation = NULL;
6486
6487         freq = wpa_s->current_bss ? wpa_s->current_bss->freq :
6488                 (int) wpa_s->assoc_freq;
6489
6490         ip_addr[0] = '\0';
6491         if (wpa_sm_get_p2p_ip_addr(wpa_s->wpa, ip) == 0) {
6492                 int res;
6493
6494                 res = os_snprintf(ip_addr, sizeof(ip_addr),
6495                                   " ip_addr=%u.%u.%u.%u "
6496                                   "ip_mask=%u.%u.%u.%u go_ip_addr=%u.%u.%u.%u",
6497                                   ip[0], ip[1], ip[2], ip[3],
6498                                   ip[4], ip[5], ip[6], ip[7],
6499                                   ip[8], ip[9], ip[10], ip[11]);
6500                 if (os_snprintf_error(sizeof(ip_addr), res))
6501                         ip_addr[0] = '\0';
6502         }
6503
6504         wpas_p2p_group_started(wpa_s, 0, ssid, freq,
6505                                ssid->passphrase == NULL && ssid->psk_set ?
6506                                ssid->psk : NULL,
6507                                ssid->passphrase, go_dev_addr, persistent,
6508                                ip_addr);
6509
6510         if (persistent)
6511                 network_id = wpas_p2p_store_persistent_group(wpa_s->parent,
6512                                                              ssid, go_dev_addr);
6513         if (network_id < 0)
6514                 network_id = ssid->id;
6515         wpas_notify_p2p_group_started(wpa_s, ssid, network_id, 1);
6516 }
6517
6518
6519 int wpas_p2p_presence_req(struct wpa_supplicant *wpa_s, u32 duration1,
6520                           u32 interval1, u32 duration2, u32 interval2)
6521 {
6522         int ret;
6523
6524         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6525                 return -1;
6526
6527         if (wpa_s->wpa_state < WPA_ASSOCIATED ||
6528             wpa_s->current_ssid == NULL ||
6529             wpa_s->current_ssid->mode != WPAS_MODE_INFRA)
6530                 return -1;
6531
6532         ret = p2p_presence_req(wpa_s->global->p2p, wpa_s->bssid,
6533                                wpa_s->own_addr, wpa_s->assoc_freq,
6534                                duration1, interval1, duration2, interval2);
6535         if (ret == 0)
6536                 wpa_s->waiting_presence_resp = 1;
6537
6538         return ret;
6539 }
6540
6541
6542 int wpas_p2p_ext_listen(struct wpa_supplicant *wpa_s, unsigned int period,
6543                         unsigned int interval)
6544 {
6545         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6546                 return -1;
6547
6548         return p2p_ext_listen(wpa_s->global->p2p, period, interval);
6549 }
6550
6551
6552 static int wpas_p2p_is_client(struct wpa_supplicant *wpa_s)
6553 {
6554         if (wpa_s->current_ssid == NULL) {
6555                 /*
6556                  * current_ssid can be cleared when P2P client interface gets
6557                  * disconnected, so assume this interface was used as P2P
6558                  * client.
6559                  */
6560                 return 1;
6561         }
6562         return wpa_s->current_ssid->p2p_group &&
6563                 wpa_s->current_ssid->mode == WPAS_MODE_INFRA;
6564 }
6565
6566
6567 static void wpas_p2p_group_idle_timeout(void *eloop_ctx, void *timeout_ctx)
6568 {
6569         struct wpa_supplicant *wpa_s = eloop_ctx;
6570
6571         if (wpa_s->conf->p2p_group_idle == 0 && !wpas_p2p_is_client(wpa_s)) {
6572                 wpa_printf(MSG_DEBUG, "P2P: Ignore group idle timeout - "
6573                            "disabled");
6574                 return;
6575         }
6576
6577         wpa_printf(MSG_DEBUG, "P2P: Group idle timeout reached - terminate "
6578                    "group");
6579         wpas_p2p_group_delete(wpa_s, P2P_GROUP_REMOVAL_IDLE_TIMEOUT);
6580 }
6581
6582
6583 static void wpas_p2p_set_group_idle_timeout(struct wpa_supplicant *wpa_s)
6584 {
6585         int timeout;
6586
6587         if (eloop_cancel_timeout(wpas_p2p_group_idle_timeout, wpa_s, NULL) > 0)
6588                 wpa_printf(MSG_DEBUG, "P2P: Cancelled P2P group idle timeout");
6589
6590         if (wpa_s->current_ssid == NULL || !wpa_s->current_ssid->p2p_group)
6591                 return;
6592
6593         timeout = wpa_s->conf->p2p_group_idle;
6594         if (wpa_s->current_ssid->mode == WPAS_MODE_INFRA &&
6595             (timeout == 0 || timeout > P2P_MAX_CLIENT_IDLE))
6596             timeout = P2P_MAX_CLIENT_IDLE;
6597
6598         if (timeout == 0)
6599                 return;
6600
6601         if (timeout < 0) {
6602                 if (wpa_s->current_ssid->mode == WPAS_MODE_INFRA)
6603                         timeout = 0; /* special client mode no-timeout */
6604                 else
6605                         return;
6606         }
6607
6608         if (wpa_s->p2p_in_provisioning) {
6609                 /*
6610                  * Use the normal group formation timeout during the
6611                  * provisioning phase to avoid terminating this process too
6612                  * early due to group idle timeout.
6613                  */
6614                 wpa_printf(MSG_DEBUG, "P2P: Do not use P2P group idle timeout "
6615                            "during provisioning");
6616                 return;
6617         }
6618
6619         if (wpa_s->show_group_started) {
6620                 /*
6621                  * Use the normal group formation timeout between the end of
6622                  * the provisioning phase and completion of 4-way handshake to
6623                  * avoid terminating this process too early due to group idle
6624                  * timeout.
6625                  */
6626                 wpa_printf(MSG_DEBUG, "P2P: Do not use P2P group idle timeout "
6627                            "while waiting for initial 4-way handshake to "
6628                            "complete");
6629                 return;
6630         }
6631
6632         wpa_printf(MSG_DEBUG, "P2P: Set P2P group idle timeout to %u seconds",
6633                    timeout);
6634         eloop_register_timeout(timeout, 0, wpas_p2p_group_idle_timeout,
6635                                wpa_s, NULL);
6636 }
6637
6638
6639 /* Returns 1 if the interface was removed */
6640 int wpas_p2p_deauth_notif(struct wpa_supplicant *wpa_s, const u8 *bssid,
6641                           u16 reason_code, const u8 *ie, size_t ie_len,
6642                           int locally_generated)
6643 {
6644         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6645                 return 0;
6646
6647         if (!locally_generated)
6648                 p2p_deauth_notif(wpa_s->global->p2p, bssid, reason_code, ie,
6649                                  ie_len);
6650
6651         if (reason_code == WLAN_REASON_DEAUTH_LEAVING && !locally_generated &&
6652             wpa_s->current_ssid &&
6653             wpa_s->current_ssid->p2p_group &&
6654             wpa_s->current_ssid->mode == WPAS_MODE_INFRA) {
6655                 wpa_printf(MSG_DEBUG, "P2P: GO indicated that the P2P Group "
6656                            "session is ending");
6657                 if (wpas_p2p_group_delete(wpa_s,
6658                                           P2P_GROUP_REMOVAL_GO_ENDING_SESSION)
6659                     > 0)
6660                         return 1;
6661         }
6662
6663         return 0;
6664 }
6665
6666
6667 void wpas_p2p_disassoc_notif(struct wpa_supplicant *wpa_s, const u8 *bssid,
6668                              u16 reason_code, const u8 *ie, size_t ie_len,
6669                              int locally_generated)
6670 {
6671         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6672                 return;
6673
6674         if (!locally_generated)
6675                 p2p_disassoc_notif(wpa_s->global->p2p, bssid, reason_code, ie,
6676                                    ie_len);
6677 }
6678
6679
6680 void wpas_p2p_update_config(struct wpa_supplicant *wpa_s)
6681 {
6682         struct p2p_data *p2p = wpa_s->global->p2p;
6683
6684         if (p2p == NULL)
6685                 return;
6686
6687         if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_CAPABLE))
6688                 return;
6689
6690         if (wpa_s->conf->changed_parameters & CFG_CHANGED_DEVICE_NAME)
6691                 p2p_set_dev_name(p2p, wpa_s->conf->device_name);
6692
6693         if (wpa_s->conf->changed_parameters & CFG_CHANGED_DEVICE_TYPE)
6694                 p2p_set_pri_dev_type(p2p, wpa_s->conf->device_type);
6695
6696         if (wpa_s->wps &&
6697             (wpa_s->conf->changed_parameters & CFG_CHANGED_CONFIG_METHODS))
6698                 p2p_set_config_methods(p2p, wpa_s->wps->config_methods);
6699
6700         if (wpa_s->wps && (wpa_s->conf->changed_parameters & CFG_CHANGED_UUID))
6701                 p2p_set_uuid(p2p, wpa_s->wps->uuid);
6702
6703         if (wpa_s->conf->changed_parameters & CFG_CHANGED_WPS_STRING) {
6704                 p2p_set_manufacturer(p2p, wpa_s->conf->manufacturer);
6705                 p2p_set_model_name(p2p, wpa_s->conf->model_name);
6706                 p2p_set_model_number(p2p, wpa_s->conf->model_number);
6707                 p2p_set_serial_number(p2p, wpa_s->conf->serial_number);
6708         }
6709
6710         if (wpa_s->conf->changed_parameters & CFG_CHANGED_SEC_DEVICE_TYPE)
6711                 p2p_set_sec_dev_types(p2p,
6712                                       (void *) wpa_s->conf->sec_device_type,
6713                                       wpa_s->conf->num_sec_device_types);
6714
6715         if (wpa_s->conf->changed_parameters & CFG_CHANGED_VENDOR_EXTENSION) {
6716                 int i;
6717                 p2p_remove_wps_vendor_extensions(p2p);
6718                 for (i = 0; i < MAX_WPS_VENDOR_EXT; i++) {
6719                         if (wpa_s->conf->wps_vendor_ext[i] == NULL)
6720                                 continue;
6721                         p2p_add_wps_vendor_extension(
6722                                 p2p, wpa_s->conf->wps_vendor_ext[i]);
6723                 }
6724         }
6725
6726         if ((wpa_s->conf->changed_parameters & CFG_CHANGED_COUNTRY) &&
6727             wpa_s->conf->country[0] && wpa_s->conf->country[1]) {
6728                 char country[3];
6729                 country[0] = wpa_s->conf->country[0];
6730                 country[1] = wpa_s->conf->country[1];
6731                 country[2] = 0x04;
6732                 p2p_set_country(p2p, country);
6733         }
6734
6735         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_SSID_POSTFIX) {
6736                 p2p_set_ssid_postfix(p2p, (u8 *) wpa_s->conf->p2p_ssid_postfix,
6737                                      wpa_s->conf->p2p_ssid_postfix ?
6738                                      os_strlen(wpa_s->conf->p2p_ssid_postfix) :
6739                                      0);
6740         }
6741
6742         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_INTRA_BSS)
6743                 p2p_set_intra_bss_dist(p2p, wpa_s->conf->p2p_intra_bss);
6744
6745         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_LISTEN_CHANNEL) {
6746                 u8 reg_class, channel;
6747                 int ret;
6748                 unsigned int r;
6749                 u8 channel_forced;
6750
6751                 if (wpa_s->conf->p2p_listen_reg_class &&
6752                     wpa_s->conf->p2p_listen_channel) {
6753                         reg_class = wpa_s->conf->p2p_listen_reg_class;
6754                         channel = wpa_s->conf->p2p_listen_channel;
6755                         channel_forced = 1;
6756                 } else {
6757                         reg_class = 81;
6758                         /*
6759                          * Pick one of the social channels randomly as the
6760                          * listen channel.
6761                          */
6762                         if (os_get_random((u8 *) &r, sizeof(r)) < 0)
6763                                 channel = 1;
6764                         else
6765                                 channel = 1 + (r % 3) * 5;
6766                         channel_forced = 0;
6767                 }
6768                 ret = p2p_set_listen_channel(p2p, reg_class, channel,
6769                                              channel_forced);
6770                 if (ret)
6771                         wpa_printf(MSG_ERROR, "P2P: Own listen channel update "
6772                                    "failed: %d", ret);
6773         }
6774         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_OPER_CHANNEL) {
6775                 u8 op_reg_class, op_channel, cfg_op_channel;
6776                 int ret = 0;
6777                 unsigned int r;
6778                 if (wpa_s->conf->p2p_oper_reg_class &&
6779                     wpa_s->conf->p2p_oper_channel) {
6780                         op_reg_class = wpa_s->conf->p2p_oper_reg_class;
6781                         op_channel = wpa_s->conf->p2p_oper_channel;
6782                         cfg_op_channel = 1;
6783                 } else {
6784                         op_reg_class = 81;
6785                         /*
6786                          * Use random operation channel from (1, 6, 11)
6787                          *if no other preference is indicated.
6788                          */
6789                         if (os_get_random((u8 *) &r, sizeof(r)) < 0)
6790                                 op_channel = 1;
6791                         else
6792                                 op_channel = 1 + (r % 3) * 5;
6793                         cfg_op_channel = 0;
6794                 }
6795                 ret = p2p_set_oper_channel(p2p, op_reg_class, op_channel,
6796                                            cfg_op_channel);
6797                 if (ret)
6798                         wpa_printf(MSG_ERROR, "P2P: Own oper channel update "
6799                                    "failed: %d", ret);
6800         }
6801
6802         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_PREF_CHAN) {
6803                 if (p2p_set_pref_chan(p2p, wpa_s->conf->num_p2p_pref_chan,
6804                                       wpa_s->conf->p2p_pref_chan) < 0) {
6805                         wpa_printf(MSG_ERROR, "P2P: Preferred channel list "
6806                                    "update failed");
6807                 }
6808
6809                 if (p2p_set_no_go_freq(p2p, &wpa_s->conf->p2p_no_go_freq) < 0) {
6810                         wpa_printf(MSG_ERROR, "P2P: No GO channel list "
6811                                    "update failed");
6812                 }
6813         }
6814
6815         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_PASSPHRASE_LEN)
6816                 p2p_set_passphrase_len(p2p, wpa_s->conf->p2p_passphrase_len);
6817 }
6818
6819
6820 int wpas_p2p_set_noa(struct wpa_supplicant *wpa_s, u8 count, int start,
6821                      int duration)
6822 {
6823         if (!wpa_s->ap_iface)
6824                 return -1;
6825         return hostapd_p2p_set_noa(wpa_s->ap_iface->bss[0], count, start,
6826                                    duration);
6827 }
6828
6829
6830 int wpas_p2p_set_cross_connect(struct wpa_supplicant *wpa_s, int enabled)
6831 {
6832         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6833                 return -1;
6834
6835         wpa_s->global->cross_connection = enabled;
6836         p2p_set_cross_connect(wpa_s->global->p2p, enabled);
6837
6838         if (!enabled) {
6839                 struct wpa_supplicant *iface;
6840
6841                 for (iface = wpa_s->global->ifaces; iface; iface = iface->next)
6842                 {
6843                         if (iface->cross_connect_enabled == 0)
6844                                 continue;
6845
6846                         iface->cross_connect_enabled = 0;
6847                         iface->cross_connect_in_use = 0;
6848                         wpa_msg_global(iface->parent, MSG_INFO,
6849                                        P2P_EVENT_CROSS_CONNECT_DISABLE "%s %s",
6850                                        iface->ifname,
6851                                        iface->cross_connect_uplink);
6852                 }
6853         }
6854
6855         return 0;
6856 }
6857
6858
6859 static void wpas_p2p_enable_cross_connect(struct wpa_supplicant *uplink)
6860 {
6861         struct wpa_supplicant *iface;
6862
6863         if (!uplink->global->cross_connection)
6864                 return;
6865
6866         for (iface = uplink->global->ifaces; iface; iface = iface->next) {
6867                 if (!iface->cross_connect_enabled)
6868                         continue;
6869                 if (os_strcmp(uplink->ifname, iface->cross_connect_uplink) !=
6870                     0)
6871                         continue;
6872                 if (iface->ap_iface == NULL)
6873                         continue;
6874                 if (iface->cross_connect_in_use)
6875                         continue;
6876
6877                 iface->cross_connect_in_use = 1;
6878                 wpa_msg_global(iface->parent, MSG_INFO,
6879                                P2P_EVENT_CROSS_CONNECT_ENABLE "%s %s",
6880                                iface->ifname, iface->cross_connect_uplink);
6881         }
6882 }
6883
6884
6885 static void wpas_p2p_disable_cross_connect(struct wpa_supplicant *uplink)
6886 {
6887         struct wpa_supplicant *iface;
6888
6889         for (iface = uplink->global->ifaces; iface; iface = iface->next) {
6890                 if (!iface->cross_connect_enabled)
6891                         continue;
6892                 if (os_strcmp(uplink->ifname, iface->cross_connect_uplink) !=
6893                     0)
6894                         continue;
6895                 if (!iface->cross_connect_in_use)
6896                         continue;
6897
6898                 wpa_msg_global(iface->parent, MSG_INFO,
6899                                P2P_EVENT_CROSS_CONNECT_DISABLE "%s %s",
6900                                iface->ifname, iface->cross_connect_uplink);
6901                 iface->cross_connect_in_use = 0;
6902         }
6903 }
6904
6905
6906 void wpas_p2p_notif_connected(struct wpa_supplicant *wpa_s)
6907 {
6908         if (wpa_s->ap_iface || wpa_s->current_ssid == NULL ||
6909             wpa_s->current_ssid->mode != WPAS_MODE_INFRA ||
6910             wpa_s->cross_connect_disallowed)
6911                 wpas_p2p_disable_cross_connect(wpa_s);
6912         else
6913                 wpas_p2p_enable_cross_connect(wpa_s);
6914         if (!wpa_s->ap_iface &&
6915             eloop_cancel_timeout(wpas_p2p_group_idle_timeout, wpa_s, NULL) > 0)
6916                 wpa_printf(MSG_DEBUG, "P2P: Cancelled P2P group idle timeout");
6917 }
6918
6919
6920 void wpas_p2p_notif_disconnected(struct wpa_supplicant *wpa_s)
6921 {
6922         wpas_p2p_disable_cross_connect(wpa_s);
6923         if (!wpa_s->ap_iface &&
6924             !eloop_is_timeout_registered(wpas_p2p_group_idle_timeout,
6925                                          wpa_s, NULL))
6926                 wpas_p2p_set_group_idle_timeout(wpa_s);
6927 }
6928
6929
6930 static void wpas_p2p_cross_connect_setup(struct wpa_supplicant *wpa_s)
6931 {
6932         struct wpa_supplicant *iface;
6933
6934         if (!wpa_s->global->cross_connection)
6935                 return;
6936
6937         for (iface = wpa_s->global->ifaces; iface; iface = iface->next) {
6938                 if (iface == wpa_s)
6939                         continue;
6940                 if (iface->drv_flags &
6941                     WPA_DRIVER_FLAGS_P2P_DEDICATED_INTERFACE)
6942                         continue;
6943                 if ((iface->drv_flags & WPA_DRIVER_FLAGS_P2P_CAPABLE) &&
6944                     iface != wpa_s->parent)
6945                         continue;
6946
6947                 wpa_s->cross_connect_enabled = 1;
6948                 os_strlcpy(wpa_s->cross_connect_uplink, iface->ifname,
6949                            sizeof(wpa_s->cross_connect_uplink));
6950                 wpa_printf(MSG_DEBUG, "P2P: Enable cross connection from "
6951                            "%s to %s whenever uplink is available",
6952                            wpa_s->ifname, wpa_s->cross_connect_uplink);
6953
6954                 if (iface->ap_iface || iface->current_ssid == NULL ||
6955                     iface->current_ssid->mode != WPAS_MODE_INFRA ||
6956                     iface->cross_connect_disallowed ||
6957                     iface->wpa_state != WPA_COMPLETED)
6958                         break;
6959
6960                 wpa_s->cross_connect_in_use = 1;
6961                 wpa_msg_global(wpa_s->parent, MSG_INFO,
6962                                P2P_EVENT_CROSS_CONNECT_ENABLE "%s %s",
6963                                wpa_s->ifname, wpa_s->cross_connect_uplink);
6964                 break;
6965         }
6966 }
6967
6968
6969 int wpas_p2p_notif_pbc_overlap(struct wpa_supplicant *wpa_s)
6970 {
6971         if (wpa_s->p2p_group_interface != P2P_GROUP_INTERFACE_CLIENT &&
6972             !wpa_s->p2p_in_provisioning)
6973                 return 0; /* not P2P client operation */
6974
6975         wpa_printf(MSG_DEBUG, "P2P: Terminate connection due to WPS PBC "
6976                    "session overlap");
6977         if (wpa_s != wpa_s->parent)
6978                 wpa_msg_ctrl(wpa_s->parent, MSG_INFO, WPS_EVENT_OVERLAP);
6979         wpas_p2p_group_formation_failed(wpa_s, 0);
6980         return 1;
6981 }
6982
6983
6984 void wpas_p2p_pbc_overlap_cb(void *eloop_ctx, void *timeout_ctx)
6985 {
6986         struct wpa_supplicant *wpa_s = eloop_ctx;
6987         wpas_p2p_notif_pbc_overlap(wpa_s);
6988 }
6989
6990
6991 void wpas_p2p_update_channel_list(struct wpa_supplicant *wpa_s)
6992 {
6993         struct p2p_channels chan, cli_chan;
6994         struct wpa_supplicant *ifs;
6995
6996         if (wpa_s->global == NULL || wpa_s->global->p2p == NULL)
6997                 return;
6998
6999         os_memset(&chan, 0, sizeof(chan));
7000         os_memset(&cli_chan, 0, sizeof(cli_chan));
7001         if (wpas_p2p_setup_channels(wpa_s, &chan, &cli_chan)) {
7002                 wpa_printf(MSG_ERROR, "P2P: Failed to update supported "
7003                            "channel list");
7004                 return;
7005         }
7006
7007         p2p_update_channel_list(wpa_s->global->p2p, &chan, &cli_chan);
7008
7009         for (ifs = wpa_s->global->ifaces; ifs; ifs = ifs->next) {
7010                 int freq;
7011                 if (!ifs->current_ssid ||
7012                     !ifs->current_ssid->p2p_group ||
7013                     (ifs->current_ssid->mode != WPAS_MODE_P2P_GO &&
7014                      ifs->current_ssid->mode != WPAS_MODE_P2P_GROUP_FORMATION))
7015                                 continue;
7016                 freq = ifs->current_ssid->frequency;
7017                 if (freq_included(&chan, freq)) {
7018                         wpa_dbg(ifs, MSG_DEBUG,
7019                                 "P2P GO operating frequency %d MHz in valid range",
7020                                 freq);
7021                         continue;
7022                 }
7023
7024                 wpa_dbg(ifs, MSG_DEBUG,
7025                         "P2P GO operating in invalid frequency %d MHz", freq);
7026                 /* TODO: Consider using CSA or removing the group within
7027                  * wpa_supplicant */
7028                 wpa_msg(ifs, MSG_INFO, P2P_EVENT_REMOVE_AND_REFORM_GROUP);
7029         }
7030 }
7031
7032
7033 static void wpas_p2p_scan_res_ignore(struct wpa_supplicant *wpa_s,
7034                                      struct wpa_scan_results *scan_res)
7035 {
7036         wpa_printf(MSG_DEBUG, "P2P: Ignore scan results");
7037 }
7038
7039
7040 int wpas_p2p_cancel(struct wpa_supplicant *wpa_s)
7041 {
7042         struct wpa_global *global = wpa_s->global;
7043         int found = 0;
7044         const u8 *peer;
7045
7046         if (global->p2p == NULL)
7047                 return -1;
7048
7049         wpa_printf(MSG_DEBUG, "P2P: Request to cancel group formation");
7050
7051         if (wpa_s->pending_interface_name[0] &&
7052             !is_zero_ether_addr(wpa_s->pending_interface_addr))
7053                 found = 1;
7054
7055         peer = p2p_get_go_neg_peer(global->p2p);
7056         if (peer) {
7057                 wpa_printf(MSG_DEBUG, "P2P: Unauthorize pending GO Neg peer "
7058                            MACSTR, MAC2STR(peer));
7059                 p2p_unauthorize(global->p2p, peer);
7060                 found = 1;
7061         }
7062
7063         if (wpa_s->scan_res_handler == wpas_p2p_scan_res_join) {
7064                 wpa_printf(MSG_DEBUG, "P2P: Stop pending scan for join");
7065                 wpa_s->scan_res_handler = wpas_p2p_scan_res_ignore;
7066                 found = 1;
7067         }
7068
7069         if (wpa_s->pending_pd_before_join) {
7070                 wpa_printf(MSG_DEBUG, "P2P: Stop pending PD before join");
7071                 wpa_s->pending_pd_before_join = 0;
7072                 found = 1;
7073         }
7074
7075         wpas_p2p_stop_find(wpa_s);
7076
7077         for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) {
7078                 if (wpa_s == global->p2p_group_formation &&
7079                     (wpa_s->p2p_in_provisioning ||
7080                      wpa_s->parent->pending_interface_type ==
7081                      WPA_IF_P2P_CLIENT)) {
7082                         wpa_printf(MSG_DEBUG, "P2P: Interface %s in group "
7083                                    "formation found - cancelling",
7084                                    wpa_s->ifname);
7085                         found = 1;
7086                         eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
7087                                              wpa_s->parent, NULL);
7088                         if (wpa_s->p2p_in_provisioning) {
7089                                 wpas_group_formation_completed(wpa_s, 0, 0);
7090                                 break;
7091                         }
7092                         wpas_p2p_group_delete(wpa_s,
7093                                               P2P_GROUP_REMOVAL_REQUESTED);
7094                         break;
7095                 } else if (wpa_s->p2p_in_invitation) {
7096                         wpa_printf(MSG_DEBUG, "P2P: Interface %s in invitation found - cancelling",
7097                                    wpa_s->ifname);
7098                         found = 1;
7099                         wpas_p2p_group_formation_failed(wpa_s, 0);
7100                 }
7101         }
7102
7103         if (!found) {
7104                 wpa_printf(MSG_DEBUG, "P2P: No ongoing group formation found");
7105                 return -1;
7106         }
7107
7108         return 0;
7109 }
7110
7111
7112 void wpas_p2p_interface_unavailable(struct wpa_supplicant *wpa_s)
7113 {
7114         if (wpa_s->current_ssid == NULL || !wpa_s->current_ssid->p2p_group)
7115                 return;
7116
7117         wpa_printf(MSG_DEBUG, "P2P: Remove group due to driver resource not "
7118                    "being available anymore");
7119         wpas_p2p_group_delete(wpa_s, P2P_GROUP_REMOVAL_UNAVAILABLE);
7120 }
7121
7122
7123 void wpas_p2p_update_best_channels(struct wpa_supplicant *wpa_s,
7124                                    int freq_24, int freq_5, int freq_overall)
7125 {
7126         struct p2p_data *p2p = wpa_s->global->p2p;
7127         if (p2p == NULL)
7128                 return;
7129         p2p_set_best_channels(p2p, freq_24, freq_5, freq_overall);
7130 }
7131
7132
7133 int wpas_p2p_unauthorize(struct wpa_supplicant *wpa_s, const char *addr)
7134 {
7135         u8 peer[ETH_ALEN];
7136         struct p2p_data *p2p = wpa_s->global->p2p;
7137
7138         if (p2p == NULL)
7139                 return -1;
7140
7141         if (hwaddr_aton(addr, peer))
7142                 return -1;
7143
7144         return p2p_unauthorize(p2p, peer);
7145 }
7146
7147
7148 /**
7149  * wpas_p2p_disconnect - Disconnect from a P2P Group
7150  * @wpa_s: Pointer to wpa_supplicant data
7151  * Returns: 0 on success, -1 on failure
7152  *
7153  * This can be used to disconnect from a group in which the local end is a P2P
7154  * Client or to end a P2P Group in case the local end is the Group Owner. If a
7155  * virtual network interface was created for this group, that interface will be
7156  * removed. Otherwise, only the configured P2P group network will be removed
7157  * from the interface.
7158  */
7159 int wpas_p2p_disconnect(struct wpa_supplicant *wpa_s)
7160 {
7161
7162         if (wpa_s == NULL)
7163                 return -1;
7164
7165         return wpas_p2p_group_delete(wpa_s, P2P_GROUP_REMOVAL_REQUESTED) < 0 ?
7166                 -1 : 0;
7167 }
7168
7169
7170 int wpas_p2p_in_progress(struct wpa_supplicant *wpa_s)
7171 {
7172         int ret;
7173
7174         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
7175                 return 0;
7176
7177         ret = p2p_in_progress(wpa_s->global->p2p);
7178         if (ret == 0) {
7179                 /*
7180                  * Check whether there is an ongoing WPS provisioning step (or
7181                  * other parts of group formation) on another interface since
7182                  * p2p_in_progress() does not report this to avoid issues for
7183                  * scans during such provisioning step.
7184                  */
7185                 if (wpa_s->global->p2p_group_formation &&
7186                     wpa_s->global->p2p_group_formation != wpa_s) {
7187                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Another interface (%s) "
7188                                 "in group formation",
7189                                 wpa_s->global->p2p_group_formation->ifname);
7190                         ret = 1;
7191                 }
7192         }
7193
7194         if (!ret && wpa_s->global->p2p_go_wait_client.sec) {
7195                 struct os_reltime now;
7196                 os_get_reltime(&now);
7197                 if (os_reltime_expired(&now, &wpa_s->global->p2p_go_wait_client,
7198                                        P2P_MAX_INITIAL_CONN_WAIT_GO)) {
7199                         /* Wait for the first client has expired */
7200                         wpa_s->global->p2p_go_wait_client.sec = 0;
7201                 } else {
7202                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Waiting for initial client connection during group formation");
7203                         ret = 1;
7204                 }
7205         }
7206
7207         return ret;
7208 }
7209
7210
7211 void wpas_p2p_network_removed(struct wpa_supplicant *wpa_s,
7212                               struct wpa_ssid *ssid)
7213 {
7214         if (wpa_s->p2p_in_provisioning && ssid->p2p_group &&
7215             eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
7216                                  wpa_s->parent, NULL) > 0) {
7217                 /**
7218                  * Remove the network by scheduling the group formation
7219                  * timeout to happen immediately. The teardown code
7220                  * needs to be scheduled to run asynch later so that we
7221                  * don't delete data from under ourselves unexpectedly.
7222                  * Calling wpas_p2p_group_formation_timeout directly
7223                  * causes a series of crashes in WPS failure scenarios.
7224                  */
7225                 wpa_printf(MSG_DEBUG, "P2P: Canceled group formation due to "
7226                            "P2P group network getting removed");
7227                 eloop_register_timeout(0, 0, wpas_p2p_group_formation_timeout,
7228                                        wpa_s->parent, NULL);
7229         }
7230 }
7231
7232
7233 struct wpa_ssid * wpas_p2p_get_persistent(struct wpa_supplicant *wpa_s,
7234                                           const u8 *addr, const u8 *ssid,
7235                                           size_t ssid_len)
7236 {
7237         struct wpa_ssid *s;
7238         size_t i;
7239
7240         for (s = wpa_s->conf->ssid; s; s = s->next) {
7241                 if (s->disabled != 2)
7242                         continue;
7243                 if (ssid &&
7244                     (ssid_len != s->ssid_len ||
7245                      os_memcmp(ssid, s->ssid, ssid_len) != 0))
7246                         continue;
7247                 if (addr == NULL) {
7248                         if (s->mode == WPAS_MODE_P2P_GO)
7249                                 return s;
7250                         continue;
7251                 }
7252                 if (os_memcmp(s->bssid, addr, ETH_ALEN) == 0)
7253                         return s; /* peer is GO in the persistent group */
7254                 if (s->mode != WPAS_MODE_P2P_GO || s->p2p_client_list == NULL)
7255                         continue;
7256                 for (i = 0; i < s->num_p2p_clients; i++) {
7257                         if (os_memcmp(s->p2p_client_list + i * 2 * ETH_ALEN,
7258                                       addr, ETH_ALEN) == 0)
7259                                 return s; /* peer is P2P client in persistent
7260                                            * group */
7261                 }
7262         }
7263
7264         return NULL;
7265 }
7266
7267
7268 void wpas_p2p_notify_ap_sta_authorized(struct wpa_supplicant *wpa_s,
7269                                        const u8 *addr)
7270 {
7271         if (eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
7272                                  wpa_s->parent, NULL) > 0) {
7273                 /*
7274                  * This can happen if WPS provisioning step is not terminated
7275                  * cleanly (e.g., P2P Client does not send WSC_Done). Since the
7276                  * peer was able to connect, there is no need to time out group
7277                  * formation after this, though. In addition, this is used with
7278                  * the initial connection wait on the GO as a separate formation
7279                  * timeout and as such, expected to be hit after the initial WPS
7280                  * provisioning step.
7281                  */
7282                 wpa_printf(MSG_DEBUG, "P2P: Canceled P2P group formation timeout on data connection");
7283
7284                 if (!wpa_s->p2p_go_group_formation_completed &&
7285                     !wpa_s->group_formation_reported) {
7286                         /*
7287                          * GO has not yet notified group formation success since
7288                          * the WPS step was not completed cleanly. Do that
7289                          * notification now since the P2P Client was able to
7290                          * connect and as such, must have received the
7291                          * credential from the WPS step.
7292                          */
7293                         if (wpa_s->global->p2p)
7294                                 p2p_wps_success_cb(wpa_s->global->p2p, addr);
7295                         wpas_group_formation_completed(wpa_s, 1, 0);
7296                 }
7297         }
7298         if (!wpa_s->p2p_go_group_formation_completed) {
7299                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Marking group formation completed on GO on first data connection");
7300                 wpa_s->p2p_go_group_formation_completed = 1;
7301                 wpa_s->global->p2p_group_formation = NULL;
7302                 wpa_s->p2p_in_provisioning = 0;
7303                 wpa_s->p2p_in_invitation = 0;
7304         }
7305         wpa_s->global->p2p_go_wait_client.sec = 0;
7306         if (addr == NULL)
7307                 return;
7308         wpas_p2p_add_persistent_group_client(wpa_s, addr);
7309 }
7310
7311
7312 static int wpas_p2p_fallback_to_go_neg(struct wpa_supplicant *wpa_s,
7313                                        int group_added)
7314 {
7315         struct wpa_supplicant *group = wpa_s;
7316         int ret = 0;
7317
7318         if (wpa_s->global->p2p_group_formation)
7319                 group = wpa_s->global->p2p_group_formation;
7320         wpa_s = wpa_s->global->p2p_init_wpa_s;
7321         offchannel_send_action_done(wpa_s);
7322         if (group_added)
7323                 ret = wpas_p2p_group_delete(group, P2P_GROUP_REMOVAL_SILENT);
7324         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Fall back to GO Negotiation");
7325         wpas_p2p_connect(wpa_s, wpa_s->pending_join_dev_addr, wpa_s->p2p_pin,
7326                          wpa_s->p2p_wps_method, wpa_s->p2p_persistent_group, 0,
7327                          0, 0, wpa_s->p2p_go_intent, wpa_s->p2p_connect_freq,
7328                          wpa_s->p2p_persistent_id,
7329                          wpa_s->p2p_pd_before_go_neg,
7330                          wpa_s->p2p_go_ht40,
7331                          wpa_s->p2p_go_vht);
7332         return ret;
7333 }
7334
7335
7336 int wpas_p2p_scan_no_go_seen(struct wpa_supplicant *wpa_s)
7337 {
7338         int res;
7339
7340         if (!wpa_s->p2p_fallback_to_go_neg ||
7341             wpa_s->p2p_in_provisioning <= 5)
7342                 return 0;
7343
7344         if (wpas_p2p_peer_go(wpa_s, wpa_s->pending_join_dev_addr) > 0)
7345                 return 0; /* peer operating as a GO */
7346
7347         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: GO not found for p2p_connect-auto - "
7348                 "fallback to GO Negotiation");
7349         wpa_msg_global(wpa_s->parent, MSG_INFO, P2P_EVENT_FALLBACK_TO_GO_NEG
7350                        "reason=GO-not-found");
7351         res = wpas_p2p_fallback_to_go_neg(wpa_s, 1);
7352
7353         return res == 1 ? 2 : 1;
7354 }
7355
7356
7357 unsigned int wpas_p2p_search_delay(struct wpa_supplicant *wpa_s)
7358 {
7359         struct wpa_supplicant *ifs;
7360
7361         if (wpa_s->wpa_state > WPA_SCANNING) {
7362                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Use %u ms search delay due to "
7363                         "concurrent operation",
7364                         wpa_s->conf->p2p_search_delay);
7365                 return wpa_s->conf->p2p_search_delay;
7366         }
7367
7368         dl_list_for_each(ifs, &wpa_s->radio->ifaces, struct wpa_supplicant,
7369                          radio_list) {
7370                 if (ifs != wpa_s && ifs->wpa_state > WPA_SCANNING) {
7371                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Use %u ms search "
7372                                 "delay due to concurrent operation on "
7373                                 "interface %s",
7374                                 wpa_s->conf->p2p_search_delay,
7375                                 ifs->ifname);
7376                         return wpa_s->conf->p2p_search_delay;
7377                 }
7378         }
7379
7380         return 0;
7381 }
7382
7383
7384 static int wpas_p2p_remove_psk_entry(struct wpa_supplicant *wpa_s,
7385                                      struct wpa_ssid *s, const u8 *addr,
7386                                      int iface_addr)
7387 {
7388         struct psk_list_entry *psk, *tmp;
7389         int changed = 0;
7390
7391         dl_list_for_each_safe(psk, tmp, &s->psk_list, struct psk_list_entry,
7392                               list) {
7393                 if ((iface_addr && !psk->p2p &&
7394                      os_memcmp(addr, psk->addr, ETH_ALEN) == 0) ||
7395                     (!iface_addr && psk->p2p &&
7396                      os_memcmp(addr, psk->addr, ETH_ALEN) == 0)) {
7397                         wpa_dbg(wpa_s, MSG_DEBUG,
7398                                 "P2P: Remove persistent group PSK list entry for "
7399                                 MACSTR " p2p=%u",
7400                                 MAC2STR(psk->addr), psk->p2p);
7401                         dl_list_del(&psk->list);
7402                         os_free(psk);
7403                         changed++;
7404                 }
7405         }
7406
7407         return changed;
7408 }
7409
7410
7411 void wpas_p2p_new_psk_cb(struct wpa_supplicant *wpa_s, const u8 *mac_addr,
7412                          const u8 *p2p_dev_addr,
7413                          const u8 *psk, size_t psk_len)
7414 {
7415         struct wpa_ssid *ssid = wpa_s->current_ssid;
7416         struct wpa_ssid *persistent;
7417         struct psk_list_entry *p, *last;
7418
7419         if (psk_len != sizeof(p->psk))
7420                 return;
7421
7422         if (p2p_dev_addr) {
7423                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: New PSK for addr=" MACSTR
7424                         " p2p_dev_addr=" MACSTR,
7425                         MAC2STR(mac_addr), MAC2STR(p2p_dev_addr));
7426                 if (is_zero_ether_addr(p2p_dev_addr))
7427                         p2p_dev_addr = NULL;
7428         } else {
7429                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: New PSK for addr=" MACSTR,
7430                         MAC2STR(mac_addr));
7431         }
7432
7433         if (ssid->mode == WPAS_MODE_P2P_GROUP_FORMATION) {
7434                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: new_psk_cb during group formation");
7435                 /* To be added to persistent group once created */
7436                 if (wpa_s->global->add_psk == NULL) {
7437                         wpa_s->global->add_psk = os_zalloc(sizeof(*p));
7438                         if (wpa_s->global->add_psk == NULL)
7439                                 return;
7440                 }
7441                 p = wpa_s->global->add_psk;
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                 return;
7451         }
7452
7453         if (ssid->mode != WPAS_MODE_P2P_GO || !ssid->p2p_persistent_group) {
7454                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Ignore new_psk_cb on not-persistent GO");
7455                 return;
7456         }
7457
7458         persistent = wpas_p2p_get_persistent(wpa_s->parent, NULL, ssid->ssid,
7459                                              ssid->ssid_len);
7460         if (!persistent) {
7461                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Could not find persistent group information to store the new PSK");
7462                 return;
7463         }
7464
7465         p = os_zalloc(sizeof(*p));
7466         if (p == NULL)
7467                 return;
7468         if (p2p_dev_addr) {
7469                 p->p2p = 1;
7470                 os_memcpy(p->addr, p2p_dev_addr, ETH_ALEN);
7471         } else {
7472                 p->p2p = 0;
7473                 os_memcpy(p->addr, mac_addr, ETH_ALEN);
7474         }
7475         os_memcpy(p->psk, psk, psk_len);
7476
7477         if (dl_list_len(&persistent->psk_list) > P2P_MAX_STORED_CLIENTS &&
7478             (last = dl_list_last(&persistent->psk_list,
7479                                  struct psk_list_entry, list))) {
7480                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Remove oldest PSK entry for "
7481                         MACSTR " (p2p=%u) to make room for a new one",
7482                         MAC2STR(last->addr), last->p2p);
7483                 dl_list_del(&last->list);
7484                 os_free(last);
7485         }
7486
7487         wpas_p2p_remove_psk_entry(wpa_s->parent, persistent,
7488                                   p2p_dev_addr ? p2p_dev_addr : mac_addr,
7489                                   p2p_dev_addr == NULL);
7490         if (p2p_dev_addr) {
7491                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Add new PSK for p2p_dev_addr="
7492                         MACSTR, MAC2STR(p2p_dev_addr));
7493         } else {
7494                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Add new PSK for addr=" MACSTR,
7495                         MAC2STR(mac_addr));
7496         }
7497         dl_list_add(&persistent->psk_list, &p->list);
7498
7499         if (wpa_s->parent->conf->update_config &&
7500             wpa_config_write(wpa_s->parent->confname, wpa_s->parent->conf))
7501                 wpa_printf(MSG_DEBUG, "P2P: Failed to update configuration");
7502 }
7503
7504
7505 static void wpas_p2p_remove_psk(struct wpa_supplicant *wpa_s,
7506                                 struct wpa_ssid *s, const u8 *addr,
7507                                 int iface_addr)
7508 {
7509         int res;
7510
7511         res = wpas_p2p_remove_psk_entry(wpa_s, s, addr, iface_addr);
7512         if (res > 0 && wpa_s->conf->update_config &&
7513             wpa_config_write(wpa_s->confname, wpa_s->conf))
7514                 wpa_dbg(wpa_s, MSG_DEBUG,
7515                         "P2P: Failed to update configuration");
7516 }
7517
7518
7519 static void wpas_p2p_remove_client_go(struct wpa_supplicant *wpa_s,
7520                                       const u8 *peer, int iface_addr)
7521 {
7522         struct hostapd_data *hapd;
7523         struct hostapd_wpa_psk *psk, *prev, *rem;
7524         struct sta_info *sta;
7525
7526         if (wpa_s->ap_iface == NULL || wpa_s->current_ssid == NULL ||
7527             wpa_s->current_ssid->mode != WPAS_MODE_P2P_GO)
7528                 return;
7529
7530         /* Remove per-station PSK entry */
7531         hapd = wpa_s->ap_iface->bss[0];
7532         prev = NULL;
7533         psk = hapd->conf->ssid.wpa_psk;
7534         while (psk) {
7535                 if ((iface_addr && os_memcmp(peer, psk->addr, ETH_ALEN) == 0) ||
7536                     (!iface_addr &&
7537                      os_memcmp(peer, psk->p2p_dev_addr, ETH_ALEN) == 0)) {
7538                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Remove operating group PSK entry for "
7539                                 MACSTR " iface_addr=%d",
7540                                 MAC2STR(peer), iface_addr);
7541                         if (prev)
7542                                 prev->next = psk->next;
7543                         else
7544                                 hapd->conf->ssid.wpa_psk = psk->next;
7545                         rem = psk;
7546                         psk = psk->next;
7547                         os_free(rem);
7548                 } else {
7549                         prev = psk;
7550                         psk = psk->next;
7551                 }
7552         }
7553
7554         /* Disconnect from group */
7555         if (iface_addr)
7556                 sta = ap_get_sta(hapd, peer);
7557         else
7558                 sta = ap_get_sta_p2p(hapd, peer);
7559         if (sta) {
7560                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Disconnect peer " MACSTR
7561                         " (iface_addr=%d) from group",
7562                         MAC2STR(peer), iface_addr);
7563                 hostapd_drv_sta_deauth(hapd, sta->addr,
7564                                        WLAN_REASON_DEAUTH_LEAVING);
7565                 ap_sta_deauthenticate(hapd, sta, WLAN_REASON_DEAUTH_LEAVING);
7566         }
7567 }
7568
7569
7570 void wpas_p2p_remove_client(struct wpa_supplicant *wpa_s, const u8 *peer,
7571                             int iface_addr)
7572 {
7573         struct wpa_ssid *s;
7574         struct wpa_supplicant *w;
7575         struct wpa_supplicant *p2p_wpa_s = wpa_s->global->p2p_init_wpa_s;
7576
7577         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Remove client " MACSTR, MAC2STR(peer));
7578
7579         /* Remove from any persistent group */
7580         for (s = p2p_wpa_s->conf->ssid; s; s = s->next) {
7581                 if (s->disabled != 2 || s->mode != WPAS_MODE_P2P_GO)
7582                         continue;
7583                 if (!iface_addr)
7584                         wpas_remove_persistent_peer(p2p_wpa_s, s, peer, 0);
7585                 wpas_p2p_remove_psk(p2p_wpa_s, s, peer, iface_addr);
7586         }
7587
7588         /* Remove from any operating group */
7589         for (w = wpa_s->global->ifaces; w; w = w->next)
7590                 wpas_p2p_remove_client_go(w, peer, iface_addr);
7591 }
7592
7593
7594 static void wpas_p2p_psk_failure_removal(void *eloop_ctx, void *timeout_ctx)
7595 {
7596         struct wpa_supplicant *wpa_s = eloop_ctx;
7597         wpas_p2p_group_delete(wpa_s, P2P_GROUP_REMOVAL_PSK_FAILURE);
7598 }
7599
7600
7601 static void wpas_p2p_group_freq_conflict(void *eloop_ctx, void *timeout_ctx)
7602 {
7603         struct wpa_supplicant *wpa_s = eloop_ctx;
7604
7605         wpa_printf(MSG_DEBUG, "P2P: Frequency conflict - terminate group");
7606         wpas_p2p_group_delete(wpa_s, P2P_GROUP_REMOVAL_FREQ_CONFLICT);
7607 }
7608
7609
7610 int wpas_p2p_handle_frequency_conflicts(struct wpa_supplicant *wpa_s, int freq,
7611                                         struct wpa_ssid *ssid)
7612 {
7613         struct wpa_supplicant *iface;
7614
7615         for (iface = wpa_s->global->ifaces; iface; iface = iface->next) {
7616                 if (!iface->current_ssid ||
7617                     iface->current_ssid->frequency == freq ||
7618                     (iface->p2p_group_interface == NOT_P2P_GROUP_INTERFACE &&
7619                      !iface->current_ssid->p2p_group))
7620                         continue;
7621
7622                 /* Remove the connection with least priority */
7623                 if (!wpas_is_p2p_prioritized(iface)) {
7624                         /* STA connection has priority over existing
7625                          * P2P connection, so remove the interface. */
7626                         wpa_printf(MSG_DEBUG, "P2P: Removing P2P connection due to single channel concurrent mode frequency conflict");
7627                         eloop_register_timeout(0, 0,
7628                                                wpas_p2p_group_freq_conflict,
7629                                                iface, NULL);
7630                         /* If connection in progress is P2P connection, do not
7631                          * proceed for the connection. */
7632                         if (wpa_s == iface)
7633                                 return -1;
7634                         else
7635                                 return 0;
7636                 } else {
7637                         /* P2P connection has priority, disable the STA network
7638                          */
7639                         wpa_supplicant_disable_network(wpa_s->global->ifaces,
7640                                                        ssid);
7641                         wpa_msg(wpa_s->global->ifaces, MSG_INFO,
7642                                 WPA_EVENT_FREQ_CONFLICT " id=%d", ssid->id);
7643                         os_memset(wpa_s->global->ifaces->pending_bssid, 0,
7644                                   ETH_ALEN);
7645                         /* If P2P connection is in progress, continue
7646                          * connecting...*/
7647                         if (wpa_s == iface)
7648                                 return 0;
7649                         else
7650                                 return -1;
7651                 }
7652         }
7653
7654         return 0;
7655 }
7656
7657
7658 int wpas_p2p_4way_hs_failed(struct wpa_supplicant *wpa_s)
7659 {
7660         struct wpa_ssid *ssid = wpa_s->current_ssid;
7661
7662         if (ssid == NULL || !ssid->p2p_group)
7663                 return 0;
7664
7665         if (wpa_s->p2p_last_4way_hs_fail &&
7666             wpa_s->p2p_last_4way_hs_fail == ssid) {
7667                 u8 go_dev_addr[ETH_ALEN];
7668                 struct wpa_ssid *persistent;
7669
7670                 if (wpas_p2p_persistent_group(wpa_s, go_dev_addr,
7671                                               ssid->ssid,
7672                                               ssid->ssid_len) <= 0) {
7673                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Could not determine whether 4-way handshake failures were for a persistent group");
7674                         goto disconnect;
7675                 }
7676
7677                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Two 4-way handshake failures for a P2P group - go_dev_addr="
7678                         MACSTR, MAC2STR(go_dev_addr));
7679                 persistent = wpas_p2p_get_persistent(wpa_s->parent, go_dev_addr,
7680                                                      ssid->ssid,
7681                                                      ssid->ssid_len);
7682                 if (persistent == NULL || persistent->mode != WPAS_MODE_INFRA) {
7683                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: No matching persistent group stored");
7684                         goto disconnect;
7685                 }
7686                 wpa_msg_global(wpa_s->parent, MSG_INFO,
7687                                P2P_EVENT_PERSISTENT_PSK_FAIL "%d",
7688                                persistent->id);
7689         disconnect:
7690                 wpa_s->p2p_last_4way_hs_fail = NULL;
7691                 /*
7692                  * Remove the group from a timeout to avoid issues with caller
7693                  * continuing to use the interface if this is on a P2P group
7694                  * interface.
7695                  */
7696                 eloop_register_timeout(0, 0, wpas_p2p_psk_failure_removal,
7697                                        wpa_s, NULL);
7698                 return 1;
7699         }
7700
7701         wpa_s->p2p_last_4way_hs_fail = ssid;
7702         return 0;
7703 }
7704
7705
7706 #ifdef CONFIG_WPS_NFC
7707
7708 static struct wpabuf * wpas_p2p_nfc_handover(int ndef, struct wpabuf *wsc,
7709                                              struct wpabuf *p2p)
7710 {
7711         struct wpabuf *ret;
7712         size_t wsc_len;
7713
7714         if (p2p == NULL) {
7715                 wpabuf_free(wsc);
7716                 wpa_printf(MSG_DEBUG, "P2P: No p2p buffer for handover");
7717                 return NULL;
7718         }
7719
7720         wsc_len = wsc ? wpabuf_len(wsc) : 0;
7721         ret = wpabuf_alloc(2 + wsc_len + 2 + wpabuf_len(p2p));
7722         if (ret == NULL) {
7723                 wpabuf_free(wsc);
7724                 wpabuf_free(p2p);
7725                 return NULL;
7726         }
7727
7728         wpabuf_put_be16(ret, wsc_len);
7729         if (wsc)
7730                 wpabuf_put_buf(ret, wsc);
7731         wpabuf_put_be16(ret, wpabuf_len(p2p));
7732         wpabuf_put_buf(ret, p2p);
7733
7734         wpabuf_free(wsc);
7735         wpabuf_free(p2p);
7736         wpa_hexdump_buf(MSG_DEBUG,
7737                         "P2P: Generated NFC connection handover message", ret);
7738
7739         if (ndef && ret) {
7740                 struct wpabuf *tmp;
7741                 tmp = ndef_build_p2p(ret);
7742                 wpabuf_free(ret);
7743                 if (tmp == NULL) {
7744                         wpa_printf(MSG_DEBUG, "P2P: Failed to NDEF encapsulate handover request");
7745                         return NULL;
7746                 }
7747                 ret = tmp;
7748         }
7749
7750         return ret;
7751 }
7752
7753
7754 static int wpas_p2p_cli_freq(struct wpa_supplicant *wpa_s,
7755                              struct wpa_ssid **ssid, u8 *go_dev_addr)
7756 {
7757         struct wpa_supplicant *iface;
7758
7759         if (go_dev_addr)
7760                 os_memset(go_dev_addr, 0, ETH_ALEN);
7761         if (ssid)
7762                 *ssid = NULL;
7763         for (iface = wpa_s->global->ifaces; iface; iface = iface->next) {
7764                 if (iface->wpa_state < WPA_ASSOCIATING ||
7765                     iface->current_ssid == NULL || iface->assoc_freq == 0 ||
7766                     !iface->current_ssid->p2p_group ||
7767                     iface->current_ssid->mode != WPAS_MODE_INFRA)
7768                         continue;
7769                 if (ssid)
7770                         *ssid = iface->current_ssid;
7771                 if (go_dev_addr)
7772                         os_memcpy(go_dev_addr, iface->go_dev_addr, ETH_ALEN);
7773                 return iface->assoc_freq;
7774         }
7775         return 0;
7776 }
7777
7778
7779 struct wpabuf * wpas_p2p_nfc_handover_req(struct wpa_supplicant *wpa_s,
7780                                           int ndef)
7781 {
7782         struct wpabuf *wsc, *p2p;
7783         struct wpa_ssid *ssid;
7784         u8 go_dev_addr[ETH_ALEN];
7785         int cli_freq = wpas_p2p_cli_freq(wpa_s, &ssid, go_dev_addr);
7786
7787         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL) {
7788                 wpa_printf(MSG_DEBUG, "P2P: P2P disabled - cannot build handover request");
7789                 return NULL;
7790         }
7791
7792         if (wpa_s->conf->wps_nfc_dh_pubkey == NULL &&
7793             wps_nfc_gen_dh(&wpa_s->conf->wps_nfc_dh_pubkey,
7794                            &wpa_s->conf->wps_nfc_dh_privkey) < 0) {
7795                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: No DH key available for handover request");
7796                 return NULL;
7797         }
7798
7799         if (cli_freq == 0) {
7800                 wsc = wps_build_nfc_handover_req_p2p(
7801                         wpa_s->parent->wps, wpa_s->conf->wps_nfc_dh_pubkey);
7802         } else
7803                 wsc = NULL;
7804         p2p = p2p_build_nfc_handover_req(wpa_s->global->p2p, cli_freq,
7805                                          go_dev_addr, ssid ? ssid->ssid : NULL,
7806                                          ssid ? ssid->ssid_len : 0);
7807
7808         return wpas_p2p_nfc_handover(ndef, wsc, p2p);
7809 }
7810
7811
7812 struct wpabuf * wpas_p2p_nfc_handover_sel(struct wpa_supplicant *wpa_s,
7813                                           int ndef, int tag)
7814 {
7815         struct wpabuf *wsc, *p2p;
7816         struct wpa_ssid *ssid;
7817         u8 go_dev_addr[ETH_ALEN];
7818         int cli_freq = wpas_p2p_cli_freq(wpa_s, &ssid, go_dev_addr);
7819
7820         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
7821                 return NULL;
7822
7823         if (!tag && wpa_s->conf->wps_nfc_dh_pubkey == NULL &&
7824             wps_nfc_gen_dh(&wpa_s->conf->wps_nfc_dh_pubkey,
7825                            &wpa_s->conf->wps_nfc_dh_privkey) < 0)
7826                 return NULL;
7827
7828         if (cli_freq == 0) {
7829                 wsc = wps_build_nfc_handover_sel_p2p(
7830                         wpa_s->parent->wps,
7831                         tag ? wpa_s->conf->wps_nfc_dev_pw_id :
7832                         DEV_PW_NFC_CONNECTION_HANDOVER,
7833                         wpa_s->conf->wps_nfc_dh_pubkey,
7834                         tag ? wpa_s->conf->wps_nfc_dev_pw : NULL);
7835         } else
7836                 wsc = NULL;
7837         p2p = p2p_build_nfc_handover_sel(wpa_s->global->p2p, cli_freq,
7838                                          go_dev_addr, ssid ? ssid->ssid : NULL,
7839                                          ssid ? ssid->ssid_len : 0);
7840
7841         return wpas_p2p_nfc_handover(ndef, wsc, p2p);
7842 }
7843
7844
7845 static int wpas_p2p_nfc_join_group(struct wpa_supplicant *wpa_s,
7846                                    struct p2p_nfc_params *params)
7847 {
7848         wpa_printf(MSG_DEBUG, "P2P: Initiate join-group based on NFC "
7849                    "connection handover (freq=%d)",
7850                    params->go_freq);
7851
7852         if (params->go_freq && params->go_ssid_len) {
7853                 wpa_s->p2p_wps_method = WPS_NFC;
7854                 wpa_s->pending_join_wps_method = WPS_NFC;
7855                 os_memset(wpa_s->pending_join_iface_addr, 0, ETH_ALEN);
7856                 os_memcpy(wpa_s->pending_join_dev_addr, params->go_dev_addr,
7857                           ETH_ALEN);
7858                 return wpas_p2p_join_start(wpa_s, params->go_freq,
7859                                            params->go_ssid,
7860                                            params->go_ssid_len);
7861         }
7862
7863         return wpas_p2p_connect(wpa_s, params->peer->p2p_device_addr, NULL,
7864                                 WPS_NFC, 0, 0, 1, 0, wpa_s->conf->p2p_go_intent,
7865                                 params->go_freq, -1, 0, 1, 1);
7866 }
7867
7868
7869 static int wpas_p2p_nfc_auth_join(struct wpa_supplicant *wpa_s,
7870                                   struct p2p_nfc_params *params, int tag)
7871 {
7872         int res, persistent;
7873         struct wpa_ssid *ssid;
7874
7875         wpa_printf(MSG_DEBUG, "P2P: Authorize join-group based on NFC "
7876                    "connection handover");
7877         for (wpa_s = wpa_s->global->ifaces; wpa_s; wpa_s = wpa_s->next) {
7878                 ssid = wpa_s->current_ssid;
7879                 if (ssid == NULL)
7880                         continue;
7881                 if (ssid->mode != WPAS_MODE_P2P_GO)
7882                         continue;
7883                 if (wpa_s->ap_iface == NULL)
7884                         continue;
7885                 break;
7886         }
7887         if (wpa_s == NULL) {
7888                 wpa_printf(MSG_DEBUG, "P2P: Could not find GO interface");
7889                 return -1;
7890         }
7891
7892         if (wpa_s->parent->p2p_oob_dev_pw_id !=
7893             DEV_PW_NFC_CONNECTION_HANDOVER &&
7894             !wpa_s->parent->p2p_oob_dev_pw) {
7895                 wpa_printf(MSG_DEBUG, "P2P: No NFC Dev Pw known");
7896                 return -1;
7897         }
7898         res = wpas_ap_wps_add_nfc_pw(
7899                 wpa_s, wpa_s->parent->p2p_oob_dev_pw_id,
7900                 wpa_s->parent->p2p_oob_dev_pw,
7901                 wpa_s->parent->p2p_peer_oob_pk_hash_known ?
7902                 wpa_s->parent->p2p_peer_oob_pubkey_hash : NULL);
7903         if (res)
7904                 return res;
7905
7906         if (!tag) {
7907                 wpa_printf(MSG_DEBUG, "P2P: Negotiated handover - wait for peer to join without invitation");
7908                 return 0;
7909         }
7910
7911         if (!params->peer ||
7912             !(params->peer->dev_capab & P2P_DEV_CAPAB_INVITATION_PROCEDURE))
7913                 return 0;
7914
7915         wpa_printf(MSG_DEBUG, "P2P: Static handover - invite peer " MACSTR
7916                    " to join", MAC2STR(params->peer->p2p_device_addr));
7917
7918         wpa_s->global->p2p_invite_group = wpa_s;
7919         persistent = ssid->p2p_persistent_group &&
7920                 wpas_p2p_get_persistent(wpa_s->parent,
7921                                         params->peer->p2p_device_addr,
7922                                         ssid->ssid, ssid->ssid_len);
7923         wpa_s->parent->pending_invite_ssid_id = -1;
7924
7925         return p2p_invite(wpa_s->global->p2p, params->peer->p2p_device_addr,
7926                           P2P_INVITE_ROLE_ACTIVE_GO, wpa_s->own_addr,
7927                           ssid->ssid, ssid->ssid_len, ssid->frequency,
7928                           wpa_s->global->p2p_dev_addr, persistent, 0,
7929                           wpa_s->parent->p2p_oob_dev_pw_id);
7930 }
7931
7932
7933 static int wpas_p2p_nfc_init_go_neg(struct wpa_supplicant *wpa_s,
7934                                     struct p2p_nfc_params *params,
7935                                     int forced_freq)
7936 {
7937         wpa_printf(MSG_DEBUG, "P2P: Initiate GO Negotiation based on NFC "
7938                    "connection handover");
7939         return wpas_p2p_connect(wpa_s, params->peer->p2p_device_addr, NULL,
7940                                 WPS_NFC, 0, 0, 0, 0, wpa_s->conf->p2p_go_intent,
7941                                 forced_freq, -1, 0, 1, 1);
7942 }
7943
7944
7945 static int wpas_p2p_nfc_resp_go_neg(struct wpa_supplicant *wpa_s,
7946                                     struct p2p_nfc_params *params,
7947                                     int forced_freq)
7948 {
7949         int res;
7950
7951         wpa_printf(MSG_DEBUG, "P2P: Authorize GO Negotiation based on NFC "
7952                    "connection handover");
7953         res = wpas_p2p_connect(wpa_s, params->peer->p2p_device_addr, NULL,
7954                                WPS_NFC, 0, 0, 0, 1, wpa_s->conf->p2p_go_intent,
7955                                forced_freq, -1, 0, 1, 1);
7956         if (res)
7957                 return res;
7958
7959         res = wpas_p2p_listen(wpa_s, 60);
7960         if (res) {
7961                 p2p_unauthorize(wpa_s->global->p2p,
7962                                 params->peer->p2p_device_addr);
7963         }
7964
7965         return res;
7966 }
7967
7968
7969 static int wpas_p2p_nfc_connection_handover(struct wpa_supplicant *wpa_s,
7970                                             const struct wpabuf *data,
7971                                             int sel, int tag, int forced_freq)
7972 {
7973         const u8 *pos, *end;
7974         u16 len, id;
7975         struct p2p_nfc_params params;
7976         int res;
7977
7978         os_memset(&params, 0, sizeof(params));
7979         params.sel = sel;
7980
7981         wpa_hexdump_buf(MSG_DEBUG, "P2P: Received NFC tag payload", data);
7982
7983         pos = wpabuf_head(data);
7984         end = pos + wpabuf_len(data);
7985
7986         if (end - pos < 2) {
7987                 wpa_printf(MSG_DEBUG, "P2P: Not enough data for Length of WSC "
7988                            "attributes");
7989                 return -1;
7990         }
7991         len = WPA_GET_BE16(pos);
7992         pos += 2;
7993         if (len > end - pos) {
7994                 wpa_printf(MSG_DEBUG, "P2P: Not enough data for WSC "
7995                            "attributes");
7996                 return -1;
7997         }
7998         params.wsc_attr = pos;
7999         params.wsc_len = len;
8000         pos += len;
8001
8002         if (end - pos < 2) {
8003                 wpa_printf(MSG_DEBUG, "P2P: Not enough data for Length of P2P "
8004                            "attributes");
8005                 return -1;
8006         }
8007         len = WPA_GET_BE16(pos);
8008         pos += 2;
8009         if (len > end - pos) {
8010                 wpa_printf(MSG_DEBUG, "P2P: Not enough data for P2P "
8011                            "attributes");
8012                 return -1;
8013         }
8014         params.p2p_attr = pos;
8015         params.p2p_len = len;
8016         pos += len;
8017
8018         wpa_hexdump(MSG_DEBUG, "P2P: WSC attributes",
8019                     params.wsc_attr, params.wsc_len);
8020         wpa_hexdump(MSG_DEBUG, "P2P: P2P attributes",
8021                     params.p2p_attr, params.p2p_len);
8022         if (pos < end) {
8023                 wpa_hexdump(MSG_DEBUG,
8024                             "P2P: Ignored extra data after P2P attributes",
8025                             pos, end - pos);
8026         }
8027
8028         res = p2p_process_nfc_connection_handover(wpa_s->global->p2p, &params);
8029         if (res)
8030                 return res;
8031
8032         if (params.next_step == NO_ACTION)
8033                 return 0;
8034
8035         if (params.next_step == BOTH_GO) {
8036                 wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_NFC_BOTH_GO "peer=" MACSTR,
8037                         MAC2STR(params.peer->p2p_device_addr));
8038                 return 0;
8039         }
8040
8041         if (params.next_step == PEER_CLIENT) {
8042                 if (!is_zero_ether_addr(params.go_dev_addr)) {
8043                         wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_NFC_PEER_CLIENT
8044                                 "peer=" MACSTR " freq=%d go_dev_addr=" MACSTR
8045                                 " ssid=\"%s\"",
8046                                 MAC2STR(params.peer->p2p_device_addr),
8047                                 params.go_freq,
8048                                 MAC2STR(params.go_dev_addr),
8049                                 wpa_ssid_txt(params.go_ssid,
8050                                              params.go_ssid_len));
8051                 } else {
8052                         wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_NFC_PEER_CLIENT
8053                                 "peer=" MACSTR " freq=%d",
8054                                 MAC2STR(params.peer->p2p_device_addr),
8055                                 params.go_freq);
8056                 }
8057                 return 0;
8058         }
8059
8060         if (wpas_p2p_cli_freq(wpa_s, NULL, NULL)) {
8061                 wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_NFC_WHILE_CLIENT "peer="
8062                         MACSTR, MAC2STR(params.peer->p2p_device_addr));
8063                 return 0;
8064         }
8065
8066         wpabuf_free(wpa_s->p2p_oob_dev_pw);
8067         wpa_s->p2p_oob_dev_pw = NULL;
8068
8069         if (params.oob_dev_pw_len < WPS_OOB_PUBKEY_HASH_LEN + 2) {
8070                 wpa_printf(MSG_DEBUG, "P2P: No peer OOB Dev Pw "
8071                            "received");
8072                 return -1;
8073         }
8074
8075         id = WPA_GET_BE16(params.oob_dev_pw + WPS_OOB_PUBKEY_HASH_LEN);
8076         wpa_printf(MSG_DEBUG, "P2P: Peer OOB Dev Pw %u", id);
8077         wpa_hexdump(MSG_DEBUG, "P2P: Peer OOB Public Key hash",
8078                     params.oob_dev_pw, WPS_OOB_PUBKEY_HASH_LEN);
8079         os_memcpy(wpa_s->p2p_peer_oob_pubkey_hash,
8080                   params.oob_dev_pw, WPS_OOB_PUBKEY_HASH_LEN);
8081         wpa_s->p2p_peer_oob_pk_hash_known = 1;
8082
8083         if (tag) {
8084                 if (id < 0x10) {
8085                         wpa_printf(MSG_DEBUG, "P2P: Static handover - invalid "
8086                                    "peer OOB Device Password Id %u", id);
8087                         return -1;
8088                 }
8089                 wpa_printf(MSG_DEBUG, "P2P: Static handover - use peer OOB "
8090                            "Device Password Id %u", id);
8091                 wpa_hexdump_key(MSG_DEBUG, "P2P: Peer OOB Device Password",
8092                                 params.oob_dev_pw + WPS_OOB_PUBKEY_HASH_LEN + 2,
8093                                 params.oob_dev_pw_len -
8094                                 WPS_OOB_PUBKEY_HASH_LEN - 2);
8095                 wpa_s->p2p_oob_dev_pw_id = id;
8096                 wpa_s->p2p_oob_dev_pw = wpabuf_alloc_copy(
8097                         params.oob_dev_pw + WPS_OOB_PUBKEY_HASH_LEN + 2,
8098                         params.oob_dev_pw_len -
8099                         WPS_OOB_PUBKEY_HASH_LEN - 2);
8100                 if (wpa_s->p2p_oob_dev_pw == NULL)
8101                         return -1;
8102
8103                 if (wpa_s->conf->wps_nfc_dh_pubkey == NULL &&
8104                     wps_nfc_gen_dh(&wpa_s->conf->wps_nfc_dh_pubkey,
8105                                    &wpa_s->conf->wps_nfc_dh_privkey) < 0)
8106                         return -1;
8107         } else {
8108                 wpa_printf(MSG_DEBUG, "P2P: Using abbreviated WPS handshake "
8109                            "without Device Password");
8110                 wpa_s->p2p_oob_dev_pw_id = DEV_PW_NFC_CONNECTION_HANDOVER;
8111         }
8112
8113         switch (params.next_step) {
8114         case NO_ACTION:
8115         case BOTH_GO:
8116         case PEER_CLIENT:
8117                 /* already covered above */
8118                 return 0;
8119         case JOIN_GROUP:
8120                 return wpas_p2p_nfc_join_group(wpa_s, &params);
8121         case AUTH_JOIN:
8122                 return wpas_p2p_nfc_auth_join(wpa_s, &params, tag);
8123         case INIT_GO_NEG:
8124                 return wpas_p2p_nfc_init_go_neg(wpa_s, &params, forced_freq);
8125         case RESP_GO_NEG:
8126                 /* TODO: use own OOB Dev Pw */
8127                 return wpas_p2p_nfc_resp_go_neg(wpa_s, &params, forced_freq);
8128         }
8129
8130         return -1;
8131 }
8132
8133
8134 int wpas_p2p_nfc_tag_process(struct wpa_supplicant *wpa_s,
8135                              const struct wpabuf *data, int forced_freq)
8136 {
8137         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
8138                 return -1;
8139
8140         return wpas_p2p_nfc_connection_handover(wpa_s, data, 1, 1, forced_freq);
8141 }
8142
8143
8144 int wpas_p2p_nfc_report_handover(struct wpa_supplicant *wpa_s, int init,
8145                                  const struct wpabuf *req,
8146                                  const struct wpabuf *sel, int forced_freq)
8147 {
8148         struct wpabuf *tmp;
8149         int ret;
8150
8151         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
8152                 return -1;
8153
8154         wpa_printf(MSG_DEBUG, "NFC: P2P connection handover reported");
8155
8156         wpa_hexdump_ascii(MSG_DEBUG, "NFC: Req",
8157                           wpabuf_head(req), wpabuf_len(req));
8158         wpa_hexdump_ascii(MSG_DEBUG, "NFC: Sel",
8159                           wpabuf_head(sel), wpabuf_len(sel));
8160         if (forced_freq)
8161                 wpa_printf(MSG_DEBUG, "NFC: Forced freq %d", forced_freq);
8162         tmp = ndef_parse_p2p(init ? sel : req);
8163         if (tmp == NULL) {
8164                 wpa_printf(MSG_DEBUG, "P2P: Could not parse NDEF");
8165                 return -1;
8166         }
8167
8168         ret = wpas_p2p_nfc_connection_handover(wpa_s, tmp, init, 0,
8169                                                forced_freq);
8170         wpabuf_free(tmp);
8171
8172         return ret;
8173 }
8174
8175
8176 int wpas_p2p_nfc_tag_enabled(struct wpa_supplicant *wpa_s, int enabled)
8177 {
8178         const u8 *if_addr;
8179         int go_intent = wpa_s->conf->p2p_go_intent;
8180         struct wpa_supplicant *iface;
8181
8182         if (wpa_s->global->p2p == NULL)
8183                 return -1;
8184
8185         if (!enabled) {
8186                 wpa_printf(MSG_DEBUG, "P2P: Disable use of own NFC Tag");
8187                 for (iface = wpa_s->global->ifaces; iface; iface = iface->next)
8188                 {
8189                         if (!iface->ap_iface)
8190                                 continue;
8191                         hostapd_wps_nfc_token_disable(iface->ap_iface->bss[0]);
8192                 }
8193                 p2p_set_authorized_oob_dev_pw_id(wpa_s->global->p2p, 0,
8194                                                  0, NULL);
8195                 if (wpa_s->p2p_nfc_tag_enabled)
8196                         wpas_p2p_remove_pending_group_interface(wpa_s);
8197                 wpa_s->p2p_nfc_tag_enabled = 0;
8198                 return 0;
8199         }
8200
8201         if (wpa_s->global->p2p_disabled)
8202                 return -1;
8203
8204         if (wpa_s->conf->wps_nfc_dh_pubkey == NULL ||
8205             wpa_s->conf->wps_nfc_dh_privkey == NULL ||
8206             wpa_s->conf->wps_nfc_dev_pw == NULL ||
8207             wpa_s->conf->wps_nfc_dev_pw_id < 0x10) {
8208                 wpa_printf(MSG_DEBUG, "P2P: NFC password token not configured "
8209                            "to allow static handover cases");
8210                 return -1;
8211         }
8212
8213         wpa_printf(MSG_DEBUG, "P2P: Enable use of own NFC Tag");
8214
8215         wpa_s->p2p_oob_dev_pw_id = wpa_s->conf->wps_nfc_dev_pw_id;
8216         wpabuf_free(wpa_s->p2p_oob_dev_pw);
8217         wpa_s->p2p_oob_dev_pw = wpabuf_dup(wpa_s->conf->wps_nfc_dev_pw);
8218         if (wpa_s->p2p_oob_dev_pw == NULL)
8219                 return -1;
8220         wpa_s->p2p_peer_oob_pk_hash_known = 0;
8221
8222         if (wpa_s->p2p_group_interface == P2P_GROUP_INTERFACE_GO ||
8223             wpa_s->p2p_group_interface == P2P_GROUP_INTERFACE_CLIENT) {
8224                 /*
8225                  * P2P Group Interface present and the command came on group
8226                  * interface, so enable the token for the current interface.
8227                  */
8228                 wpa_s->create_p2p_iface = 0;
8229         } else {
8230                 wpa_s->create_p2p_iface = wpas_p2p_create_iface(wpa_s);
8231         }
8232
8233         if (wpa_s->create_p2p_iface) {
8234                 enum wpa_driver_if_type iftype;
8235                 /* Prepare to add a new interface for the group */
8236                 iftype = WPA_IF_P2P_GROUP;
8237                 if (go_intent == 15)
8238                         iftype = WPA_IF_P2P_GO;
8239                 if (wpas_p2p_add_group_interface(wpa_s, iftype) < 0) {
8240                         wpa_printf(MSG_ERROR, "P2P: Failed to allocate a new "
8241                                    "interface for the group");
8242                         return -1;
8243                 }
8244
8245                 if_addr = wpa_s->pending_interface_addr;
8246         } else
8247                 if_addr = wpa_s->own_addr;
8248
8249         wpa_s->p2p_nfc_tag_enabled = enabled;
8250
8251         for (iface = wpa_s->global->ifaces; iface; iface = iface->next) {
8252                 struct hostapd_data *hapd;
8253                 if (iface->ap_iface == NULL)
8254                         continue;
8255                 hapd = iface->ap_iface->bss[0];
8256                 wpabuf_free(hapd->conf->wps_nfc_dh_pubkey);
8257                 hapd->conf->wps_nfc_dh_pubkey =
8258                         wpabuf_dup(wpa_s->conf->wps_nfc_dh_pubkey);
8259                 wpabuf_free(hapd->conf->wps_nfc_dh_privkey);
8260                 hapd->conf->wps_nfc_dh_privkey =
8261                         wpabuf_dup(wpa_s->conf->wps_nfc_dh_privkey);
8262                 wpabuf_free(hapd->conf->wps_nfc_dev_pw);
8263                 hapd->conf->wps_nfc_dev_pw =
8264                         wpabuf_dup(wpa_s->conf->wps_nfc_dev_pw);
8265                 hapd->conf->wps_nfc_dev_pw_id = wpa_s->conf->wps_nfc_dev_pw_id;
8266
8267                 if (hostapd_wps_nfc_token_enable(iface->ap_iface->bss[0]) < 0) {
8268                         wpa_dbg(iface, MSG_DEBUG,
8269                                 "P2P: Failed to enable NFC Tag for GO");
8270                 }
8271         }
8272         p2p_set_authorized_oob_dev_pw_id(
8273                 wpa_s->global->p2p, wpa_s->conf->wps_nfc_dev_pw_id, go_intent,
8274                 if_addr);
8275
8276         return 0;
8277 }
8278
8279 #endif /* CONFIG_WPS_NFC */
8280
8281
8282 static void wpas_p2p_optimize_listen_channel(struct wpa_supplicant *wpa_s,
8283                                              struct wpa_used_freq_data *freqs,
8284                                              unsigned int num)
8285 {
8286         u8 curr_chan, cand, chan;
8287         unsigned int i;
8288
8289         curr_chan = p2p_get_listen_channel(wpa_s->global->p2p);
8290         for (i = 0, cand = 0; i < num; i++) {
8291                 ieee80211_freq_to_chan(freqs[i].freq, &chan);
8292                 if (curr_chan == chan) {
8293                         cand = 0;
8294                         break;
8295                 }
8296
8297                 if (chan == 1 || chan == 6 || chan == 11)
8298                         cand = chan;
8299         }
8300
8301         if (cand) {
8302                 wpa_dbg(wpa_s, MSG_DEBUG,
8303                         "P2P: Update Listen channel to %u based on operating channel",
8304                         cand);
8305                 p2p_set_listen_channel(wpa_s->global->p2p, 81, cand, 0);
8306         }
8307 }
8308
8309
8310 static int wpas_p2p_move_go_csa(struct wpa_supplicant *wpa_s)
8311 {
8312         if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_AP_CSA)) {
8313                 wpa_dbg(wpa_s, MSG_DEBUG, "CSA is not enabled");
8314                 return -1;
8315         }
8316
8317         /* TODO: Add CSA support */
8318         wpa_dbg(wpa_s, MSG_DEBUG, "Moving GO with CSA is not implemented");
8319         return -1;
8320 }
8321
8322
8323 static void wpas_p2p_move_go_no_csa(struct wpa_supplicant *wpa_s)
8324 {
8325         struct p2p_go_neg_results params;
8326         struct wpa_ssid *current_ssid = wpa_s->current_ssid;
8327
8328         wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_REMOVE_AND_REFORM_GROUP);
8329
8330         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Move GO from freq=%d MHz",
8331                 current_ssid->frequency);
8332
8333         /* Stop the AP functionality */
8334         /* TODO: Should do this in a way that does not indicated to possible
8335          * P2P Clients in the group that the group is terminated. */
8336         wpa_supplicant_ap_deinit(wpa_s);
8337
8338         /* Reselect the GO frequency */
8339         if (wpas_p2p_init_go_params(wpa_s, &params, 0, 0, 0, NULL)) {
8340                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Failed to reselect freq");
8341                 wpas_p2p_group_delete(wpa_s,
8342                                       P2P_GROUP_REMOVAL_GO_LEAVE_CHANNEL);
8343                 return;
8344         }
8345         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: New freq selected for the GO (%u MHz)",
8346                 params.freq);
8347
8348         if (params.freq &&
8349             !p2p_supported_freq_go(wpa_s->global->p2p, params.freq)) {
8350                 wpa_printf(MSG_DEBUG,
8351                            "P2P: Selected freq (%u MHz) is not valid for P2P",
8352                            params.freq);
8353                 wpas_p2p_group_delete(wpa_s,
8354                                       P2P_GROUP_REMOVAL_GO_LEAVE_CHANNEL);
8355                 return;
8356         }
8357
8358         /* Update the frequency */
8359         current_ssid->frequency = params.freq;
8360         wpa_s->connect_without_scan = current_ssid;
8361         wpa_s->reassociate = 1;
8362         wpa_s->disconnected = 0;
8363         wpa_supplicant_req_scan(wpa_s, 0, 0);
8364 }
8365
8366
8367 static void wpas_p2p_move_go(void *eloop_ctx, void *timeout_ctx)
8368 {
8369         struct wpa_supplicant *wpa_s = eloop_ctx;
8370
8371         if (!wpa_s->ap_iface || !wpa_s->current_ssid)
8372                 return;
8373
8374         wpas_p2p_go_update_common_freqs(wpa_s);
8375
8376         /*
8377          * First, try a channel switch flow. If it is not supported or fails,
8378          * take down the GO and bring it up again.
8379          */
8380         if (wpas_p2p_move_go_csa(wpa_s) < 0)
8381                 wpas_p2p_move_go_no_csa(wpa_s);
8382 }
8383
8384
8385 /*
8386  * Consider moving a GO from its currently used frequency:
8387  * 1. It is possible that due to regulatory consideration the frequency
8388  *    can no longer be used and there is a need to evacuate the GO.
8389  * 2. It is possible that due to MCC considerations, it would be preferable
8390  *    to move the GO to a channel that is currently used by some other
8391  *    station interface.
8392  *
8393  * In case a frequency that became invalid is once again valid, cancel a
8394  * previously initiated GO frequency change.
8395  */
8396 static void wpas_p2p_consider_moving_one_go(struct wpa_supplicant *wpa_s,
8397                                             struct wpa_used_freq_data *freqs,
8398                                             unsigned int num)
8399 {
8400         unsigned int i, invalid_freq = 0, policy_move = 0, flags = 0;
8401         unsigned int timeout;
8402         int freq;
8403
8404         wpas_p2p_go_update_common_freqs(wpa_s);
8405
8406         freq = wpa_s->current_ssid->frequency;
8407         for (i = 0, invalid_freq = 0; i < num; i++) {
8408                 if (freqs[i].freq == freq) {
8409                         flags = freqs[i].flags;
8410
8411                         /* The channel is invalid, must change it */
8412                         if (!p2p_supported_freq_go(wpa_s->global->p2p, freq)) {
8413                                 wpa_dbg(wpa_s, MSG_DEBUG,
8414                                         "P2P: Freq=%d MHz no longer valid for GO",
8415                                         freq);
8416                                 invalid_freq = 1;
8417                         }
8418                 } else if (freqs[i].flags == 0) {
8419                         /* Freq is not used by any other station interface */
8420                         continue;
8421                 } else if (!p2p_supported_freq(wpa_s->global->p2p,
8422                                                freqs[i].freq)) {
8423                         /* Freq is not valid for P2P use cases */
8424                         continue;
8425                 } else if (wpa_s->conf->p2p_go_freq_change_policy ==
8426                            P2P_GO_FREQ_MOVE_SCM) {
8427                         policy_move = 1;
8428                 } else if (wpa_s->conf->p2p_go_freq_change_policy ==
8429                            P2P_GO_FREQ_MOVE_SCM_PEER_SUPPORTS &&
8430                            wpas_p2p_go_is_peer_freq(wpa_s, freqs[i].freq)) {
8431                         policy_move = 1;
8432                 }
8433         }
8434
8435         wpa_dbg(wpa_s, MSG_DEBUG,
8436                 "P2P: GO move: invalid_freq=%u, policy_move=%u, flags=0x%X",
8437                 invalid_freq, policy_move, flags);
8438
8439         /*
8440          * The channel is valid, or we are going to have a policy move, so
8441          * cancel timeout.
8442          */
8443         if (!invalid_freq || policy_move) {
8444                 wpa_dbg(wpa_s, MSG_DEBUG,
8445                         "P2P: Cancel a GO move from freq=%d MHz", freq);
8446                 eloop_cancel_timeout(wpas_p2p_move_go, wpa_s, NULL);
8447         }
8448
8449         if (!invalid_freq && (!policy_move || flags != 0)) {
8450                 wpa_dbg(wpa_s, MSG_DEBUG,
8451                         "P2P: Not initiating a GO frequency change");
8452                 return;
8453         }
8454
8455         if (invalid_freq && !wpas_p2p_disallowed_freq(wpa_s->global, freq))
8456                 timeout = P2P_GO_FREQ_CHANGE_TIME;
8457         else
8458                 timeout = 0;
8459
8460         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Move GO from freq=%d MHz in %d secs",
8461                 freq, timeout);
8462         eloop_cancel_timeout(wpas_p2p_move_go, wpa_s, NULL);
8463         eloop_register_timeout(timeout, 0, wpas_p2p_move_go, wpa_s, NULL);
8464 }
8465
8466
8467 static void wpas_p2p_consider_moving_gos(struct wpa_supplicant *wpa_s,
8468                                          struct wpa_used_freq_data *freqs,
8469                                          unsigned int num)
8470 {
8471         struct wpa_supplicant *ifs;
8472
8473         /*
8474          * Travers all the radio interfaces, and for each GO interface, check
8475          * if there is a need to move the GO from the frequency it is using,
8476          * or in case the frequency is valid again, cancel the evacuation flow.
8477          */
8478         dl_list_for_each(ifs, &wpa_s->radio->ifaces, struct wpa_supplicant,
8479                          radio_list) {
8480                 if (ifs->current_ssid == NULL ||
8481                     ifs->current_ssid->mode != WPAS_MODE_P2P_GO)
8482                         continue;
8483
8484                 wpas_p2p_consider_moving_one_go(ifs, freqs, num);
8485         }
8486 }
8487
8488
8489 void wpas_p2p_indicate_state_change(struct wpa_supplicant *wpa_s)
8490 {
8491         struct wpa_used_freq_data *freqs;
8492         unsigned int num = wpa_s->num_multichan_concurrent;
8493
8494         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
8495                 return;
8496
8497         /*
8498          * If possible, optimize the Listen channel to be a channel that is
8499          * already used by one of the other interfaces.
8500          */
8501         if (!wpa_s->conf->p2p_optimize_listen_chan)
8502                 return;
8503
8504         if (!wpa_s->current_ssid || wpa_s->wpa_state != WPA_COMPLETED)
8505                 return;
8506
8507         freqs = os_calloc(num, sizeof(struct wpa_used_freq_data));
8508         if (!freqs)
8509                 return;
8510
8511         num = get_shared_radio_freqs_data(wpa_s, freqs, num);
8512
8513         wpas_p2p_optimize_listen_channel(wpa_s, freqs, num);
8514
8515         /*
8516          * The used frequencies map changed, so it is possible that a GO is
8517          * using a channel that is no longer valid for P2P use. It is also
8518          * possible that due to policy consideration, it would be preferable to
8519          * move the group to a frequency already used by other station
8520          * interfaces.
8521          */
8522         wpas_p2p_consider_moving_gos(wpa_s, freqs, num);
8523
8524         os_free(freqs);
8525 }
8526
8527
8528 void wpas_p2p_deinit_iface(struct wpa_supplicant *wpa_s)
8529 {
8530         if (wpa_s == wpa_s->global->p2p_init_wpa_s && wpa_s->global->p2p) {
8531                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Disable P2P since removing "
8532                         "the management interface is being removed");
8533                 wpas_p2p_deinit_global(wpa_s->global);
8534         }
8535 }
8536
8537
8538 void wpas_p2p_ap_deinit(struct wpa_supplicant *wpa_s)
8539 {
8540         if (wpa_s->ap_iface->bss)
8541                 wpa_s->ap_iface->bss[0]->p2p_group = NULL;
8542         wpas_p2p_group_deinit(wpa_s);
8543 }