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