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