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