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