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