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