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