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