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