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