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