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