P2PS: Add P2PS attributes into PD Request if requested
[mech_eap.git] / wpa_supplicant / p2p_supplicant.c
1 /*
2  * wpa_supplicant - P2P
3  * Copyright (c) 2009-2010, Atheros Communications
4  * Copyright (c) 2010-2014, Jouni Malinen <j@w1.fi>
5  *
6  * This software may be distributed under the terms of the BSD license.
7  * See README for more details.
8  */
9
10 #include "includes.h"
11
12 #include "common.h"
13 #include "eloop.h"
14 #include "common/ieee802_11_common.h"
15 #include "common/ieee802_11_defs.h"
16 #include "common/wpa_ctrl.h"
17 #include "wps/wps_i.h"
18 #include "p2p/p2p.h"
19 #include "ap/hostapd.h"
20 #include "ap/ap_config.h"
21 #include "ap/sta_info.h"
22 #include "ap/ap_drv_ops.h"
23 #include "ap/wps_hostapd.h"
24 #include "ap/p2p_hostapd.h"
25 #include "eapol_supp/eapol_supp_sm.h"
26 #include "rsn_supp/wpa.h"
27 #include "wpa_supplicant_i.h"
28 #include "driver_i.h"
29 #include "ap.h"
30 #include "config_ssid.h"
31 #include "config.h"
32 #include "notify.h"
33 #include "scan.h"
34 #include "bss.h"
35 #include "offchannel.h"
36 #include "wps_supplicant.h"
37 #include "p2p_supplicant.h"
38 #include "wifi_display.h"
39
40
41 /*
42  * How many times to try to scan to find the GO before giving up on join
43  * request.
44  */
45 #define P2P_MAX_JOIN_SCAN_ATTEMPTS 10
46
47 #define P2P_AUTO_PD_SCAN_ATTEMPTS 5
48
49 #ifndef P2P_MAX_CLIENT_IDLE
50 /*
51  * How many seconds to try to reconnect to the GO when connection in P2P client
52  * role has been lost.
53  */
54 #define P2P_MAX_CLIENT_IDLE 10
55 #endif /* P2P_MAX_CLIENT_IDLE */
56
57 #ifndef P2P_MAX_INITIAL_CONN_WAIT
58 /*
59  * How many seconds to wait for initial 4-way handshake to get completed after
60  * WPS provisioning step or after the re-invocation of a persistent group on a
61  * P2P Client.
62  */
63 #define P2P_MAX_INITIAL_CONN_WAIT 10
64 #endif /* P2P_MAX_INITIAL_CONN_WAIT */
65
66 #ifndef P2P_MAX_INITIAL_CONN_WAIT_GO
67 /*
68  * How many seconds to wait for initial 4-way handshake to get completed after
69  * WPS provisioning step on the GO. This controls the extra time the P2P
70  * operation is considered to be in progress (e.g., to delay other scans) after
71  * WPS provisioning has been completed on the GO during group formation.
72  */
73 #define P2P_MAX_INITIAL_CONN_WAIT_GO 10
74 #endif /* P2P_MAX_INITIAL_CONN_WAIT_GO */
75
76 #ifndef P2P_MAX_INITIAL_CONN_WAIT_GO_REINVOKE
77 /*
78  * How many seconds to wait for initial 4-way handshake to get completed after
79  * re-invocation of a persistent group on the GO when the client is expected
80  * to connect automatically (no user interaction).
81  */
82 #define P2P_MAX_INITIAL_CONN_WAIT_GO_REINVOKE 15
83 #endif /* P2P_MAX_INITIAL_CONN_WAIT_GO_REINVOKE */
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         P2P_GROUP_REMOVAL_FREQ_CONFLICT
97 };
98
99
100 static void wpas_p2p_long_listen_timeout(void *eloop_ctx, void *timeout_ctx);
101 static struct wpa_supplicant *
102 wpas_p2p_get_group_iface(struct wpa_supplicant *wpa_s, int addr_allocated,
103                          int go);
104 static int wpas_p2p_join_start(struct wpa_supplicant *wpa_s, int freq,
105                                const u8 *ssid, size_t ssid_len);
106 static void wpas_p2p_join_scan_req(struct wpa_supplicant *wpa_s, int freq,
107                                    const u8 *ssid, size_t ssid_len);
108 static void wpas_p2p_join_scan(void *eloop_ctx, void *timeout_ctx);
109 static int wpas_p2p_join(struct wpa_supplicant *wpa_s, const u8 *iface_addr,
110                          const u8 *dev_addr, enum p2p_wps_method wps_method,
111                          int auto_join, int freq,
112                          const u8 *ssid, size_t ssid_len);
113 static int wpas_p2p_create_iface(struct wpa_supplicant *wpa_s);
114 static void wpas_p2p_cross_connect_setup(struct wpa_supplicant *wpa_s);
115 static void wpas_p2p_group_idle_timeout(void *eloop_ctx, void *timeout_ctx);
116 static void wpas_p2p_set_group_idle_timeout(struct wpa_supplicant *wpa_s);
117 static void wpas_p2p_group_formation_timeout(void *eloop_ctx,
118                                              void *timeout_ctx);
119 static void wpas_p2p_group_freq_conflict(void *eloop_ctx, void *timeout_ctx);
120 static void wpas_p2p_fallback_to_go_neg(struct wpa_supplicant *wpa_s,
121                                         int group_added);
122 static void wpas_p2p_stop_find_oper(struct wpa_supplicant *wpa_s);
123 static void wpas_stop_listen(void *ctx);
124 static void wpas_p2p_psk_failure_removal(void *eloop_ctx, void *timeout_ctx);
125 static void wpas_p2p_group_deinit(struct wpa_supplicant *wpa_s);
126
127
128 /*
129  * Get the number of concurrent channels that the HW can operate, but that are
130  * currently not in use by any of the wpa_supplicant interfaces.
131  */
132 static int wpas_p2p_num_unused_channels(struct wpa_supplicant *wpa_s)
133 {
134         int *freqs;
135         int num, unused;
136
137         freqs = os_calloc(wpa_s->num_multichan_concurrent, sizeof(int));
138         if (!freqs)
139                 return -1;
140
141         num = get_shared_radio_freqs(wpa_s, freqs,
142                                      wpa_s->num_multichan_concurrent);
143         os_free(freqs);
144
145         unused = wpa_s->num_multichan_concurrent - num;
146         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: num_unused_channels: %d", unused);
147         return unused;
148 }
149
150
151 /*
152  * Get the frequencies that are currently in use by one or more of the virtual
153  * interfaces, and that are also valid for P2P operation.
154  */
155 static unsigned int
156 wpas_p2p_valid_oper_freqs(struct wpa_supplicant *wpa_s,
157                           struct wpa_used_freq_data *p2p_freqs,
158                           unsigned int len)
159 {
160         struct wpa_used_freq_data *freqs;
161         unsigned int num, i, j;
162
163         freqs = os_calloc(wpa_s->num_multichan_concurrent,
164                           sizeof(struct wpa_used_freq_data));
165         if (!freqs)
166                 return 0;
167
168         num = get_shared_radio_freqs_data(wpa_s, freqs,
169                                           wpa_s->num_multichan_concurrent);
170
171         os_memset(p2p_freqs, 0, sizeof(struct wpa_used_freq_data) * len);
172
173         for (i = 0, j = 0; i < num && j < len; i++) {
174                 if (p2p_supported_freq(wpa_s->global->p2p, freqs[i].freq))
175                         p2p_freqs[j++] = freqs[i];
176         }
177
178         os_free(freqs);
179
180         dump_freq_data(wpa_s, "valid for P2P", p2p_freqs, j);
181
182         return j;
183 }
184
185
186 static void wpas_p2p_set_own_freq_preference(struct wpa_supplicant *wpa_s,
187                                              int freq)
188 {
189         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
190                 return;
191         if (wpa_s->parent->conf->p2p_ignore_shared_freq &&
192             freq > 0 && wpa_s->num_multichan_concurrent > 1 &&
193             wpas_p2p_num_unused_channels(wpa_s) > 0) {
194                 wpa_printf(MSG_DEBUG, "P2P: Ignore own channel preference %d MHz due to p2p_ignore_shared_freq=1 configuration",
195                            freq);
196                 freq = 0;
197         }
198         p2p_set_own_freq_preference(wpa_s->global->p2p, freq);
199 }
200
201
202 static void wpas_p2p_scan_res_handler(struct wpa_supplicant *wpa_s,
203                                       struct wpa_scan_results *scan_res)
204 {
205         size_t i;
206
207         if (wpa_s->p2p_scan_work) {
208                 struct wpa_radio_work *work = wpa_s->p2p_scan_work;
209                 wpa_s->p2p_scan_work = NULL;
210                 radio_work_done(work);
211         }
212
213         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
214                 return;
215
216         wpa_printf(MSG_DEBUG, "P2P: Scan results received (%d BSS)",
217                    (int) scan_res->num);
218
219         for (i = 0; i < scan_res->num; i++) {
220                 struct wpa_scan_res *bss = scan_res->res[i];
221                 struct os_reltime time_tmp_age, entry_ts;
222                 const u8 *ies;
223                 size_t ies_len;
224
225                 time_tmp_age.sec = bss->age / 1000;
226                 time_tmp_age.usec = (bss->age % 1000) * 1000;
227                 os_reltime_sub(&scan_res->fetch_time, &time_tmp_age, &entry_ts);
228
229                 ies = (const u8 *) (bss + 1);
230                 ies_len = bss->ie_len;
231                 if (bss->beacon_ie_len > 0 &&
232                     !wpa_scan_get_vendor_ie(bss, P2P_IE_VENDOR_TYPE) &&
233                     wpa_scan_get_vendor_ie_beacon(bss, P2P_IE_VENDOR_TYPE)) {
234                         wpa_printf(MSG_DEBUG, "P2P: Use P2P IE(s) from Beacon frame since no P2P IE(s) in Probe Response frames received for "
235                                    MACSTR, MAC2STR(bss->bssid));
236                         ies = ies + ies_len;
237                         ies_len = bss->beacon_ie_len;
238                 }
239
240
241                 if (p2p_scan_res_handler(wpa_s->global->p2p, bss->bssid,
242                                          bss->freq, &entry_ts, bss->level,
243                                          ies, ies_len) > 0)
244                         break;
245         }
246
247         p2p_scan_res_handled(wpa_s->global->p2p);
248 }
249
250
251 static void wpas_p2p_trigger_scan_cb(struct wpa_radio_work *work, int deinit)
252 {
253         struct wpa_supplicant *wpa_s = work->wpa_s;
254         struct wpa_driver_scan_params *params = work->ctx;
255         int ret;
256
257         if (deinit) {
258                 if (!work->started) {
259                         wpa_scan_free_params(params);
260                         return;
261                 }
262
263                 wpa_s->p2p_scan_work = NULL;
264                 return;
265         }
266
267         ret = wpa_drv_scan(wpa_s, params);
268         wpa_scan_free_params(params);
269         work->ctx = NULL;
270         if (ret) {
271                 radio_work_done(work);
272                 p2p_notify_scan_trigger_status(wpa_s->global->p2p, ret);
273                 return;
274         }
275
276         p2p_notify_scan_trigger_status(wpa_s->global->p2p, ret);
277         os_get_reltime(&wpa_s->scan_trigger_time);
278         wpa_s->scan_res_handler = wpas_p2p_scan_res_handler;
279         wpa_s->own_scan_requested = 1;
280         wpa_s->p2p_scan_work = work;
281 }
282
283
284 static int wpas_p2p_search_social_channel(struct wpa_supplicant *wpa_s,
285                                           int freq)
286 {
287         if (wpa_s->global->p2p_24ghz_social_channels &&
288             (freq == 2412 || freq == 2437 || freq == 2462)) {
289                 /*
290                  * Search all social channels regardless of whether these have
291                  * been disabled for P2P operating channel use to avoid missing
292                  * peers.
293                  */
294                 return 1;
295         }
296         return p2p_supported_freq(wpa_s->global->p2p, freq);
297 }
298
299
300 static int wpas_p2p_scan(void *ctx, enum p2p_scan_type type, int freq,
301                          unsigned int num_req_dev_types,
302                          const u8 *req_dev_types, const u8 *dev_id, u16 pw_id)
303 {
304         struct wpa_supplicant *wpa_s = ctx;
305         struct wpa_driver_scan_params *params = NULL;
306         struct wpabuf *wps_ie, *ies;
307         unsigned int num_channels = 0;
308         int social_channels_freq[] = { 2412, 2437, 2462, 60480 };
309         size_t ielen;
310         u8 *n, i;
311
312         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
313                 return -1;
314
315         if (wpa_s->p2p_scan_work) {
316                 wpa_dbg(wpa_s, MSG_INFO, "P2P: Reject scan trigger since one is already pending");
317                 return -1;
318         }
319
320         params = os_zalloc(sizeof(*params));
321         if (params == NULL)
322                 return -1;
323
324         /* P2P Wildcard SSID */
325         params->num_ssids = 1;
326         n = os_malloc(P2P_WILDCARD_SSID_LEN);
327         if (n == NULL)
328                 goto fail;
329         os_memcpy(n, P2P_WILDCARD_SSID, P2P_WILDCARD_SSID_LEN);
330         params->ssids[0].ssid = n;
331         params->ssids[0].ssid_len = P2P_WILDCARD_SSID_LEN;
332
333         wpa_s->wps->dev.p2p = 1;
334         wps_ie = wps_build_probe_req_ie(pw_id, &wpa_s->wps->dev,
335                                         wpa_s->wps->uuid, WPS_REQ_ENROLLEE,
336                                         num_req_dev_types, req_dev_types);
337         if (wps_ie == NULL)
338                 goto fail;
339
340         ielen = p2p_scan_ie_buf_len(wpa_s->global->p2p);
341         ies = wpabuf_alloc(wpabuf_len(wps_ie) + ielen);
342         if (ies == NULL) {
343                 wpabuf_free(wps_ie);
344                 goto fail;
345         }
346         wpabuf_put_buf(ies, wps_ie);
347         wpabuf_free(wps_ie);
348
349         p2p_scan_ie(wpa_s->global->p2p, ies, dev_id);
350
351         params->p2p_probe = 1;
352         n = os_malloc(wpabuf_len(ies));
353         if (n == NULL) {
354                 wpabuf_free(ies);
355                 goto fail;
356         }
357         os_memcpy(n, wpabuf_head(ies), wpabuf_len(ies));
358         params->extra_ies = n;
359         params->extra_ies_len = wpabuf_len(ies);
360         wpabuf_free(ies);
361
362         switch (type) {
363         case P2P_SCAN_SOCIAL:
364                 params->freqs = os_calloc(ARRAY_SIZE(social_channels_freq) + 1,
365                                           sizeof(int));
366                 if (params->freqs == NULL)
367                         goto fail;
368                 for (i = 0; i < ARRAY_SIZE(social_channels_freq); i++) {
369                         if (wpas_p2p_search_social_channel(
370                                     wpa_s, social_channels_freq[i]))
371                                 params->freqs[num_channels++] =
372                                         social_channels_freq[i];
373                 }
374                 params->freqs[num_channels++] = 0;
375                 break;
376         case P2P_SCAN_FULL:
377                 break;
378         case P2P_SCAN_SOCIAL_PLUS_ONE:
379                 params->freqs = os_calloc(ARRAY_SIZE(social_channels_freq) + 2,
380                                           sizeof(int));
381                 if (params->freqs == NULL)
382                         goto fail;
383                 for (i = 0; i < ARRAY_SIZE(social_channels_freq); i++) {
384                         if (wpas_p2p_search_social_channel(
385                                     wpa_s, social_channels_freq[i]))
386                                 params->freqs[num_channels++] =
387                                         social_channels_freq[i];
388                 }
389                 if (p2p_supported_freq(wpa_s->global->p2p, freq))
390                         params->freqs[num_channels++] = freq;
391                 params->freqs[num_channels++] = 0;
392                 break;
393         }
394
395         radio_remove_works(wpa_s, "p2p-scan", 0);
396         if (radio_add_work(wpa_s, 0, "p2p-scan", 0, wpas_p2p_trigger_scan_cb,
397                            params) < 0)
398                 goto fail;
399         return 0;
400
401 fail:
402         wpa_scan_free_params(params);
403         return -1;
404 }
405
406
407 static enum wpa_driver_if_type wpas_p2p_if_type(int p2p_group_interface)
408 {
409         switch (p2p_group_interface) {
410         case P2P_GROUP_INTERFACE_PENDING:
411                 return WPA_IF_P2P_GROUP;
412         case P2P_GROUP_INTERFACE_GO:
413                 return WPA_IF_P2P_GO;
414         case P2P_GROUP_INTERFACE_CLIENT:
415                 return WPA_IF_P2P_CLIENT;
416         }
417
418         return WPA_IF_P2P_GROUP;
419 }
420
421
422 static struct wpa_supplicant * wpas_get_p2p_group(struct wpa_supplicant *wpa_s,
423                                                   const u8 *ssid,
424                                                   size_t ssid_len, int *go)
425 {
426         struct wpa_ssid *s;
427
428         for (wpa_s = wpa_s->global->ifaces; wpa_s; wpa_s = wpa_s->next) {
429                 for (s = wpa_s->conf->ssid; s; s = s->next) {
430                         if (s->disabled != 0 || !s->p2p_group ||
431                             s->ssid_len != ssid_len ||
432                             os_memcmp(ssid, s->ssid, ssid_len) != 0)
433                                 continue;
434                         if (s->mode == WPAS_MODE_P2P_GO &&
435                             s != wpa_s->current_ssid)
436                                 continue;
437                         if (go)
438                                 *go = s->mode == WPAS_MODE_P2P_GO;
439                         return wpa_s;
440                 }
441         }
442
443         return NULL;
444 }
445
446
447 static void run_wpas_p2p_disconnect(void *eloop_ctx, void *timeout_ctx)
448 {
449         struct wpa_supplicant *wpa_s = eloop_ctx;
450         wpa_printf(MSG_DEBUG,
451                    "P2P: Complete previously requested removal of %s",
452                    wpa_s->ifname);
453         wpas_p2p_disconnect(wpa_s);
454 }
455
456
457 static int wpas_p2p_disconnect_safely(struct wpa_supplicant *wpa_s,
458                                       struct wpa_supplicant *calling_wpa_s)
459 {
460         if (calling_wpa_s == wpa_s && wpa_s &&
461             wpa_s->p2p_group_interface != NOT_P2P_GROUP_INTERFACE) {
462                 /*
463                  * The calling wpa_s instance is going to be removed. Do that
464                  * from an eloop callback to keep the instance available until
465                  * the caller has returned. This my be needed, e.g., to provide
466                  * control interface responses on the per-interface socket.
467                  */
468                 if (eloop_register_timeout(0, 0, run_wpas_p2p_disconnect,
469                                            wpa_s, NULL) < 0)
470                         return -1;
471                 return 0;
472         }
473
474         return wpas_p2p_disconnect(wpa_s);
475 }
476
477
478 /* Find an active P2P group where we are the GO */
479 static struct wpa_ssid * wpas_p2p_group_go_ssid(struct wpa_supplicant *wpa_s,
480                                                 u8 *bssid)
481 {
482         struct wpa_ssid *s, *empty = NULL;
483
484         if (!wpa_s)
485                 return 0;
486
487         for (wpa_s = wpa_s->global->ifaces; wpa_s; wpa_s = wpa_s->next) {
488                 for (s = wpa_s->conf->ssid; s; s = s->next) {
489                         if (s->disabled || !s->p2p_group ||
490                             s->mode != WPAS_MODE_P2P_GO)
491                                 continue;
492
493                         os_memcpy(bssid, wpa_s->own_addr, ETH_ALEN);
494                         if (p2p_get_group_num_members(wpa_s->p2p_group))
495                                 return s;
496                         empty = s;
497                 }
498         }
499
500         return empty;
501 }
502
503
504 /* Find a persistent group where we are the GO */
505 static struct wpa_ssid *
506 wpas_p2p_get_persistent_go(struct wpa_supplicant *wpa_s)
507 {
508         struct wpa_ssid *s;
509
510         for (s = wpa_s->conf->ssid; s; s = s->next) {
511                 if (s->disabled == 2 && s->mode == WPAS_MODE_P2P_GO)
512                         return s;
513         }
514
515         return NULL;
516 }
517
518
519 static int wpas_p2p_group_delete(struct wpa_supplicant *wpa_s,
520                                  enum p2p_group_removal_reason removal_reason)
521 {
522         struct wpa_ssid *ssid;
523         char *gtype;
524         const char *reason;
525
526         ssid = wpa_s->current_ssid;
527         if (ssid == NULL) {
528                 /*
529                  * The current SSID was not known, but there may still be a
530                  * pending P2P group interface waiting for provisioning or a
531                  * P2P group that is trying to reconnect.
532                  */
533                 ssid = wpa_s->conf->ssid;
534                 while (ssid) {
535                         if (ssid->p2p_group && ssid->disabled != 2)
536                                 break;
537                         ssid = ssid->next;
538                 }
539                 if (ssid == NULL &&
540                         wpa_s->p2p_group_interface == NOT_P2P_GROUP_INTERFACE)
541                 {
542                         wpa_printf(MSG_ERROR, "P2P: P2P group interface "
543                                    "not found");
544                         return -1;
545                 }
546         }
547         if (wpa_s->p2p_group_interface == P2P_GROUP_INTERFACE_GO)
548                 gtype = "GO";
549         else if (wpa_s->p2p_group_interface == P2P_GROUP_INTERFACE_CLIENT ||
550                  (ssid && ssid->mode == WPAS_MODE_INFRA)) {
551                 wpa_s->reassociate = 0;
552                 wpa_s->disconnected = 1;
553                 gtype = "client";
554         } else
555                 gtype = "GO";
556
557         if (removal_reason != P2P_GROUP_REMOVAL_SILENT && ssid)
558                 wpas_notify_p2p_group_removed(wpa_s, ssid, gtype);
559
560         if (os_strcmp(gtype, "client") == 0) {
561                 wpa_supplicant_deauthenticate(wpa_s, WLAN_REASON_DEAUTH_LEAVING);
562                 if (eloop_is_timeout_registered(wpas_p2p_psk_failure_removal,
563                                                 wpa_s, NULL)) {
564                         wpa_printf(MSG_DEBUG,
565                                    "P2P: PSK failure removal was scheduled, so use PSK failure as reason for group removal");
566                         removal_reason = P2P_GROUP_REMOVAL_PSK_FAILURE;
567                         eloop_cancel_timeout(wpas_p2p_psk_failure_removal,
568                                              wpa_s, NULL);
569                 }
570         }
571
572         if (wpa_s->cross_connect_in_use) {
573                 wpa_s->cross_connect_in_use = 0;
574                 wpa_msg_global(wpa_s->parent, MSG_INFO,
575                                P2P_EVENT_CROSS_CONNECT_DISABLE "%s %s",
576                                wpa_s->ifname, wpa_s->cross_connect_uplink);
577         }
578         switch (removal_reason) {
579         case P2P_GROUP_REMOVAL_REQUESTED:
580                 reason = " reason=REQUESTED";
581                 break;
582         case P2P_GROUP_REMOVAL_FORMATION_FAILED:
583                 reason = " reason=FORMATION_FAILED";
584                 break;
585         case P2P_GROUP_REMOVAL_IDLE_TIMEOUT:
586                 reason = " reason=IDLE";
587                 break;
588         case P2P_GROUP_REMOVAL_UNAVAILABLE:
589                 reason = " reason=UNAVAILABLE";
590                 break;
591         case P2P_GROUP_REMOVAL_GO_ENDING_SESSION:
592                 reason = " reason=GO_ENDING_SESSION";
593                 break;
594         case P2P_GROUP_REMOVAL_PSK_FAILURE:
595                 reason = " reason=PSK_FAILURE";
596                 break;
597         case P2P_GROUP_REMOVAL_FREQ_CONFLICT:
598                 reason = " reason=FREQ_CONFLICT";
599                 break;
600         default:
601                 reason = "";
602                 break;
603         }
604         if (removal_reason != P2P_GROUP_REMOVAL_SILENT) {
605                 wpa_msg_global(wpa_s->parent, MSG_INFO,
606                                P2P_EVENT_GROUP_REMOVED "%s %s%s",
607                                wpa_s->ifname, gtype, reason);
608         }
609
610         if (eloop_cancel_timeout(wpas_p2p_group_freq_conflict, wpa_s, NULL) > 0)
611                 wpa_printf(MSG_DEBUG, "P2P: Cancelled P2P group freq_conflict timeout");
612         if (eloop_cancel_timeout(wpas_p2p_group_idle_timeout, wpa_s, NULL) > 0)
613                 wpa_printf(MSG_DEBUG, "P2P: Cancelled P2P group idle timeout");
614         if (eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
615                                  wpa_s->parent, NULL) > 0) {
616                 wpa_printf(MSG_DEBUG, "P2P: Cancelled P2P group formation "
617                            "timeout");
618                 wpa_s->p2p_in_provisioning = 0;
619         }
620
621         wpa_s->p2p_in_invitation = 0;
622
623         /*
624          * Make sure wait for the first client does not remain active after the
625          * group has been removed.
626          */
627         wpa_s->global->p2p_go_wait_client.sec = 0;
628
629         if (wpa_s->p2p_group_interface != NOT_P2P_GROUP_INTERFACE) {
630                 struct wpa_global *global;
631                 char *ifname;
632                 enum wpa_driver_if_type type;
633                 wpa_printf(MSG_DEBUG, "P2P: Remove group interface %s",
634                         wpa_s->ifname);
635                 global = wpa_s->global;
636                 ifname = os_strdup(wpa_s->ifname);
637                 type = wpas_p2p_if_type(wpa_s->p2p_group_interface);
638                 eloop_cancel_timeout(run_wpas_p2p_disconnect, wpa_s, NULL);
639                 wpa_supplicant_remove_iface(wpa_s->global, wpa_s, 0);
640                 wpa_s = global->ifaces;
641                 if (wpa_s && ifname)
642                         wpa_drv_if_remove(wpa_s, type, ifname);
643                 os_free(ifname);
644                 return 1;
645         }
646
647         if (!wpa_s->p2p_go_group_formation_completed) {
648                 wpa_s->global->p2p_group_formation = NULL;
649                 wpa_s->p2p_in_provisioning = 0;
650         }
651
652         wpa_s->show_group_started = 0;
653         os_free(wpa_s->go_params);
654         wpa_s->go_params = NULL;
655
656         os_free(wpa_s->p2p_group_common_freqs);
657         wpa_s->p2p_group_common_freqs = NULL;
658         wpa_s->p2p_group_common_freqs_num = 0;
659
660         wpa_s->waiting_presence_resp = 0;
661
662         wpa_printf(MSG_DEBUG, "P2P: Remove temporary group network");
663         if (ssid && (ssid->p2p_group ||
664                      ssid->mode == WPAS_MODE_P2P_GROUP_FORMATION ||
665                      (ssid->key_mgmt & WPA_KEY_MGMT_WPS))) {
666                 int id = ssid->id;
667                 if (ssid == wpa_s->current_ssid) {
668                         wpa_sm_set_config(wpa_s->wpa, NULL);
669                         eapol_sm_notify_config(wpa_s->eapol, NULL, NULL);
670                         wpa_s->current_ssid = NULL;
671                 }
672                 /*
673                  * Networks objects created during any P2P activities are not
674                  * exposed out as they might/will confuse certain non-P2P aware
675                  * applications since these network objects won't behave like
676                  * regular ones.
677                  *
678                  * Likewise, we don't send out network removed signals for such
679                  * network objects.
680                  */
681                 wpa_config_remove_network(wpa_s->conf, id);
682                 wpa_supplicant_clear_status(wpa_s);
683                 wpa_supplicant_cancel_sched_scan(wpa_s);
684         } else {
685                 wpa_printf(MSG_DEBUG, "P2P: Temporary group network not "
686                            "found");
687         }
688         if (wpa_s->ap_iface)
689                 wpa_supplicant_ap_deinit(wpa_s);
690         else
691                 wpa_drv_deinit_p2p_cli(wpa_s);
692
693         return 0;
694 }
695
696
697 static int wpas_p2p_persistent_group(struct wpa_supplicant *wpa_s,
698                                      u8 *go_dev_addr,
699                                      const u8 *ssid, size_t ssid_len)
700 {
701         struct wpa_bss *bss;
702         const u8 *bssid;
703         struct wpabuf *p2p;
704         u8 group_capab;
705         const u8 *addr;
706
707         if (wpa_s->go_params)
708                 bssid = wpa_s->go_params->peer_interface_addr;
709         else
710                 bssid = wpa_s->bssid;
711
712         bss = wpa_bss_get(wpa_s, bssid, ssid, ssid_len);
713         if (bss == NULL && wpa_s->go_params &&
714             !is_zero_ether_addr(wpa_s->go_params->peer_device_addr))
715                 bss = wpa_bss_get_p2p_dev_addr(
716                         wpa_s, wpa_s->go_params->peer_device_addr);
717         if (bss == NULL) {
718                 u8 iface_addr[ETH_ALEN];
719                 if (p2p_get_interface_addr(wpa_s->global->p2p, bssid,
720                                            iface_addr) == 0)
721                         bss = wpa_bss_get(wpa_s, iface_addr, ssid, ssid_len);
722         }
723         if (bss == NULL) {
724                 wpa_printf(MSG_DEBUG, "P2P: Could not figure out whether "
725                            "group is persistent - BSS " MACSTR " not found",
726                            MAC2STR(bssid));
727                 return 0;
728         }
729
730         p2p = wpa_bss_get_vendor_ie_multi(bss, P2P_IE_VENDOR_TYPE);
731         if (p2p == NULL)
732                 p2p = wpa_bss_get_vendor_ie_multi_beacon(bss,
733                                                          P2P_IE_VENDOR_TYPE);
734         if (p2p == NULL) {
735                 wpa_printf(MSG_DEBUG, "P2P: Could not figure out whether "
736                            "group is persistent - BSS " MACSTR
737                            " did not include P2P IE", MAC2STR(bssid));
738                 wpa_hexdump(MSG_DEBUG, "P2P: Probe Response IEs",
739                             (u8 *) (bss + 1), bss->ie_len);
740                 wpa_hexdump(MSG_DEBUG, "P2P: Beacon IEs",
741                             ((u8 *) bss + 1) + bss->ie_len,
742                             bss->beacon_ie_len);
743                 return 0;
744         }
745
746         group_capab = p2p_get_group_capab(p2p);
747         addr = p2p_get_go_dev_addr(p2p);
748         wpa_printf(MSG_DEBUG, "P2P: Checking whether group is persistent: "
749                    "group_capab=0x%x", group_capab);
750         if (addr) {
751                 os_memcpy(go_dev_addr, addr, ETH_ALEN);
752                 wpa_printf(MSG_DEBUG, "P2P: GO Device Address " MACSTR,
753                            MAC2STR(addr));
754         } else
755                 os_memset(go_dev_addr, 0, ETH_ALEN);
756         wpabuf_free(p2p);
757
758         wpa_printf(MSG_DEBUG, "P2P: BSS " MACSTR " group_capab=0x%x "
759                    "go_dev_addr=" MACSTR,
760                    MAC2STR(bssid), group_capab, MAC2STR(go_dev_addr));
761
762         return group_capab & P2P_GROUP_CAPAB_PERSISTENT_GROUP;
763 }
764
765
766 static int wpas_p2p_store_persistent_group(struct wpa_supplicant *wpa_s,
767                                            struct wpa_ssid *ssid,
768                                            const u8 *go_dev_addr)
769 {
770         struct wpa_ssid *s;
771         int changed = 0;
772
773         wpa_printf(MSG_DEBUG, "P2P: Storing credentials for a persistent "
774                    "group (GO Dev Addr " MACSTR ")", MAC2STR(go_dev_addr));
775         for (s = wpa_s->conf->ssid; s; s = s->next) {
776                 if (s->disabled == 2 &&
777                     os_memcmp(go_dev_addr, s->bssid, ETH_ALEN) == 0 &&
778                     s->ssid_len == ssid->ssid_len &&
779                     os_memcmp(ssid->ssid, s->ssid, ssid->ssid_len) == 0)
780                         break;
781         }
782
783         if (s) {
784                 wpa_printf(MSG_DEBUG, "P2P: Update existing persistent group "
785                            "entry");
786                 if (ssid->passphrase && !s->passphrase)
787                         changed = 1;
788                 else if (ssid->passphrase && s->passphrase &&
789                          os_strcmp(ssid->passphrase, s->passphrase) != 0)
790                         changed = 1;
791         } else {
792                 wpa_printf(MSG_DEBUG, "P2P: Create a new persistent group "
793                            "entry");
794                 changed = 1;
795                 s = wpa_config_add_network(wpa_s->conf);
796                 if (s == NULL)
797                         return -1;
798
799                 /*
800                  * Instead of network_added we emit persistent_group_added
801                  * notification. Also to keep the defense checks in
802                  * persistent_group obj registration method, we set the
803                  * relevant flags in s to designate it as a persistent group.
804                  */
805                 s->p2p_group = 1;
806                 s->p2p_persistent_group = 1;
807                 wpas_notify_persistent_group_added(wpa_s, s);
808                 wpa_config_set_network_defaults(s);
809         }
810
811         s->p2p_group = 1;
812         s->p2p_persistent_group = 1;
813         s->disabled = 2;
814         s->bssid_set = 1;
815         os_memcpy(s->bssid, go_dev_addr, ETH_ALEN);
816         s->mode = ssid->mode;
817         s->auth_alg = WPA_AUTH_ALG_OPEN;
818         s->key_mgmt = WPA_KEY_MGMT_PSK;
819         s->proto = WPA_PROTO_RSN;
820         s->pairwise_cipher = WPA_CIPHER_CCMP;
821         s->export_keys = 1;
822         if (ssid->passphrase) {
823                 os_free(s->passphrase);
824                 s->passphrase = os_strdup(ssid->passphrase);
825         }
826         if (ssid->psk_set) {
827                 s->psk_set = 1;
828                 os_memcpy(s->psk, ssid->psk, 32);
829         }
830         if (s->passphrase && !s->psk_set)
831                 wpa_config_update_psk(s);
832         if (s->ssid == NULL || s->ssid_len < ssid->ssid_len) {
833                 os_free(s->ssid);
834                 s->ssid = os_malloc(ssid->ssid_len);
835         }
836         if (s->ssid) {
837                 s->ssid_len = ssid->ssid_len;
838                 os_memcpy(s->ssid, ssid->ssid, s->ssid_len);
839         }
840         if (ssid->mode == WPAS_MODE_P2P_GO && wpa_s->global->add_psk) {
841                 dl_list_add(&s->psk_list, &wpa_s->global->add_psk->list);
842                 wpa_s->global->add_psk = NULL;
843                 changed = 1;
844         }
845
846         if (changed && wpa_s->conf->update_config &&
847             wpa_config_write(wpa_s->confname, wpa_s->conf)) {
848                 wpa_printf(MSG_DEBUG, "P2P: Failed to update configuration");
849         }
850
851         return s->id;
852 }
853
854
855 static void wpas_p2p_add_persistent_group_client(struct wpa_supplicant *wpa_s,
856                                                  const u8 *addr)
857 {
858         struct wpa_ssid *ssid, *s;
859         u8 *n;
860         size_t i;
861         int found = 0;
862
863         ssid = wpa_s->current_ssid;
864         if (ssid == NULL || ssid->mode != WPAS_MODE_P2P_GO ||
865             !ssid->p2p_persistent_group)
866                 return;
867
868         for (s = wpa_s->parent->conf->ssid; s; s = s->next) {
869                 if (s->disabled != 2 || s->mode != WPAS_MODE_P2P_GO)
870                         continue;
871
872                 if (s->ssid_len == ssid->ssid_len &&
873                     os_memcmp(s->ssid, ssid->ssid, s->ssid_len) == 0)
874                         break;
875         }
876
877         if (s == NULL)
878                 return;
879
880         for (i = 0; s->p2p_client_list && i < s->num_p2p_clients; i++) {
881                 if (os_memcmp(s->p2p_client_list + i * 2 * ETH_ALEN, addr,
882                               ETH_ALEN) != 0)
883                         continue;
884
885                 if (i == s->num_p2p_clients - 1)
886                         return; /* already the most recent entry */
887
888                 /* move the entry to mark it most recent */
889                 os_memmove(s->p2p_client_list + i * 2 * ETH_ALEN,
890                            s->p2p_client_list + (i + 1) * 2 * ETH_ALEN,
891                            (s->num_p2p_clients - i - 1) * 2 * ETH_ALEN);
892                 os_memcpy(s->p2p_client_list +
893                           (s->num_p2p_clients - 1) * 2 * ETH_ALEN, addr,
894                           ETH_ALEN);
895                 os_memset(s->p2p_client_list +
896                           (s->num_p2p_clients - 1) * 2 * ETH_ALEN + ETH_ALEN,
897                           0xff, ETH_ALEN);
898                 found = 1;
899                 break;
900         }
901
902         if (!found && s->num_p2p_clients < P2P_MAX_STORED_CLIENTS) {
903                 n = os_realloc_array(s->p2p_client_list,
904                                      s->num_p2p_clients + 1, 2 * ETH_ALEN);
905                 if (n == NULL)
906                         return;
907                 os_memcpy(n + s->num_p2p_clients * 2 * ETH_ALEN, addr,
908                           ETH_ALEN);
909                 os_memset(n + s->num_p2p_clients * 2 * ETH_ALEN + ETH_ALEN,
910                           0xff, ETH_ALEN);
911                 s->p2p_client_list = n;
912                 s->num_p2p_clients++;
913         } else if (!found && s->p2p_client_list) {
914                 /* Not enough room for an additional entry - drop the oldest
915                  * entry */
916                 os_memmove(s->p2p_client_list,
917                            s->p2p_client_list + 2 * ETH_ALEN,
918                            (s->num_p2p_clients - 1) * 2 * ETH_ALEN);
919                 os_memcpy(s->p2p_client_list +
920                           (s->num_p2p_clients - 1) * 2 * ETH_ALEN,
921                           addr, ETH_ALEN);
922                 os_memset(s->p2p_client_list +
923                           (s->num_p2p_clients - 1) * 2 * ETH_ALEN + ETH_ALEN,
924                           0xff, ETH_ALEN);
925         }
926
927         if (wpa_s->parent->conf->update_config &&
928             wpa_config_write(wpa_s->parent->confname, wpa_s->parent->conf))
929                 wpa_printf(MSG_DEBUG, "P2P: Failed to update configuration");
930 }
931
932
933 static void wpas_p2p_group_started(struct wpa_supplicant *wpa_s,
934                                    int go, struct wpa_ssid *ssid, int freq,
935                                    const u8 *psk, const char *passphrase,
936                                    const u8 *go_dev_addr, int persistent,
937                                    const char *extra)
938 {
939         const char *ssid_txt;
940         char psk_txt[65];
941
942         if (psk)
943                 wpa_snprintf_hex(psk_txt, sizeof(psk_txt), psk, 32);
944         else
945                 psk_txt[0] = '\0';
946
947         if (ssid)
948                 ssid_txt = wpa_ssid_txt(ssid->ssid, ssid->ssid_len);
949         else
950                 ssid_txt = "";
951
952         if (passphrase && passphrase[0] == '\0')
953                 passphrase = NULL;
954
955         /*
956          * Include PSK/passphrase only in the control interface message and
957          * leave it out from the debug log entry.
958          */
959         wpa_msg_global_ctrl(wpa_s->parent, MSG_INFO,
960                             P2P_EVENT_GROUP_STARTED
961                             "%s %s ssid=\"%s\" freq=%d%s%s%s%s%s go_dev_addr="
962                             MACSTR "%s%s",
963                             wpa_s->ifname, go ? "GO" : "client", ssid_txt, freq,
964                             psk ? " psk=" : "", psk_txt,
965                             passphrase ? " passphrase=\"" : "",
966                             passphrase ? passphrase : "",
967                             passphrase ? "\"" : "",
968                             MAC2STR(go_dev_addr),
969                             persistent ? " [PERSISTENT]" : "", extra);
970         wpa_printf(MSG_INFO, P2P_EVENT_GROUP_STARTED
971                    "%s %s ssid=\"%s\" freq=%d go_dev_addr=" MACSTR "%s%s",
972                    wpa_s->ifname, go ? "GO" : "client", ssid_txt, freq,
973                    MAC2STR(go_dev_addr), persistent ? " [PERSISTENT]" : "",
974                    extra);
975 }
976
977
978 static void wpas_group_formation_completed(struct wpa_supplicant *wpa_s,
979                                            int success)
980 {
981         struct wpa_ssid *ssid;
982         int client;
983         int persistent;
984         u8 go_dev_addr[ETH_ALEN];
985         int network_id = -1;
986
987         /*
988          * This callback is likely called for the main interface. Update wpa_s
989          * to use the group interface if a new interface was created for the
990          * group.
991          */
992         if (wpa_s->global->p2p_group_formation)
993                 wpa_s = wpa_s->global->p2p_group_formation;
994         if (wpa_s->p2p_go_group_formation_completed) {
995                 wpa_s->global->p2p_group_formation = NULL;
996                 wpa_s->p2p_in_provisioning = 0;
997         }
998         wpa_s->p2p_in_invitation = 0;
999         wpa_s->group_formation_reported = 1;
1000
1001         if (!success) {
1002                 wpa_msg_global(wpa_s->parent, MSG_INFO,
1003                                P2P_EVENT_GROUP_FORMATION_FAILURE);
1004                 wpas_p2p_group_delete(wpa_s,
1005                                       P2P_GROUP_REMOVAL_FORMATION_FAILED);
1006                 return;
1007         }
1008
1009         wpa_msg_global(wpa_s->parent, MSG_INFO,
1010                        P2P_EVENT_GROUP_FORMATION_SUCCESS);
1011
1012         ssid = wpa_s->current_ssid;
1013         if (ssid && ssid->mode == WPAS_MODE_P2P_GROUP_FORMATION) {
1014                 ssid->mode = WPAS_MODE_P2P_GO;
1015                 p2p_group_notif_formation_done(wpa_s->p2p_group);
1016                 wpa_supplicant_ap_mac_addr_filter(wpa_s, NULL);
1017         }
1018
1019         persistent = 0;
1020         if (ssid) {
1021                 client = ssid->mode == WPAS_MODE_INFRA;
1022                 if (ssid->mode == WPAS_MODE_P2P_GO) {
1023                         persistent = ssid->p2p_persistent_group;
1024                         os_memcpy(go_dev_addr, wpa_s->global->p2p_dev_addr,
1025                                   ETH_ALEN);
1026                 } else
1027                         persistent = wpas_p2p_persistent_group(wpa_s,
1028                                                                go_dev_addr,
1029                                                                ssid->ssid,
1030                                                                ssid->ssid_len);
1031         } else {
1032                 client = wpa_s->p2p_group_interface ==
1033                         P2P_GROUP_INTERFACE_CLIENT;
1034                 os_memset(go_dev_addr, 0, ETH_ALEN);
1035         }
1036
1037         wpa_s->show_group_started = 0;
1038         if (client) {
1039                 /*
1040                  * Indicate event only after successfully completed 4-way
1041                  * handshake, i.e., when the interface is ready for data
1042                  * packets.
1043                  */
1044                 wpa_s->show_group_started = 1;
1045         } else {
1046                 wpas_p2p_group_started(wpa_s, 1, ssid,
1047                                        ssid ? ssid->frequency : 0,
1048                                        ssid && ssid->passphrase == NULL &&
1049                                        ssid->psk_set ? ssid->psk : NULL,
1050                                        ssid ? ssid->passphrase : NULL,
1051                                        go_dev_addr, persistent, "");
1052                 wpas_p2p_cross_connect_setup(wpa_s);
1053                 wpas_p2p_set_group_idle_timeout(wpa_s);
1054         }
1055
1056         if (persistent)
1057                 network_id = wpas_p2p_store_persistent_group(wpa_s->parent,
1058                                                              ssid, go_dev_addr);
1059         else {
1060                 os_free(wpa_s->global->add_psk);
1061                 wpa_s->global->add_psk = NULL;
1062         }
1063         if (network_id < 0 && ssid)
1064                 network_id = ssid->id;
1065         if (!client) {
1066                 wpas_notify_p2p_group_started(wpa_s, ssid, network_id, 0);
1067                 os_get_reltime(&wpa_s->global->p2p_go_wait_client);
1068         }
1069 }
1070
1071
1072 struct send_action_work {
1073         unsigned int freq;
1074         u8 dst[ETH_ALEN];
1075         u8 src[ETH_ALEN];
1076         u8 bssid[ETH_ALEN];
1077         size_t len;
1078         unsigned int wait_time;
1079         u8 buf[0];
1080 };
1081
1082
1083 static void wpas_p2p_send_action_work_timeout(void *eloop_ctx,
1084                                               void *timeout_ctx)
1085 {
1086         struct wpa_supplicant *wpa_s = eloop_ctx;
1087
1088         if (!wpa_s->p2p_send_action_work)
1089                 return;
1090
1091         wpa_printf(MSG_DEBUG, "P2P: Send Action frame radio work timed out");
1092         os_free(wpa_s->p2p_send_action_work->ctx);
1093         radio_work_done(wpa_s->p2p_send_action_work);
1094         wpa_s->p2p_send_action_work = NULL;
1095 }
1096
1097
1098 static void wpas_p2p_action_tx_clear(struct wpa_supplicant *wpa_s)
1099 {
1100         if (wpa_s->p2p_send_action_work) {
1101                 struct send_action_work *awork;
1102                 awork = wpa_s->p2p_send_action_work->ctx;
1103                 if (awork->wait_time == 0) {
1104                         os_free(awork);
1105                         radio_work_done(wpa_s->p2p_send_action_work);
1106                         wpa_s->p2p_send_action_work = NULL;
1107                 } else {
1108                         /*
1109                          * In theory, this should not be needed, but number of
1110                          * places in the P2P code is still using non-zero wait
1111                          * time for the last Action frame in the sequence and
1112                          * some of these do not call send_action_done().
1113                          */
1114                         eloop_cancel_timeout(wpas_p2p_send_action_work_timeout,
1115                                              wpa_s, NULL);
1116                         eloop_register_timeout(
1117                                 0, awork->wait_time * 1000,
1118                                 wpas_p2p_send_action_work_timeout,
1119                                 wpa_s, NULL);
1120                 }
1121         }
1122 }
1123
1124
1125 static void wpas_p2p_send_action_tx_status(struct wpa_supplicant *wpa_s,
1126                                            unsigned int freq,
1127                                            const u8 *dst, const u8 *src,
1128                                            const u8 *bssid,
1129                                            const u8 *data, size_t data_len,
1130                                            enum offchannel_send_action_result
1131                                            result)
1132 {
1133         enum p2p_send_action_result res = P2P_SEND_ACTION_SUCCESS;
1134
1135         wpas_p2p_action_tx_clear(wpa_s);
1136
1137         if (wpa_s->global->p2p == NULL || wpa_s->global->p2p_disabled)
1138                 return;
1139
1140         switch (result) {
1141         case OFFCHANNEL_SEND_ACTION_SUCCESS:
1142                 res = P2P_SEND_ACTION_SUCCESS;
1143                 break;
1144         case OFFCHANNEL_SEND_ACTION_NO_ACK:
1145                 res = P2P_SEND_ACTION_NO_ACK;
1146                 break;
1147         case OFFCHANNEL_SEND_ACTION_FAILED:
1148                 res = P2P_SEND_ACTION_FAILED;
1149                 break;
1150         }
1151
1152         p2p_send_action_cb(wpa_s->global->p2p, freq, dst, src, bssid, res);
1153
1154         if (result != OFFCHANNEL_SEND_ACTION_SUCCESS &&
1155             wpa_s->pending_pd_before_join &&
1156             (os_memcmp(dst, wpa_s->pending_join_dev_addr, ETH_ALEN) == 0 ||
1157              os_memcmp(dst, wpa_s->pending_join_iface_addr, ETH_ALEN) == 0) &&
1158             wpa_s->p2p_fallback_to_go_neg) {
1159                 wpa_s->pending_pd_before_join = 0;
1160                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: No ACK for PD Req "
1161                         "during p2p_connect-auto");
1162                 wpas_p2p_fallback_to_go_neg(wpa_s, 0);
1163                 return;
1164         }
1165 }
1166
1167
1168 static void wpas_send_action_cb(struct wpa_radio_work *work, int deinit)
1169 {
1170         struct wpa_supplicant *wpa_s = work->wpa_s;
1171         struct send_action_work *awork = work->ctx;
1172
1173         if (deinit) {
1174                 if (work->started) {
1175                         eloop_cancel_timeout(wpas_p2p_send_action_work_timeout,
1176                                              wpa_s, NULL);
1177                         wpa_s->p2p_send_action_work = NULL;
1178                         offchannel_send_action_done(wpa_s);
1179                 }
1180                 os_free(awork);
1181                 return;
1182         }
1183
1184         if (offchannel_send_action(wpa_s, awork->freq, awork->dst, awork->src,
1185                                    awork->bssid, awork->buf, awork->len,
1186                                    awork->wait_time,
1187                                    wpas_p2p_send_action_tx_status, 1) < 0) {
1188                 os_free(awork);
1189                 radio_work_done(work);
1190                 return;
1191         }
1192         wpa_s->p2p_send_action_work = work;
1193 }
1194
1195
1196 static int wpas_send_action_work(struct wpa_supplicant *wpa_s,
1197                                  unsigned int freq, const u8 *dst,
1198                                  const u8 *src, const u8 *bssid, const u8 *buf,
1199                                  size_t len, unsigned int wait_time)
1200 {
1201         struct send_action_work *awork;
1202
1203         if (wpa_s->p2p_send_action_work) {
1204                 wpa_printf(MSG_DEBUG, "P2P: Cannot schedule new p2p-send-action work since one is already pending");
1205                 return -1;
1206         }
1207
1208         awork = os_zalloc(sizeof(*awork) + len);
1209         if (awork == NULL)
1210                 return -1;
1211
1212         awork->freq = freq;
1213         os_memcpy(awork->dst, dst, ETH_ALEN);
1214         os_memcpy(awork->src, src, ETH_ALEN);
1215         os_memcpy(awork->bssid, bssid, ETH_ALEN);
1216         awork->len = len;
1217         awork->wait_time = wait_time;
1218         os_memcpy(awork->buf, buf, len);
1219
1220         if (radio_add_work(wpa_s, freq, "p2p-send-action", 0,
1221                            wpas_send_action_cb, awork) < 0) {
1222                 os_free(awork);
1223                 return -1;
1224         }
1225
1226         return 0;
1227 }
1228
1229
1230 static int wpas_send_action(void *ctx, unsigned int freq, const u8 *dst,
1231                             const u8 *src, const u8 *bssid, const u8 *buf,
1232                             size_t len, unsigned int wait_time)
1233 {
1234         struct wpa_supplicant *wpa_s = ctx;
1235         int listen_freq = -1, send_freq = -1;
1236
1237         if (wpa_s->p2p_listen_work)
1238                 listen_freq = wpa_s->p2p_listen_work->freq;
1239         if (wpa_s->p2p_send_action_work)
1240                 send_freq = wpa_s->p2p_send_action_work->freq;
1241         if (listen_freq != (int) freq && send_freq != (int) freq) {
1242                 wpa_printf(MSG_DEBUG, "P2P: Schedule new radio work for Action frame TX (listen_freq=%d send_freq=%d)",
1243                            listen_freq, send_freq);
1244                 return wpas_send_action_work(wpa_s, freq, dst, src, bssid, buf,
1245                                              len, wait_time);
1246         }
1247
1248         wpa_printf(MSG_DEBUG, "P2P: Use ongoing radio work for Action frame TX");
1249         return offchannel_send_action(wpa_s, freq, dst, src, bssid, buf, len,
1250                                       wait_time,
1251                                       wpas_p2p_send_action_tx_status, 1);
1252 }
1253
1254
1255 static void wpas_send_action_done(void *ctx)
1256 {
1257         struct wpa_supplicant *wpa_s = ctx;
1258
1259         if (wpa_s->p2p_send_action_work) {
1260                 eloop_cancel_timeout(wpas_p2p_send_action_work_timeout,
1261                                      wpa_s, NULL);
1262                 os_free(wpa_s->p2p_send_action_work->ctx);
1263                 radio_work_done(wpa_s->p2p_send_action_work);
1264                 wpa_s->p2p_send_action_work = NULL;
1265         }
1266
1267         offchannel_send_action_done(wpa_s);
1268 }
1269
1270
1271 static int wpas_copy_go_neg_results(struct wpa_supplicant *wpa_s,
1272                                     struct p2p_go_neg_results *params)
1273 {
1274         if (wpa_s->go_params == NULL) {
1275                 wpa_s->go_params = os_malloc(sizeof(*params));
1276                 if (wpa_s->go_params == NULL)
1277                         return -1;
1278         }
1279         os_memcpy(wpa_s->go_params, params, sizeof(*params));
1280         return 0;
1281 }
1282
1283
1284 static void wpas_start_wps_enrollee(struct wpa_supplicant *wpa_s,
1285                                     struct p2p_go_neg_results *res)
1286 {
1287         wpa_s->group_formation_reported = 0;
1288         wpa_printf(MSG_DEBUG, "P2P: Start WPS Enrollee for peer " MACSTR
1289                    " dev_addr " MACSTR " wps_method %d",
1290                    MAC2STR(res->peer_interface_addr),
1291                    MAC2STR(res->peer_device_addr), res->wps_method);
1292         wpa_hexdump_ascii(MSG_DEBUG, "P2P: Start WPS Enrollee for SSID",
1293                           res->ssid, res->ssid_len);
1294         wpa_supplicant_ap_deinit(wpa_s);
1295         wpas_copy_go_neg_results(wpa_s, res);
1296         if (res->wps_method == WPS_PBC) {
1297                 wpas_wps_start_pbc(wpa_s, res->peer_interface_addr, 1);
1298 #ifdef CONFIG_WPS_NFC
1299         } else if (res->wps_method == WPS_NFC) {
1300                 wpas_wps_start_nfc(wpa_s, res->peer_device_addr,
1301                                    res->peer_interface_addr,
1302                                    wpa_s->parent->p2p_oob_dev_pw,
1303                                    wpa_s->parent->p2p_oob_dev_pw_id, 1,
1304                                    wpa_s->parent->p2p_oob_dev_pw_id ==
1305                                    DEV_PW_NFC_CONNECTION_HANDOVER ?
1306                                    wpa_s->parent->p2p_peer_oob_pubkey_hash :
1307                                    NULL,
1308                                    NULL, 0, 0);
1309 #endif /* CONFIG_WPS_NFC */
1310         } else {
1311                 u16 dev_pw_id = DEV_PW_DEFAULT;
1312                 if (wpa_s->p2p_wps_method == WPS_P2PS)
1313                         dev_pw_id = DEV_PW_P2PS_DEFAULT;
1314                 if (wpa_s->p2p_wps_method == WPS_PIN_KEYPAD)
1315                         dev_pw_id = DEV_PW_REGISTRAR_SPECIFIED;
1316                 wpas_wps_start_pin(wpa_s, res->peer_interface_addr,
1317                                    wpa_s->p2p_pin, 1, dev_pw_id);
1318         }
1319 }
1320
1321
1322 static void wpas_p2p_add_psk_list(struct wpa_supplicant *wpa_s,
1323                                   struct wpa_ssid *ssid)
1324 {
1325         struct wpa_ssid *persistent;
1326         struct psk_list_entry *psk;
1327         struct hostapd_data *hapd;
1328
1329         if (!wpa_s->ap_iface)
1330                 return;
1331
1332         persistent = wpas_p2p_get_persistent(wpa_s->parent, NULL, ssid->ssid,
1333                                              ssid->ssid_len);
1334         if (persistent == NULL)
1335                 return;
1336
1337         hapd = wpa_s->ap_iface->bss[0];
1338
1339         dl_list_for_each(psk, &persistent->psk_list, struct psk_list_entry,
1340                          list) {
1341                 struct hostapd_wpa_psk *hpsk;
1342
1343                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Add persistent group PSK entry for "
1344                         MACSTR " psk=%d",
1345                         MAC2STR(psk->addr), psk->p2p);
1346                 hpsk = os_zalloc(sizeof(*hpsk));
1347                 if (hpsk == NULL)
1348                         break;
1349                 os_memcpy(hpsk->psk, psk->psk, PMK_LEN);
1350                 if (psk->p2p)
1351                         os_memcpy(hpsk->p2p_dev_addr, psk->addr, ETH_ALEN);
1352                 else
1353                         os_memcpy(hpsk->addr, psk->addr, ETH_ALEN);
1354                 hpsk->next = hapd->conf->ssid.wpa_psk;
1355                 hapd->conf->ssid.wpa_psk = hpsk;
1356         }
1357 }
1358
1359
1360 static void p2p_go_dump_common_freqs(struct wpa_supplicant *wpa_s)
1361 {
1362         unsigned int i;
1363
1364         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Common group frequencies (len=%u):",
1365                 wpa_s->p2p_group_common_freqs_num);
1366
1367         for (i = 0; i < wpa_s->p2p_group_common_freqs_num; i++)
1368                 wpa_dbg(wpa_s, MSG_DEBUG, "freq[%u]: %d",
1369                         i, wpa_s->p2p_group_common_freqs[i]);
1370 }
1371
1372
1373 static void p2p_go_save_group_common_freqs(struct wpa_supplicant *wpa_s,
1374                                            struct p2p_go_neg_results *params)
1375 {
1376         unsigned int i, len = int_array_len(wpa_s->go_params->freq_list);
1377
1378         wpa_s->p2p_group_common_freqs_num = 0;
1379         os_free(wpa_s->p2p_group_common_freqs);
1380         wpa_s->p2p_group_common_freqs = os_calloc(len, sizeof(int));
1381         if (!wpa_s->p2p_group_common_freqs)
1382                 return;
1383
1384         for (i = 0; i < len; i++) {
1385                 if (!wpa_s->go_params->freq_list[i])
1386                         break;
1387                 wpa_s->p2p_group_common_freqs[i] =
1388                         wpa_s->go_params->freq_list[i];
1389         }
1390         wpa_s->p2p_group_common_freqs_num = i;
1391 }
1392
1393
1394 static void p2p_go_configured(void *ctx, void *data)
1395 {
1396         struct wpa_supplicant *wpa_s = ctx;
1397         struct p2p_go_neg_results *params = data;
1398         struct wpa_ssid *ssid;
1399         int network_id = -1;
1400
1401         p2p_go_save_group_common_freqs(wpa_s, params);
1402         p2p_go_dump_common_freqs(wpa_s);
1403
1404         ssid = wpa_s->current_ssid;
1405         if (ssid && ssid->mode == WPAS_MODE_P2P_GO) {
1406                 wpa_printf(MSG_DEBUG, "P2P: Group setup without provisioning");
1407                 if (wpa_s->global->p2p_group_formation == wpa_s)
1408                         wpa_s->global->p2p_group_formation = NULL;
1409                 wpas_p2p_group_started(wpa_s, 1, ssid, ssid->frequency,
1410                                        params->passphrase[0] == '\0' ?
1411                                        params->psk : NULL,
1412                                        params->passphrase,
1413                                        wpa_s->global->p2p_dev_addr,
1414                                        params->persistent_group, "");
1415                 wpa_s->group_formation_reported = 1;
1416
1417                 os_get_reltime(&wpa_s->global->p2p_go_wait_client);
1418                 if (params->persistent_group) {
1419                         network_id = wpas_p2p_store_persistent_group(
1420                                 wpa_s->parent, ssid,
1421                                 wpa_s->global->p2p_dev_addr);
1422                         wpas_p2p_add_psk_list(wpa_s, ssid);
1423                 }
1424                 if (network_id < 0)
1425                         network_id = ssid->id;
1426                 wpas_notify_p2p_group_started(wpa_s, ssid, network_id, 0);
1427                 wpas_p2p_cross_connect_setup(wpa_s);
1428                 wpas_p2p_set_group_idle_timeout(wpa_s);
1429
1430                 if (wpa_s->p2p_first_connection_timeout) {
1431                         wpa_dbg(wpa_s, MSG_DEBUG,
1432                                 "P2P: Start group formation timeout of %d seconds until first data connection on GO",
1433                                 wpa_s->p2p_first_connection_timeout);
1434                         wpa_s->p2p_go_group_formation_completed = 0;
1435                         wpa_s->global->p2p_group_formation = wpa_s;
1436                         eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
1437                                              wpa_s->parent, NULL);
1438                         eloop_register_timeout(
1439                                 wpa_s->p2p_first_connection_timeout, 0,
1440                                 wpas_p2p_group_formation_timeout,
1441                                 wpa_s->parent, NULL);
1442                 }
1443
1444                 return;
1445         }
1446
1447         wpa_printf(MSG_DEBUG, "P2P: Setting up WPS for GO provisioning");
1448         if (wpa_supplicant_ap_mac_addr_filter(wpa_s,
1449                                               params->peer_interface_addr)) {
1450                 wpa_printf(MSG_DEBUG, "P2P: Failed to setup MAC address "
1451                            "filtering");
1452                 return;
1453         }
1454         if (params->wps_method == WPS_PBC) {
1455                 wpa_supplicant_ap_wps_pbc(wpa_s, params->peer_interface_addr,
1456                                           params->peer_device_addr);
1457 #ifdef CONFIG_WPS_NFC
1458         } else if (params->wps_method == WPS_NFC) {
1459                 if (wpa_s->parent->p2p_oob_dev_pw_id !=
1460                     DEV_PW_NFC_CONNECTION_HANDOVER &&
1461                     !wpa_s->parent->p2p_oob_dev_pw) {
1462                         wpa_printf(MSG_DEBUG, "P2P: No NFC Dev Pw known");
1463                         return;
1464                 }
1465                 wpas_ap_wps_add_nfc_pw(
1466                         wpa_s, wpa_s->parent->p2p_oob_dev_pw_id,
1467                         wpa_s->parent->p2p_oob_dev_pw,
1468                         wpa_s->parent->p2p_peer_oob_pk_hash_known ?
1469                         wpa_s->parent->p2p_peer_oob_pubkey_hash : NULL);
1470 #endif /* CONFIG_WPS_NFC */
1471         } else if (wpa_s->p2p_pin[0])
1472                 wpa_supplicant_ap_wps_pin(wpa_s, params->peer_interface_addr,
1473                                           wpa_s->p2p_pin, NULL, 0, 0);
1474         os_free(wpa_s->go_params);
1475         wpa_s->go_params = NULL;
1476 }
1477
1478
1479 static void wpas_start_wps_go(struct wpa_supplicant *wpa_s,
1480                               struct p2p_go_neg_results *params,
1481                               int group_formation)
1482 {
1483         struct wpa_ssid *ssid;
1484
1485         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Starting GO");
1486         if (wpas_copy_go_neg_results(wpa_s, params) < 0) {
1487                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Could not copy GO Negotiation "
1488                         "results");
1489                 return;
1490         }
1491
1492         ssid = wpa_config_add_network(wpa_s->conf);
1493         if (ssid == NULL) {
1494                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Could not add network for GO");
1495                 return;
1496         }
1497
1498         wpa_s->show_group_started = 0;
1499         wpa_s->p2p_go_group_formation_completed = 0;
1500         wpa_s->group_formation_reported = 0;
1501
1502         wpa_config_set_network_defaults(ssid);
1503         ssid->temporary = 1;
1504         ssid->p2p_group = 1;
1505         ssid->p2p_persistent_group = params->persistent_group;
1506         ssid->mode = group_formation ? WPAS_MODE_P2P_GROUP_FORMATION :
1507                 WPAS_MODE_P2P_GO;
1508         ssid->frequency = params->freq;
1509         ssid->ht40 = params->ht40;
1510         ssid->vht = params->vht;
1511         ssid->ssid = os_zalloc(params->ssid_len + 1);
1512         if (ssid->ssid) {
1513                 os_memcpy(ssid->ssid, params->ssid, params->ssid_len);
1514                 ssid->ssid_len = params->ssid_len;
1515         }
1516         ssid->auth_alg = WPA_AUTH_ALG_OPEN;
1517         ssid->key_mgmt = WPA_KEY_MGMT_PSK;
1518         ssid->proto = WPA_PROTO_RSN;
1519         ssid->pairwise_cipher = WPA_CIPHER_CCMP;
1520         ssid->group_cipher = WPA_CIPHER_CCMP;
1521         if (params->freq > 56160) {
1522                 /*
1523                  * Enable GCMP instead of CCMP as pairwise_cipher and
1524                  * group_cipher in 60 GHz.
1525                  */
1526                 ssid->pairwise_cipher = WPA_CIPHER_GCMP;
1527                 ssid->group_cipher = WPA_CIPHER_GCMP;
1528         }
1529         if (os_strlen(params->passphrase) > 0) {
1530                 ssid->passphrase = os_strdup(params->passphrase);
1531                 if (ssid->passphrase == NULL) {
1532                         wpa_msg_global(wpa_s, MSG_ERROR,
1533                                        "P2P: Failed to copy passphrase for GO");
1534                         wpa_config_remove_network(wpa_s->conf, ssid->id);
1535                         return;
1536                 }
1537         } else
1538                 ssid->passphrase = NULL;
1539         ssid->psk_set = params->psk_set;
1540         if (ssid->psk_set)
1541                 os_memcpy(ssid->psk, params->psk, sizeof(ssid->psk));
1542         else if (ssid->passphrase)
1543                 wpa_config_update_psk(ssid);
1544         ssid->ap_max_inactivity = wpa_s->parent->conf->p2p_go_max_inactivity;
1545
1546         wpa_s->ap_configured_cb = p2p_go_configured;
1547         wpa_s->ap_configured_cb_ctx = wpa_s;
1548         wpa_s->ap_configured_cb_data = wpa_s->go_params;
1549         wpa_s->scan_req = NORMAL_SCAN_REQ;
1550         wpa_s->connect_without_scan = ssid;
1551         wpa_s->reassociate = 1;
1552         wpa_s->disconnected = 0;
1553         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Request scan (that will be skipped) to "
1554                 "start GO)");
1555         wpa_supplicant_req_scan(wpa_s, 0, 0);
1556 }
1557
1558
1559 static void wpas_p2p_clone_config(struct wpa_supplicant *dst,
1560                                   const struct wpa_supplicant *src)
1561 {
1562         struct wpa_config *d;
1563         const struct wpa_config *s;
1564
1565         d = dst->conf;
1566         s = src->conf;
1567
1568 #define C(n) if (s->n) d->n = os_strdup(s->n)
1569         C(device_name);
1570         C(manufacturer);
1571         C(model_name);
1572         C(model_number);
1573         C(serial_number);
1574         C(config_methods);
1575 #undef C
1576
1577         os_memcpy(d->device_type, s->device_type, WPS_DEV_TYPE_LEN);
1578         os_memcpy(d->sec_device_type, s->sec_device_type,
1579                   sizeof(d->sec_device_type));
1580         d->num_sec_device_types = s->num_sec_device_types;
1581
1582         d->p2p_group_idle = s->p2p_group_idle;
1583         d->p2p_intra_bss = s->p2p_intra_bss;
1584         d->persistent_reconnect = s->persistent_reconnect;
1585         d->max_num_sta = s->max_num_sta;
1586         d->pbc_in_m1 = s->pbc_in_m1;
1587         d->ignore_old_scan_res = s->ignore_old_scan_res;
1588         d->beacon_int = s->beacon_int;
1589         d->dtim_period = s->dtim_period;
1590         d->disassoc_low_ack = s->disassoc_low_ack;
1591         d->disable_scan_offload = s->disable_scan_offload;
1592         d->passive_scan = s->passive_scan;
1593
1594         if (s->wps_nfc_dh_privkey && s->wps_nfc_dh_pubkey) {
1595                 d->wps_nfc_dh_privkey = wpabuf_dup(s->wps_nfc_dh_privkey);
1596                 d->wps_nfc_dh_pubkey = wpabuf_dup(s->wps_nfc_dh_pubkey);
1597         }
1598 }
1599
1600
1601 static void wpas_p2p_get_group_ifname(struct wpa_supplicant *wpa_s,
1602                                       char *ifname, size_t len)
1603 {
1604         char *ifname_ptr = wpa_s->ifname;
1605
1606         if (os_strncmp(wpa_s->ifname, P2P_MGMT_DEVICE_PREFIX,
1607                        os_strlen(P2P_MGMT_DEVICE_PREFIX)) == 0) {
1608                 ifname_ptr = os_strrchr(wpa_s->ifname, '-') + 1;
1609         }
1610
1611         os_snprintf(ifname, len, "p2p-%s-%d", ifname_ptr, wpa_s->p2p_group_idx);
1612         if (os_strlen(ifname) >= IFNAMSIZ &&
1613             os_strlen(wpa_s->ifname) < IFNAMSIZ) {
1614                 int res;
1615
1616                 /* Try to avoid going over the IFNAMSIZ length limit */
1617                 res = os_snprintf(ifname, len, "p2p-%d", wpa_s->p2p_group_idx);
1618                 if (os_snprintf_error(len, res) && len)
1619                         ifname[len - 1] = '\0';
1620         }
1621 }
1622
1623
1624 static int wpas_p2p_add_group_interface(struct wpa_supplicant *wpa_s,
1625                                         enum wpa_driver_if_type type)
1626 {
1627         char ifname[120], force_ifname[120];
1628
1629         if (wpa_s->pending_interface_name[0]) {
1630                 wpa_printf(MSG_DEBUG, "P2P: Pending virtual interface exists "
1631                            "- skip creation of a new one");
1632                 if (is_zero_ether_addr(wpa_s->pending_interface_addr)) {
1633                         wpa_printf(MSG_DEBUG, "P2P: Pending virtual address "
1634                                    "unknown?! ifname='%s'",
1635                                    wpa_s->pending_interface_name);
1636                         return -1;
1637                 }
1638                 return 0;
1639         }
1640
1641         wpas_p2p_get_group_ifname(wpa_s, ifname, sizeof(ifname));
1642         force_ifname[0] = '\0';
1643
1644         wpa_printf(MSG_DEBUG, "P2P: Create a new interface %s for the group",
1645                    ifname);
1646         wpa_s->p2p_group_idx++;
1647
1648         wpa_s->pending_interface_type = type;
1649         if (wpa_drv_if_add(wpa_s, type, ifname, NULL, NULL, force_ifname,
1650                            wpa_s->pending_interface_addr, NULL) < 0) {
1651                 wpa_printf(MSG_ERROR, "P2P: Failed to create new group "
1652                            "interface");
1653                 return -1;
1654         }
1655
1656         if (force_ifname[0]) {
1657                 wpa_printf(MSG_DEBUG, "P2P: Driver forced interface name %s",
1658                            force_ifname);
1659                 os_strlcpy(wpa_s->pending_interface_name, force_ifname,
1660                            sizeof(wpa_s->pending_interface_name));
1661         } else
1662                 os_strlcpy(wpa_s->pending_interface_name, ifname,
1663                            sizeof(wpa_s->pending_interface_name));
1664         wpa_printf(MSG_DEBUG, "P2P: Created pending virtual interface %s addr "
1665                    MACSTR, wpa_s->pending_interface_name,
1666                    MAC2STR(wpa_s->pending_interface_addr));
1667
1668         return 0;
1669 }
1670
1671
1672 static void wpas_p2p_remove_pending_group_interface(
1673         struct wpa_supplicant *wpa_s)
1674 {
1675         if (!wpa_s->pending_interface_name[0] ||
1676             is_zero_ether_addr(wpa_s->pending_interface_addr))
1677                 return; /* No pending virtual interface */
1678
1679         wpa_printf(MSG_DEBUG, "P2P: Removing pending group interface %s",
1680                    wpa_s->pending_interface_name);
1681         wpa_drv_if_remove(wpa_s, wpa_s->pending_interface_type,
1682                           wpa_s->pending_interface_name);
1683         os_memset(wpa_s->pending_interface_addr, 0, ETH_ALEN);
1684         wpa_s->pending_interface_name[0] = '\0';
1685 }
1686
1687
1688 static struct wpa_supplicant *
1689 wpas_p2p_init_group_interface(struct wpa_supplicant *wpa_s, int go)
1690 {
1691         struct wpa_interface iface;
1692         struct wpa_supplicant *group_wpa_s;
1693
1694         if (!wpa_s->pending_interface_name[0]) {
1695                 wpa_printf(MSG_ERROR, "P2P: No pending group interface");
1696                 if (!wpas_p2p_create_iface(wpa_s))
1697                         return NULL;
1698                 /*
1699                  * Something has forced us to remove the pending interface; try
1700                  * to create a new one and hope for the best that we will get
1701                  * the same local address.
1702                  */
1703                 if (wpas_p2p_add_group_interface(wpa_s, go ? WPA_IF_P2P_GO :
1704                                                  WPA_IF_P2P_CLIENT) < 0)
1705                         return NULL;
1706         }
1707
1708         os_memset(&iface, 0, sizeof(iface));
1709         iface.ifname = wpa_s->pending_interface_name;
1710         iface.driver = wpa_s->driver->name;
1711         if (wpa_s->conf->ctrl_interface == NULL &&
1712             wpa_s->parent != wpa_s &&
1713             wpa_s->p2p_mgmt &&
1714             (wpa_s->drv_flags & WPA_DRIVER_FLAGS_DEDICATED_P2P_DEVICE))
1715                 iface.ctrl_interface = wpa_s->parent->conf->ctrl_interface;
1716         else
1717                 iface.ctrl_interface = wpa_s->conf->ctrl_interface;
1718         iface.driver_param = wpa_s->conf->driver_param;
1719         group_wpa_s = wpa_supplicant_add_iface(wpa_s->global, &iface);
1720         if (group_wpa_s == NULL) {
1721                 wpa_printf(MSG_ERROR, "P2P: Failed to create new "
1722                            "wpa_supplicant interface");
1723                 return NULL;
1724         }
1725         wpa_s->pending_interface_name[0] = '\0';
1726         group_wpa_s->parent = wpa_s;
1727         group_wpa_s->p2p_group_interface = go ? P2P_GROUP_INTERFACE_GO :
1728                 P2P_GROUP_INTERFACE_CLIENT;
1729         wpa_s->global->p2p_group_formation = group_wpa_s;
1730
1731         wpas_p2p_clone_config(group_wpa_s, wpa_s);
1732
1733         return group_wpa_s;
1734 }
1735
1736
1737 static void wpas_p2p_group_formation_timeout(void *eloop_ctx,
1738                                              void *timeout_ctx)
1739 {
1740         struct wpa_supplicant *wpa_s = eloop_ctx;
1741         wpa_printf(MSG_DEBUG, "P2P: Group Formation timed out");
1742         wpas_p2p_group_formation_failed(wpa_s);
1743 }
1744
1745
1746 void wpas_p2p_group_formation_failed(struct wpa_supplicant *wpa_s)
1747 {
1748         eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
1749                              wpa_s->parent, NULL);
1750         if (wpa_s->global->p2p)
1751                 p2p_group_formation_failed(wpa_s->global->p2p);
1752         wpas_group_formation_completed(wpa_s, 0);
1753 }
1754
1755
1756 static void wpas_p2p_grpform_fail_after_wps(struct wpa_supplicant *wpa_s)
1757 {
1758         wpa_printf(MSG_DEBUG, "P2P: Reject group formation due to WPS provisioning failure");
1759         eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
1760                              wpa_s->parent, NULL);
1761         eloop_register_timeout(0, 0, wpas_p2p_group_formation_timeout,
1762                                wpa_s->parent, NULL);
1763         wpa_s->global->p2p_fail_on_wps_complete = 0;
1764 }
1765
1766
1767 void wpas_p2p_ap_setup_failed(struct wpa_supplicant *wpa_s)
1768 {
1769         if (wpa_s->global->p2p_group_formation != wpa_s)
1770                 return;
1771         /* Speed up group formation timeout since this cannot succeed */
1772         eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
1773                              wpa_s->parent, NULL);
1774         eloop_register_timeout(0, 0, wpas_p2p_group_formation_timeout,
1775                                wpa_s->parent, NULL);
1776 }
1777
1778
1779 static void wpas_go_neg_completed(void *ctx, struct p2p_go_neg_results *res)
1780 {
1781         struct wpa_supplicant *wpa_s = ctx;
1782
1783         if (wpa_s->off_channel_freq || wpa_s->roc_waiting_drv_freq) {
1784                 wpa_drv_cancel_remain_on_channel(wpa_s);
1785                 wpa_s->off_channel_freq = 0;
1786                 wpa_s->roc_waiting_drv_freq = 0;
1787         }
1788
1789         if (res->status) {
1790                 wpa_msg_global(wpa_s, MSG_INFO,
1791                                P2P_EVENT_GO_NEG_FAILURE "status=%d",
1792                                res->status);
1793                 wpas_notify_p2p_go_neg_completed(wpa_s, res);
1794                 wpas_p2p_remove_pending_group_interface(wpa_s);
1795                 return;
1796         }
1797
1798         if (wpa_s->p2p_go_ht40)
1799                 res->ht40 = 1;
1800         if (wpa_s->p2p_go_vht)
1801                 res->vht = 1;
1802
1803         wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_GO_NEG_SUCCESS "role=%s "
1804                        "freq=%d ht40=%d peer_dev=" MACSTR " peer_iface=" MACSTR
1805                        " wps_method=%s",
1806                        res->role_go ? "GO" : "client", res->freq, res->ht40,
1807                        MAC2STR(res->peer_device_addr),
1808                        MAC2STR(res->peer_interface_addr),
1809                        p2p_wps_method_text(res->wps_method));
1810         wpas_notify_p2p_go_neg_completed(wpa_s, res);
1811
1812         if (res->role_go && wpa_s->p2p_persistent_id >= 0) {
1813                 struct wpa_ssid *ssid;
1814                 ssid = wpa_config_get_network(wpa_s->conf,
1815                                               wpa_s->p2p_persistent_id);
1816                 if (ssid && ssid->disabled == 2 &&
1817                     ssid->mode == WPAS_MODE_P2P_GO && ssid->passphrase) {
1818                         size_t len = os_strlen(ssid->passphrase);
1819                         wpa_printf(MSG_DEBUG, "P2P: Override passphrase based "
1820                                    "on requested persistent group");
1821                         os_memcpy(res->passphrase, ssid->passphrase, len);
1822                         res->passphrase[len] = '\0';
1823                 }
1824         }
1825
1826         if (wpa_s->create_p2p_iface) {
1827                 struct wpa_supplicant *group_wpa_s =
1828                         wpas_p2p_init_group_interface(wpa_s, res->role_go);
1829                 if (group_wpa_s == NULL) {
1830                         wpas_p2p_remove_pending_group_interface(wpa_s);
1831                         eloop_cancel_timeout(wpas_p2p_long_listen_timeout,
1832                                              wpa_s, NULL);
1833                         wpas_p2p_group_formation_failed(wpa_s);
1834                         return;
1835                 }
1836                 if (group_wpa_s != wpa_s) {
1837                         os_memcpy(group_wpa_s->p2p_pin, wpa_s->p2p_pin,
1838                                   sizeof(group_wpa_s->p2p_pin));
1839                         group_wpa_s->p2p_wps_method = wpa_s->p2p_wps_method;
1840                 }
1841                 os_memset(wpa_s->pending_interface_addr, 0, ETH_ALEN);
1842                 wpa_s->pending_interface_name[0] = '\0';
1843                 group_wpa_s->p2p_in_provisioning = 1;
1844
1845                 if (res->role_go)
1846                         wpas_start_wps_go(group_wpa_s, res, 1);
1847                 else
1848                         wpas_start_wps_enrollee(group_wpa_s, res);
1849         } else {
1850                 wpa_s->p2p_in_provisioning = 1;
1851                 wpa_s->global->p2p_group_formation = wpa_s;
1852
1853                 if (res->role_go)
1854                         wpas_start_wps_go(wpa_s, res, 1);
1855                 else
1856                         wpas_start_wps_enrollee(ctx, res);
1857         }
1858
1859         wpa_s->p2p_long_listen = 0;
1860         eloop_cancel_timeout(wpas_p2p_long_listen_timeout, wpa_s, NULL);
1861
1862         eloop_cancel_timeout(wpas_p2p_group_formation_timeout, wpa_s, NULL);
1863         eloop_register_timeout(15 + res->peer_config_timeout / 100,
1864                                (res->peer_config_timeout % 100) * 10000,
1865                                wpas_p2p_group_formation_timeout, wpa_s, NULL);
1866 }
1867
1868
1869 static void wpas_go_neg_req_rx(void *ctx, const u8 *src, u16 dev_passwd_id)
1870 {
1871         struct wpa_supplicant *wpa_s = ctx;
1872         wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_GO_NEG_REQUEST MACSTR
1873                        " dev_passwd_id=%u", MAC2STR(src), dev_passwd_id);
1874
1875         wpas_notify_p2p_go_neg_req(wpa_s, src, dev_passwd_id);
1876 }
1877
1878
1879 static void wpas_dev_found(void *ctx, const u8 *addr,
1880                            const struct p2p_peer_info *info,
1881                            int new_device)
1882 {
1883 #ifndef CONFIG_NO_STDOUT_DEBUG
1884         struct wpa_supplicant *wpa_s = ctx;
1885         char devtype[WPS_DEV_TYPE_BUFSIZE];
1886         char *wfd_dev_info_hex = NULL;
1887
1888 #ifdef CONFIG_WIFI_DISPLAY
1889         wfd_dev_info_hex = wifi_display_subelem_hex(info->wfd_subelems,
1890                                                     WFD_SUBELEM_DEVICE_INFO);
1891 #endif /* CONFIG_WIFI_DISPLAY */
1892
1893         if (info->p2ps_instance) {
1894                 char str[256];
1895                 const u8 *buf = wpabuf_head(info->p2ps_instance);
1896                 size_t len = wpabuf_len(info->p2ps_instance);
1897
1898                 while (len) {
1899                         u32 id;
1900                         u16 methods;
1901                         u8 str_len;
1902
1903                         if (len < 4 + 2 + 1)
1904                                 break;
1905                         id = WPA_GET_LE32(buf);
1906                         buf += sizeof(u32);
1907                         methods = WPA_GET_BE16(buf);
1908                         buf += sizeof(u16);
1909                         str_len = *buf++;
1910                         if (str_len > len - 4 - 2 - 1)
1911                                 break;
1912                         os_memcpy(str, buf, str_len);
1913                         str[str_len] = '\0';
1914                         buf += str_len;
1915                         len -= str_len + sizeof(u32) + sizeof(u16) + sizeof(u8);
1916
1917                         wpa_msg_global(wpa_s, MSG_INFO,
1918                                        P2P_EVENT_DEVICE_FOUND MACSTR
1919                                        " p2p_dev_addr=" MACSTR
1920                                        " pri_dev_type=%s name='%s'"
1921                                        " config_methods=0x%x"
1922                                        " dev_capab=0x%x"
1923                                        " group_capab=0x%x"
1924                                        " adv_id=%x asp_svc=%s%s",
1925                                        MAC2STR(addr),
1926                                        MAC2STR(info->p2p_device_addr),
1927                                        wps_dev_type_bin2str(
1928                                                info->pri_dev_type,
1929                                                devtype, sizeof(devtype)),
1930                                        info->device_name, methods,
1931                                        info->dev_capab, info->group_capab,
1932                                        id, str,
1933                                        info->vendor_elems ?
1934                                        " vendor_elems=1" : "");
1935                 }
1936                 goto done;
1937         }
1938
1939         wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_DEVICE_FOUND MACSTR
1940                        " p2p_dev_addr=" MACSTR
1941                        " pri_dev_type=%s name='%s' config_methods=0x%x "
1942                        "dev_capab=0x%x group_capab=0x%x%s%s%s new=%d",
1943                        MAC2STR(addr), MAC2STR(info->p2p_device_addr),
1944                        wps_dev_type_bin2str(info->pri_dev_type, devtype,
1945                                             sizeof(devtype)),
1946                        info->device_name, info->config_methods,
1947                        info->dev_capab, info->group_capab,
1948                        wfd_dev_info_hex ? " wfd_dev_info=0x" : "",
1949                        wfd_dev_info_hex ? wfd_dev_info_hex : "",
1950                        info->vendor_elems ? " vendor_elems=1" : "",
1951                        new_device);
1952
1953 done:
1954         os_free(wfd_dev_info_hex);
1955 #endif /* CONFIG_NO_STDOUT_DEBUG */
1956
1957         wpas_notify_p2p_device_found(ctx, info->p2p_device_addr, new_device);
1958 }
1959
1960
1961 static void wpas_dev_lost(void *ctx, const u8 *dev_addr)
1962 {
1963         struct wpa_supplicant *wpa_s = ctx;
1964
1965         wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_DEVICE_LOST
1966                        "p2p_dev_addr=" MACSTR, MAC2STR(dev_addr));
1967
1968         wpas_notify_p2p_device_lost(wpa_s, dev_addr);
1969 }
1970
1971
1972 static void wpas_find_stopped(void *ctx)
1973 {
1974         struct wpa_supplicant *wpa_s = ctx;
1975         wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_FIND_STOPPED);
1976 }
1977
1978
1979 struct wpas_p2p_listen_work {
1980         unsigned int freq;
1981         unsigned int duration;
1982         struct wpabuf *probe_resp_ie;
1983 };
1984
1985
1986 static void wpas_p2p_listen_work_free(struct wpas_p2p_listen_work *lwork)
1987 {
1988         if (lwork == NULL)
1989                 return;
1990         wpabuf_free(lwork->probe_resp_ie);
1991         os_free(lwork);
1992 }
1993
1994
1995 static void wpas_p2p_listen_work_done(struct wpa_supplicant *wpa_s)
1996 {
1997         struct wpas_p2p_listen_work *lwork;
1998
1999         if (!wpa_s->p2p_listen_work)
2000                 return;
2001
2002         lwork = wpa_s->p2p_listen_work->ctx;
2003         wpas_p2p_listen_work_free(lwork);
2004         radio_work_done(wpa_s->p2p_listen_work);
2005         wpa_s->p2p_listen_work = NULL;
2006 }
2007
2008
2009 static void wpas_start_listen_cb(struct wpa_radio_work *work, int deinit)
2010 {
2011         struct wpa_supplicant *wpa_s = work->wpa_s;
2012         struct wpas_p2p_listen_work *lwork = work->ctx;
2013         unsigned int duration;
2014
2015         if (deinit) {
2016                 if (work->started) {
2017                         wpa_s->p2p_listen_work = NULL;
2018                         wpas_stop_listen(wpa_s);
2019                 }
2020                 wpas_p2p_listen_work_free(lwork);
2021                 return;
2022         }
2023
2024         wpa_s->p2p_listen_work = work;
2025
2026         wpa_drv_set_ap_wps_ie(wpa_s, NULL, lwork->probe_resp_ie, NULL);
2027
2028         if (wpa_drv_probe_req_report(wpa_s, 1) < 0) {
2029                 wpa_printf(MSG_DEBUG, "P2P: Failed to request the driver to "
2030                            "report received Probe Request frames");
2031                 wpas_p2p_listen_work_done(wpa_s);
2032                 return;
2033         }
2034
2035         wpa_s->pending_listen_freq = lwork->freq;
2036         wpa_s->pending_listen_duration = lwork->duration;
2037
2038         duration = lwork->duration;
2039 #ifdef CONFIG_TESTING_OPTIONS
2040         if (wpa_s->extra_roc_dur) {
2041                 wpa_printf(MSG_DEBUG, "TESTING: Increase ROC duration %u -> %u",
2042                            duration, duration + wpa_s->extra_roc_dur);
2043                 duration += wpa_s->extra_roc_dur;
2044         }
2045 #endif /* CONFIG_TESTING_OPTIONS */
2046
2047         if (wpa_drv_remain_on_channel(wpa_s, lwork->freq, duration) < 0) {
2048                 wpa_printf(MSG_DEBUG, "P2P: Failed to request the driver "
2049                            "to remain on channel (%u MHz) for Listen "
2050                            "state", lwork->freq);
2051                 wpas_p2p_listen_work_done(wpa_s);
2052                 wpa_s->pending_listen_freq = 0;
2053                 return;
2054         }
2055         wpa_s->off_channel_freq = 0;
2056         wpa_s->roc_waiting_drv_freq = lwork->freq;
2057 }
2058
2059
2060 static int wpas_start_listen(void *ctx, unsigned int freq,
2061                              unsigned int duration,
2062                              const struct wpabuf *probe_resp_ie)
2063 {
2064         struct wpa_supplicant *wpa_s = ctx;
2065         struct wpas_p2p_listen_work *lwork;
2066
2067         if (wpa_s->p2p_listen_work) {
2068                 wpa_printf(MSG_DEBUG, "P2P: Reject start_listen since p2p_listen_work already exists");
2069                 return -1;
2070         }
2071
2072         lwork = os_zalloc(sizeof(*lwork));
2073         if (lwork == NULL)
2074                 return -1;
2075         lwork->freq = freq;
2076         lwork->duration = duration;
2077         if (probe_resp_ie) {
2078                 lwork->probe_resp_ie = wpabuf_dup(probe_resp_ie);
2079                 if (lwork->probe_resp_ie == NULL) {
2080                         wpas_p2p_listen_work_free(lwork);
2081                         return -1;
2082                 }
2083         }
2084
2085         if (radio_add_work(wpa_s, freq, "p2p-listen", 0, wpas_start_listen_cb,
2086                            lwork) < 0) {
2087                 wpas_p2p_listen_work_free(lwork);
2088                 return -1;
2089         }
2090
2091         return 0;
2092 }
2093
2094
2095 static void wpas_stop_listen(void *ctx)
2096 {
2097         struct wpa_supplicant *wpa_s = ctx;
2098         if (wpa_s->off_channel_freq || wpa_s->roc_waiting_drv_freq) {
2099                 wpa_drv_cancel_remain_on_channel(wpa_s);
2100                 wpa_s->off_channel_freq = 0;
2101                 wpa_s->roc_waiting_drv_freq = 0;
2102         }
2103         wpa_drv_set_ap_wps_ie(wpa_s, NULL, NULL, NULL);
2104         wpa_drv_probe_req_report(wpa_s, 0);
2105         wpas_p2p_listen_work_done(wpa_s);
2106 }
2107
2108
2109 static int wpas_send_probe_resp(void *ctx, const struct wpabuf *buf)
2110 {
2111         struct wpa_supplicant *wpa_s = ctx;
2112         return wpa_drv_send_mlme(wpa_s, wpabuf_head(buf), wpabuf_len(buf), 1);
2113 }
2114
2115
2116 /*
2117  * DNS Header section is used only to calculate compression pointers, so the
2118  * contents of this data does not matter, but the length needs to be reserved
2119  * in the virtual packet.
2120  */
2121 #define DNS_HEADER_LEN 12
2122
2123 /*
2124  * 27-octet in-memory packet from P2P specification containing two implied
2125  * queries for _tcp.lcoal. PTR IN and _udp.local. PTR IN
2126  */
2127 #define P2P_SD_IN_MEMORY_LEN 27
2128
2129 static int p2p_sd_dns_uncompress_label(char **upos, char *uend, u8 *start,
2130                                        u8 **spos, const u8 *end)
2131 {
2132         while (*spos < end) {
2133                 u8 val = ((*spos)[0] & 0xc0) >> 6;
2134                 int len;
2135
2136                 if (val == 1 || val == 2) {
2137                         /* These are reserved values in RFC 1035 */
2138                         wpa_printf(MSG_DEBUG, "P2P: Invalid domain name "
2139                                    "sequence starting with 0x%x", val);
2140                         return -1;
2141                 }
2142
2143                 if (val == 3) {
2144                         u16 offset;
2145                         u8 *spos_tmp;
2146
2147                         /* Offset */
2148                         if (*spos + 2 > end) {
2149                                 wpa_printf(MSG_DEBUG, "P2P: No room for full "
2150                                            "DNS offset field");
2151                                 return -1;
2152                         }
2153
2154                         offset = (((*spos)[0] & 0x3f) << 8) | (*spos)[1];
2155                         if (offset >= *spos - start) {
2156                                 wpa_printf(MSG_DEBUG, "P2P: Invalid DNS "
2157                                            "pointer offset %u", offset);
2158                                 return -1;
2159                         }
2160
2161                         (*spos) += 2;
2162                         spos_tmp = start + offset;
2163                         return p2p_sd_dns_uncompress_label(upos, uend, start,
2164                                                            &spos_tmp,
2165                                                            *spos - 2);
2166                 }
2167
2168                 /* Label */
2169                 len = (*spos)[0] & 0x3f;
2170                 if (len == 0)
2171                         return 0;
2172
2173                 (*spos)++;
2174                 if (*spos + len > end) {
2175                         wpa_printf(MSG_DEBUG, "P2P: Invalid domain name "
2176                                    "sequence - no room for label with length "
2177                                    "%u", len);
2178                         return -1;
2179                 }
2180
2181                 if (*upos + len + 2 > uend)
2182                         return -2;
2183
2184                 os_memcpy(*upos, *spos, len);
2185                 *spos += len;
2186                 *upos += len;
2187                 (*upos)[0] = '.';
2188                 (*upos)++;
2189                 (*upos)[0] = '\0';
2190         }
2191
2192         return 0;
2193 }
2194
2195
2196 /* Uncompress domain names per RFC 1035 using the P2P SD in-memory packet.
2197  * Returns -1 on parsing error (invalid input sequence), -2 if output buffer is
2198  * not large enough */
2199 static int p2p_sd_dns_uncompress(char *buf, size_t buf_len, const u8 *msg,
2200                                  size_t msg_len, size_t offset)
2201 {
2202         /* 27-octet in-memory packet from P2P specification */
2203         const char *prefix = "\x04_tcp\x05local\x00\x00\x0C\x00\x01"
2204                 "\x04_udp\xC0\x11\x00\x0C\x00\x01";
2205         u8 *tmp, *end, *spos;
2206         char *upos, *uend;
2207         int ret = 0;
2208
2209         if (buf_len < 2)
2210                 return -1;
2211         if (offset > msg_len)
2212                 return -1;
2213
2214         tmp = os_malloc(DNS_HEADER_LEN + P2P_SD_IN_MEMORY_LEN + msg_len);
2215         if (tmp == NULL)
2216                 return -1;
2217         spos = tmp + DNS_HEADER_LEN + P2P_SD_IN_MEMORY_LEN;
2218         end = spos + msg_len;
2219         spos += offset;
2220
2221         os_memset(tmp, 0, DNS_HEADER_LEN);
2222         os_memcpy(tmp + DNS_HEADER_LEN, prefix, P2P_SD_IN_MEMORY_LEN);
2223         os_memcpy(tmp + DNS_HEADER_LEN + P2P_SD_IN_MEMORY_LEN, msg, msg_len);
2224
2225         upos = buf;
2226         uend = buf + buf_len;
2227
2228         ret = p2p_sd_dns_uncompress_label(&upos, uend, tmp, &spos, end);
2229         if (ret) {
2230                 os_free(tmp);
2231                 return ret;
2232         }
2233
2234         if (upos == buf) {
2235                 upos[0] = '.';
2236                 upos[1] = '\0';
2237         } else if (upos[-1] == '.')
2238                 upos[-1] = '\0';
2239
2240         os_free(tmp);
2241         return 0;
2242 }
2243
2244
2245 static struct p2p_srv_bonjour *
2246 wpas_p2p_service_get_bonjour(struct wpa_supplicant *wpa_s,
2247                              const struct wpabuf *query)
2248 {
2249         struct p2p_srv_bonjour *bsrv;
2250         size_t len;
2251
2252         len = wpabuf_len(query);
2253         dl_list_for_each(bsrv, &wpa_s->global->p2p_srv_bonjour,
2254                          struct p2p_srv_bonjour, list) {
2255                 if (len == wpabuf_len(bsrv->query) &&
2256                     os_memcmp(wpabuf_head(query), wpabuf_head(bsrv->query),
2257                               len) == 0)
2258                         return bsrv;
2259         }
2260         return NULL;
2261 }
2262
2263
2264 static struct p2p_srv_upnp *
2265 wpas_p2p_service_get_upnp(struct wpa_supplicant *wpa_s, u8 version,
2266                           const char *service)
2267 {
2268         struct p2p_srv_upnp *usrv;
2269
2270         dl_list_for_each(usrv, &wpa_s->global->p2p_srv_upnp,
2271                          struct p2p_srv_upnp, list) {
2272                 if (version == usrv->version &&
2273                     os_strcmp(service, usrv->service) == 0)
2274                         return usrv;
2275         }
2276         return NULL;
2277 }
2278
2279
2280 static void wpas_sd_add_empty(struct wpabuf *resp, u8 srv_proto,
2281                               u8 srv_trans_id, u8 status)
2282 {
2283         u8 *len_pos;
2284
2285         if (wpabuf_tailroom(resp) < 5)
2286                 return;
2287
2288         /* Length (to be filled) */
2289         len_pos = wpabuf_put(resp, 2);
2290         wpabuf_put_u8(resp, srv_proto);
2291         wpabuf_put_u8(resp, srv_trans_id);
2292         /* Status Code */
2293         wpabuf_put_u8(resp, status);
2294         /* Response Data: empty */
2295         WPA_PUT_LE16(len_pos, (u8 *) wpabuf_put(resp, 0) - len_pos - 2);
2296 }
2297
2298
2299 static void wpas_sd_add_proto_not_avail(struct wpabuf *resp, u8 srv_proto,
2300                                         u8 srv_trans_id)
2301 {
2302         wpas_sd_add_empty(resp, srv_proto, srv_trans_id,
2303                           P2P_SD_PROTO_NOT_AVAILABLE);
2304 }
2305
2306
2307 static void wpas_sd_add_bad_request(struct wpabuf *resp, u8 srv_proto,
2308                                     u8 srv_trans_id)
2309 {
2310         wpas_sd_add_empty(resp, srv_proto, srv_trans_id, P2P_SD_BAD_REQUEST);
2311 }
2312
2313
2314 static void wpas_sd_add_not_found(struct wpabuf *resp, u8 srv_proto,
2315                                   u8 srv_trans_id)
2316 {
2317         wpas_sd_add_empty(resp, srv_proto, srv_trans_id,
2318                           P2P_SD_REQUESTED_INFO_NOT_AVAILABLE);
2319 }
2320
2321
2322 static void wpas_sd_all_bonjour(struct wpa_supplicant *wpa_s,
2323                                 struct wpabuf *resp, u8 srv_trans_id)
2324 {
2325         struct p2p_srv_bonjour *bsrv;
2326         u8 *len_pos;
2327
2328         wpa_printf(MSG_DEBUG, "P2P: SD Request for all Bonjour services");
2329
2330         if (dl_list_empty(&wpa_s->global->p2p_srv_bonjour)) {
2331                 wpa_printf(MSG_DEBUG, "P2P: Bonjour protocol not available");
2332                 return;
2333         }
2334
2335         dl_list_for_each(bsrv, &wpa_s->global->p2p_srv_bonjour,
2336                          struct p2p_srv_bonjour, list) {
2337                 if (wpabuf_tailroom(resp) <
2338                     5 + wpabuf_len(bsrv->query) + wpabuf_len(bsrv->resp))
2339                         return;
2340                 /* Length (to be filled) */
2341                 len_pos = wpabuf_put(resp, 2);
2342                 wpabuf_put_u8(resp, P2P_SERV_BONJOUR);
2343                 wpabuf_put_u8(resp, srv_trans_id);
2344                 /* Status Code */
2345                 wpabuf_put_u8(resp, P2P_SD_SUCCESS);
2346                 wpa_hexdump_ascii(MSG_DEBUG, "P2P: Matching Bonjour service",
2347                                   wpabuf_head(bsrv->resp),
2348                                   wpabuf_len(bsrv->resp));
2349                 /* Response Data */
2350                 wpabuf_put_buf(resp, bsrv->query); /* Key */
2351                 wpabuf_put_buf(resp, bsrv->resp); /* Value */
2352                 WPA_PUT_LE16(len_pos, (u8 *) wpabuf_put(resp, 0) - len_pos -
2353                              2);
2354         }
2355 }
2356
2357
2358 static int match_bonjour_query(struct p2p_srv_bonjour *bsrv, const u8 *query,
2359                                size_t query_len)
2360 {
2361         char str_rx[256], str_srv[256];
2362
2363         if (query_len < 3 || wpabuf_len(bsrv->query) < 3)
2364                 return 0; /* Too short to include DNS Type and Version */
2365         if (os_memcmp(query + query_len - 3,
2366                       wpabuf_head_u8(bsrv->query) + wpabuf_len(bsrv->query) - 3,
2367                       3) != 0)
2368                 return 0; /* Mismatch in DNS Type or Version */
2369         if (query_len == wpabuf_len(bsrv->query) &&
2370             os_memcmp(query, wpabuf_head(bsrv->query), query_len - 3) == 0)
2371                 return 1; /* Binary match */
2372
2373         if (p2p_sd_dns_uncompress(str_rx, sizeof(str_rx), query, query_len - 3,
2374                                   0))
2375                 return 0; /* Failed to uncompress query */
2376         if (p2p_sd_dns_uncompress(str_srv, sizeof(str_srv),
2377                                   wpabuf_head(bsrv->query),
2378                                   wpabuf_len(bsrv->query) - 3, 0))
2379                 return 0; /* Failed to uncompress service */
2380
2381         return os_strcmp(str_rx, str_srv) == 0;
2382 }
2383
2384
2385 static void wpas_sd_req_bonjour(struct wpa_supplicant *wpa_s,
2386                                 struct wpabuf *resp, u8 srv_trans_id,
2387                                 const u8 *query, size_t query_len)
2388 {
2389         struct p2p_srv_bonjour *bsrv;
2390         u8 *len_pos;
2391         int matches = 0;
2392
2393         wpa_hexdump_ascii(MSG_DEBUG, "P2P: SD Request for Bonjour",
2394                           query, query_len);
2395         if (dl_list_empty(&wpa_s->global->p2p_srv_bonjour)) {
2396                 wpa_printf(MSG_DEBUG, "P2P: Bonjour protocol not available");
2397                 wpas_sd_add_proto_not_avail(resp, P2P_SERV_BONJOUR,
2398                                             srv_trans_id);
2399                 return;
2400         }
2401
2402         if (query_len == 0) {
2403                 wpas_sd_all_bonjour(wpa_s, resp, srv_trans_id);
2404                 return;
2405         }
2406
2407         dl_list_for_each(bsrv, &wpa_s->global->p2p_srv_bonjour,
2408                          struct p2p_srv_bonjour, list) {
2409                 if (!match_bonjour_query(bsrv, query, query_len))
2410                         continue;
2411
2412                 if (wpabuf_tailroom(resp) <
2413                     5 + query_len + wpabuf_len(bsrv->resp))
2414                         return;
2415
2416                 matches++;
2417
2418                 /* Length (to be filled) */
2419                 len_pos = wpabuf_put(resp, 2);
2420                 wpabuf_put_u8(resp, P2P_SERV_BONJOUR);
2421                 wpabuf_put_u8(resp, srv_trans_id);
2422
2423                 /* Status Code */
2424                 wpabuf_put_u8(resp, P2P_SD_SUCCESS);
2425                 wpa_hexdump_ascii(MSG_DEBUG, "P2P: Matching Bonjour service",
2426                                   wpabuf_head(bsrv->resp),
2427                                   wpabuf_len(bsrv->resp));
2428
2429                 /* Response Data */
2430                 wpabuf_put_data(resp, query, query_len); /* Key */
2431                 wpabuf_put_buf(resp, bsrv->resp); /* Value */
2432
2433                 WPA_PUT_LE16(len_pos, (u8 *) wpabuf_put(resp, 0) - len_pos - 2);
2434         }
2435
2436         if (matches == 0) {
2437                 wpa_printf(MSG_DEBUG, "P2P: Requested Bonjour service not "
2438                            "available");
2439                 if (wpabuf_tailroom(resp) < 5)
2440                         return;
2441
2442                 /* Length (to be filled) */
2443                 len_pos = wpabuf_put(resp, 2);
2444                 wpabuf_put_u8(resp, P2P_SERV_BONJOUR);
2445                 wpabuf_put_u8(resp, srv_trans_id);
2446
2447                 /* Status Code */
2448                 wpabuf_put_u8(resp, P2P_SD_REQUESTED_INFO_NOT_AVAILABLE);
2449                 /* Response Data: empty */
2450                 WPA_PUT_LE16(len_pos, (u8 *) wpabuf_put(resp, 0) - len_pos -
2451                              2);
2452         }
2453 }
2454
2455
2456 static void wpas_sd_all_upnp(struct wpa_supplicant *wpa_s,
2457                              struct wpabuf *resp, u8 srv_trans_id)
2458 {
2459         struct p2p_srv_upnp *usrv;
2460         u8 *len_pos;
2461
2462         wpa_printf(MSG_DEBUG, "P2P: SD Request for all UPnP services");
2463
2464         if (dl_list_empty(&wpa_s->global->p2p_srv_upnp)) {
2465                 wpa_printf(MSG_DEBUG, "P2P: UPnP protocol not available");
2466                 return;
2467         }
2468
2469         dl_list_for_each(usrv, &wpa_s->global->p2p_srv_upnp,
2470                          struct p2p_srv_upnp, list) {
2471                 if (wpabuf_tailroom(resp) < 5 + 1 + os_strlen(usrv->service))
2472                         return;
2473
2474                 /* Length (to be filled) */
2475                 len_pos = wpabuf_put(resp, 2);
2476                 wpabuf_put_u8(resp, P2P_SERV_UPNP);
2477                 wpabuf_put_u8(resp, srv_trans_id);
2478
2479                 /* Status Code */
2480                 wpabuf_put_u8(resp, P2P_SD_SUCCESS);
2481                 /* Response Data */
2482                 wpabuf_put_u8(resp, usrv->version);
2483                 wpa_printf(MSG_DEBUG, "P2P: Matching UPnP Service: %s",
2484                            usrv->service);
2485                 wpabuf_put_str(resp, usrv->service);
2486                 WPA_PUT_LE16(len_pos, (u8 *) wpabuf_put(resp, 0) - len_pos -
2487                              2);
2488         }
2489 }
2490
2491
2492 static void wpas_sd_req_upnp(struct wpa_supplicant *wpa_s,
2493                              struct wpabuf *resp, u8 srv_trans_id,
2494                              const u8 *query, size_t query_len)
2495 {
2496         struct p2p_srv_upnp *usrv;
2497         u8 *len_pos;
2498         u8 version;
2499         char *str;
2500         int count = 0;
2501
2502         wpa_hexdump_ascii(MSG_DEBUG, "P2P: SD Request for UPnP",
2503                           query, query_len);
2504
2505         if (dl_list_empty(&wpa_s->global->p2p_srv_upnp)) {
2506                 wpa_printf(MSG_DEBUG, "P2P: UPnP protocol not available");
2507                 wpas_sd_add_proto_not_avail(resp, P2P_SERV_UPNP,
2508                                             srv_trans_id);
2509                 return;
2510         }
2511
2512         if (query_len == 0) {
2513                 wpas_sd_all_upnp(wpa_s, resp, srv_trans_id);
2514                 return;
2515         }
2516
2517         if (wpabuf_tailroom(resp) < 5)
2518                 return;
2519
2520         /* Length (to be filled) */
2521         len_pos = wpabuf_put(resp, 2);
2522         wpabuf_put_u8(resp, P2P_SERV_UPNP);
2523         wpabuf_put_u8(resp, srv_trans_id);
2524
2525         version = query[0];
2526         str = os_malloc(query_len);
2527         if (str == NULL)
2528                 return;
2529         os_memcpy(str, query + 1, query_len - 1);
2530         str[query_len - 1] = '\0';
2531
2532         dl_list_for_each(usrv, &wpa_s->global->p2p_srv_upnp,
2533                          struct p2p_srv_upnp, list) {
2534                 if (version != usrv->version)
2535                         continue;
2536
2537                 if (os_strcmp(str, "ssdp:all") != 0 &&
2538                     os_strstr(usrv->service, str) == NULL)
2539                         continue;
2540
2541                 if (wpabuf_tailroom(resp) < 2)
2542                         break;
2543                 if (count == 0) {
2544                         /* Status Code */
2545                         wpabuf_put_u8(resp, P2P_SD_SUCCESS);
2546                         /* Response Data */
2547                         wpabuf_put_u8(resp, version);
2548                 } else
2549                         wpabuf_put_u8(resp, ',');
2550
2551                 count++;
2552
2553                 wpa_printf(MSG_DEBUG, "P2P: Matching UPnP Service: %s",
2554                            usrv->service);
2555                 if (wpabuf_tailroom(resp) < os_strlen(usrv->service))
2556                         break;
2557                 wpabuf_put_str(resp, usrv->service);
2558         }
2559         os_free(str);
2560
2561         if (count == 0) {
2562                 wpa_printf(MSG_DEBUG, "P2P: Requested UPnP service not "
2563                            "available");
2564                 /* Status Code */
2565                 wpabuf_put_u8(resp, P2P_SD_REQUESTED_INFO_NOT_AVAILABLE);
2566                 /* Response Data: empty */
2567         }
2568
2569         WPA_PUT_LE16(len_pos, (u8 *) wpabuf_put(resp, 0) - len_pos - 2);
2570 }
2571
2572
2573 #ifdef CONFIG_WIFI_DISPLAY
2574 static void wpas_sd_req_wfd(struct wpa_supplicant *wpa_s,
2575                             struct wpabuf *resp, u8 srv_trans_id,
2576                             const u8 *query, size_t query_len)
2577 {
2578         const u8 *pos;
2579         u8 role;
2580         u8 *len_pos;
2581
2582         wpa_hexdump(MSG_DEBUG, "P2P: SD Request for WFD", query, query_len);
2583
2584         if (!wpa_s->global->wifi_display) {
2585                 wpa_printf(MSG_DEBUG, "P2P: WFD protocol not available");
2586                 wpas_sd_add_proto_not_avail(resp, P2P_SERV_WIFI_DISPLAY,
2587                                             srv_trans_id);
2588                 return;
2589         }
2590
2591         if (query_len < 1) {
2592                 wpa_printf(MSG_DEBUG, "P2P: Missing WFD Requested Device "
2593                            "Role");
2594                 return;
2595         }
2596
2597         if (wpabuf_tailroom(resp) < 5)
2598                 return;
2599
2600         pos = query;
2601         role = *pos++;
2602         wpa_printf(MSG_DEBUG, "P2P: WSD for device role 0x%x", role);
2603
2604         /* TODO: role specific handling */
2605
2606         /* Length (to be filled) */
2607         len_pos = wpabuf_put(resp, 2);
2608         wpabuf_put_u8(resp, P2P_SERV_WIFI_DISPLAY);
2609         wpabuf_put_u8(resp, srv_trans_id);
2610         wpabuf_put_u8(resp, P2P_SD_SUCCESS); /* Status Code */
2611
2612         while (pos < query + query_len) {
2613                 if (*pos < MAX_WFD_SUBELEMS &&
2614                     wpa_s->global->wfd_subelem[*pos] &&
2615                     wpabuf_tailroom(resp) >=
2616                     wpabuf_len(wpa_s->global->wfd_subelem[*pos])) {
2617                         wpa_printf(MSG_DEBUG, "P2P: Add WSD response "
2618                                    "subelement %u", *pos);
2619                         wpabuf_put_buf(resp, wpa_s->global->wfd_subelem[*pos]);
2620                 }
2621                 pos++;
2622         }
2623
2624         WPA_PUT_LE16(len_pos, (u8 *) wpabuf_put(resp, 0) - len_pos - 2);
2625 }
2626 #endif /* CONFIG_WIFI_DISPLAY */
2627
2628
2629 static int find_p2ps_substr(struct p2ps_advertisement *adv_data,
2630                             const u8 *needle, size_t needle_len)
2631 {
2632         const u8 *haystack = (const u8 *) adv_data->svc_info;
2633         size_t haystack_len, i;
2634
2635         /* Allow search term to be empty */
2636         if (!needle || !needle_len)
2637                 return 1;
2638
2639         if (!haystack)
2640                 return 0;
2641
2642         haystack_len = os_strlen(adv_data->svc_info);
2643         for (i = 0; i < haystack_len; i++) {
2644                 if (haystack_len - i < needle_len)
2645                         break;
2646                 if (os_memcmp(haystack + i, needle, needle_len) == 0)
2647                         return 1;
2648         }
2649
2650         return 0;
2651 }
2652
2653
2654 static void wpas_sd_req_asp(struct wpa_supplicant *wpa_s,
2655                             struct wpabuf *resp, u8 srv_trans_id,
2656                             const u8 *query, size_t query_len)
2657 {
2658         struct p2ps_advertisement *adv_data;
2659         const u8 *svc = &query[1];
2660         const u8 *info = NULL;
2661         size_t svc_len = query[0];
2662         size_t info_len = 0;
2663         int prefix = 0;
2664         u8 *count_pos = NULL;
2665         u8 *len_pos = NULL;
2666
2667         wpa_hexdump(MSG_DEBUG, "P2P: SD Request for ASP", query, query_len);
2668
2669         if (!wpa_s->global->p2p) {
2670                 wpa_printf(MSG_DEBUG, "P2P: ASP protocol not available");
2671                 wpas_sd_add_proto_not_avail(resp, P2P_SERV_P2PS, srv_trans_id);
2672                 return;
2673         }
2674
2675         /* Info block is optional */
2676         if (svc_len + 1 < query_len) {
2677                 info = &svc[svc_len];
2678                 info_len = *info++;
2679         }
2680
2681         /* Range check length of svc string and info block */
2682         if (svc_len + (info_len ? info_len + 2 : 1) > query_len) {
2683                 wpa_printf(MSG_DEBUG, "P2P: ASP bad request");
2684                 wpas_sd_add_bad_request(resp, P2P_SERV_P2PS, srv_trans_id);
2685                 return;
2686         }
2687
2688         /* Detect and correct for prefix search */
2689         if (svc_len && svc[svc_len - 1] == '*') {
2690                 prefix = 1;
2691                 svc_len--;
2692         }
2693
2694         for (adv_data = p2p_get_p2ps_adv_list(wpa_s->global->p2p);
2695              adv_data; adv_data = adv_data->next) {
2696                 /* If not a prefix match, reject length mismatches */
2697                 if (!prefix && svc_len != os_strlen(adv_data->svc_name))
2698                         continue;
2699
2700                 /* Search each service for request */
2701                 if (os_memcmp(adv_data->svc_name, svc, svc_len) == 0 &&
2702                     find_p2ps_substr(adv_data, info, info_len)) {
2703                         size_t len = os_strlen(adv_data->svc_name);
2704                         size_t svc_info_len = 0;
2705
2706                         if (adv_data->svc_info)
2707                                 svc_info_len = os_strlen(adv_data->svc_info);
2708
2709                         if (len > 0xff || svc_info_len > 0xffff)
2710                                 return;
2711
2712                         /* Length & Count to be filled as we go */
2713                         if (!len_pos && !count_pos) {
2714                                 if (wpabuf_tailroom(resp) <
2715                                     len + svc_info_len + 16)
2716                                         return;
2717
2718                                 len_pos = wpabuf_put(resp, 2);
2719                                 wpabuf_put_u8(resp, P2P_SERV_P2PS);
2720                                 wpabuf_put_u8(resp, srv_trans_id);
2721                                 /* Status Code */
2722                                 wpabuf_put_u8(resp, P2P_SD_SUCCESS);
2723                                 count_pos = wpabuf_put(resp, 1);
2724                                 *count_pos = 0;
2725                         } else if (wpabuf_tailroom(resp) <
2726                                    len + svc_info_len + 10)
2727                                 return;
2728
2729                         if (svc_info_len) {
2730                                 wpa_printf(MSG_DEBUG,
2731                                            "P2P: Add Svc: %s info: %s",
2732                                            adv_data->svc_name,
2733                                            adv_data->svc_info);
2734                         } else {
2735                                 wpa_printf(MSG_DEBUG, "P2P: Add Svc: %s",
2736                                            adv_data->svc_name);
2737                         }
2738
2739                         /* Advertisement ID */
2740                         wpabuf_put_le32(resp, adv_data->id);
2741
2742                         /* Config Methods */
2743                         wpabuf_put_be16(resp, adv_data->config_methods);
2744
2745                         /* Service Name */
2746                         wpabuf_put_u8(resp, (u8) len);
2747                         wpabuf_put_data(resp, adv_data->svc_name, len);
2748
2749                         /* Service State */
2750                         wpabuf_put_u8(resp, adv_data->state);
2751
2752                         /* Service Information */
2753                         wpabuf_put_le16(resp, (u16) svc_info_len);
2754                         wpabuf_put_data(resp, adv_data->svc_info, svc_info_len);
2755
2756                         /* Update length and count */
2757                         (*count_pos)++;
2758                         WPA_PUT_LE16(len_pos,
2759                                      (u8 *) wpabuf_put(resp, 0) - len_pos - 2);
2760                 }
2761         }
2762
2763         /* Return error if no matching svc found */
2764         if (count_pos == NULL) {
2765                 wpa_printf(MSG_DEBUG, "P2P: ASP service not found");
2766                 wpas_sd_add_not_found(resp, P2P_SERV_P2PS, srv_trans_id);
2767         }
2768 }
2769
2770
2771 static void wpas_sd_request(void *ctx, int freq, const u8 *sa, u8 dialog_token,
2772                             u16 update_indic, const u8 *tlvs, size_t tlvs_len)
2773 {
2774         struct wpa_supplicant *wpa_s = ctx;
2775         const u8 *pos = tlvs;
2776         const u8 *end = tlvs + tlvs_len;
2777         const u8 *tlv_end;
2778         u16 slen;
2779         struct wpabuf *resp;
2780         u8 srv_proto, srv_trans_id;
2781         size_t buf_len;
2782         char *buf;
2783
2784         wpa_hexdump(MSG_MSGDUMP, "P2P: Service Discovery Request TLVs",
2785                     tlvs, tlvs_len);
2786         buf_len = 2 * tlvs_len + 1;
2787         buf = os_malloc(buf_len);
2788         if (buf) {
2789                 wpa_snprintf_hex(buf, buf_len, tlvs, tlvs_len);
2790                 wpa_msg_ctrl(wpa_s, MSG_INFO, P2P_EVENT_SERV_DISC_REQ "%d "
2791                              MACSTR " %u %u %s",
2792                              freq, MAC2STR(sa), dialog_token, update_indic,
2793                              buf);
2794                 os_free(buf);
2795         }
2796
2797         if (wpa_s->p2p_sd_over_ctrl_iface) {
2798                 wpas_notify_p2p_sd_request(wpa_s, freq, sa, dialog_token,
2799                                            update_indic, tlvs, tlvs_len);
2800                 return; /* to be processed by an external program */
2801         }
2802
2803         resp = wpabuf_alloc(10000);
2804         if (resp == NULL)
2805                 return;
2806
2807         while (pos + 1 < end) {
2808                 wpa_printf(MSG_DEBUG, "P2P: Service Request TLV");
2809                 slen = WPA_GET_LE16(pos);
2810                 pos += 2;
2811                 if (pos + slen > end || slen < 2) {
2812                         wpa_printf(MSG_DEBUG, "P2P: Unexpected Query Data "
2813                                    "length");
2814                         wpabuf_free(resp);
2815                         return;
2816                 }
2817                 tlv_end = pos + slen;
2818
2819                 srv_proto = *pos++;
2820                 wpa_printf(MSG_DEBUG, "P2P: Service Protocol Type %u",
2821                            srv_proto);
2822                 srv_trans_id = *pos++;
2823                 wpa_printf(MSG_DEBUG, "P2P: Service Transaction ID %u",
2824                            srv_trans_id);
2825
2826                 wpa_hexdump(MSG_MSGDUMP, "P2P: Query Data",
2827                             pos, tlv_end - pos);
2828
2829
2830                 if (wpa_s->force_long_sd) {
2831                         wpa_printf(MSG_DEBUG, "P2P: SD test - force long "
2832                                    "response");
2833                         wpas_sd_all_bonjour(wpa_s, resp, srv_trans_id);
2834                         wpas_sd_all_upnp(wpa_s, resp, srv_trans_id);
2835                         goto done;
2836                 }
2837
2838                 switch (srv_proto) {
2839                 case P2P_SERV_ALL_SERVICES:
2840                         wpa_printf(MSG_DEBUG, "P2P: Service Discovery Request "
2841                                    "for all services");
2842                         if (dl_list_empty(&wpa_s->global->p2p_srv_upnp) &&
2843                             dl_list_empty(&wpa_s->global->p2p_srv_bonjour)) {
2844                                 wpa_printf(MSG_DEBUG, "P2P: No service "
2845                                            "discovery protocols available");
2846                                 wpas_sd_add_proto_not_avail(
2847                                         resp, P2P_SERV_ALL_SERVICES,
2848                                         srv_trans_id);
2849                                 break;
2850                         }
2851                         wpas_sd_all_bonjour(wpa_s, resp, srv_trans_id);
2852                         wpas_sd_all_upnp(wpa_s, resp, srv_trans_id);
2853                         break;
2854                 case P2P_SERV_BONJOUR:
2855                         wpas_sd_req_bonjour(wpa_s, resp, srv_trans_id,
2856                                             pos, tlv_end - pos);
2857                         break;
2858                 case P2P_SERV_UPNP:
2859                         wpas_sd_req_upnp(wpa_s, resp, srv_trans_id,
2860                                          pos, tlv_end - pos);
2861                         break;
2862 #ifdef CONFIG_WIFI_DISPLAY
2863                 case P2P_SERV_WIFI_DISPLAY:
2864                         wpas_sd_req_wfd(wpa_s, resp, srv_trans_id,
2865                                         pos, tlv_end - pos);
2866                         break;
2867 #endif /* CONFIG_WIFI_DISPLAY */
2868                 case P2P_SERV_P2PS:
2869                         wpas_sd_req_asp(wpa_s, resp, srv_trans_id,
2870                                         pos, tlv_end - pos);
2871                         break;
2872                 default:
2873                         wpa_printf(MSG_DEBUG, "P2P: Unavailable service "
2874                                    "protocol %u", srv_proto);
2875                         wpas_sd_add_proto_not_avail(resp, srv_proto,
2876                                                     srv_trans_id);
2877                         break;
2878                 }
2879
2880                 pos = tlv_end;
2881         }
2882
2883 done:
2884         wpas_notify_p2p_sd_request(wpa_s, freq, sa, dialog_token,
2885                                    update_indic, tlvs, tlvs_len);
2886
2887         wpas_p2p_sd_response(wpa_s, freq, sa, dialog_token, resp);
2888
2889         wpabuf_free(resp);
2890 }
2891
2892
2893 static void wpas_sd_p2ps_serv_response(struct wpa_supplicant *wpa_s,
2894                                        const u8 *sa, u8 srv_trans_id,
2895                                        const u8 *pos, const u8 *tlv_end)
2896 {
2897         u8 left = *pos++;
2898         u32 adv_id;
2899         u8 svc_status;
2900         u16 config_methods;
2901         char svc_str[256];
2902
2903         while (left-- && pos < tlv_end) {
2904                 char *buf = NULL;
2905                 size_t buf_len;
2906                 u8 svc_len;
2907
2908                 /* Sanity check fixed length+svc_str */
2909                 if (pos + 6 >= tlv_end)
2910                         break;
2911                 svc_len = pos[6];
2912                 if (pos + svc_len + 10 > tlv_end)
2913                         break;
2914
2915                 /* Advertisement ID */
2916                 adv_id = WPA_GET_LE32(pos);
2917                 pos += sizeof(u32);
2918
2919                 /* Config Methods */
2920                 config_methods = WPA_GET_BE16(pos);
2921                 pos += sizeof(u16);
2922
2923                 /* Service Name */
2924                 pos++; /* svc_len */
2925                 os_memcpy(svc_str, pos, svc_len);
2926                 svc_str[svc_len] = '\0';
2927                 pos += svc_len;
2928
2929                 /* Service Status */
2930                 svc_status = *pos++;
2931
2932                 /* Service Information Length */
2933                 buf_len = WPA_GET_LE16(pos);
2934                 pos += sizeof(u16);
2935
2936                 /* Sanity check buffer length */
2937                 if (buf_len > (unsigned int) (tlv_end - pos))
2938                         break;
2939
2940                 if (buf_len) {
2941                         buf = os_zalloc(2 * buf_len + 1);
2942                         if (buf) {
2943                                 utf8_escape((const char *) pos, buf_len, buf,
2944                                             2 * buf_len + 1);
2945                         }
2946                 }
2947
2948                 pos += buf_len;
2949
2950                 if (buf) {
2951                         wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_SERV_ASP_RESP
2952                                        MACSTR " %x %x %x %x %s '%s'",
2953                                        MAC2STR(sa), srv_trans_id, adv_id,
2954                                        svc_status, config_methods, svc_str,
2955                                        buf);
2956                         os_free(buf);
2957                 } else {
2958                         wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_SERV_ASP_RESP
2959                                        MACSTR " %x %x %x %x %s",
2960                                        MAC2STR(sa), srv_trans_id, adv_id,
2961                                        svc_status, config_methods, svc_str);
2962                 }
2963         }
2964 }
2965
2966
2967 static void wpas_sd_response(void *ctx, const u8 *sa, u16 update_indic,
2968                              const u8 *tlvs, size_t tlvs_len)
2969 {
2970         struct wpa_supplicant *wpa_s = ctx;
2971         const u8 *pos = tlvs;
2972         const u8 *end = tlvs + tlvs_len;
2973         const u8 *tlv_end;
2974         u16 slen;
2975         size_t buf_len;
2976         char *buf;
2977
2978         wpa_hexdump(MSG_MSGDUMP, "P2P: Service Discovery Response TLVs",
2979                     tlvs, tlvs_len);
2980         if (tlvs_len > 1500) {
2981                 /* TODO: better way for handling this */
2982                 wpa_msg_ctrl(wpa_s, MSG_INFO,
2983                              P2P_EVENT_SERV_DISC_RESP MACSTR
2984                              " %u <long response: %u bytes>",
2985                              MAC2STR(sa), update_indic,
2986                              (unsigned int) tlvs_len);
2987         } else {
2988                 buf_len = 2 * tlvs_len + 1;
2989                 buf = os_malloc(buf_len);
2990                 if (buf) {
2991                         wpa_snprintf_hex(buf, buf_len, tlvs, tlvs_len);
2992                         wpa_msg_ctrl(wpa_s, MSG_INFO,
2993                                      P2P_EVENT_SERV_DISC_RESP MACSTR " %u %s",
2994                                      MAC2STR(sa), update_indic, buf);
2995                         os_free(buf);
2996                 }
2997         }
2998
2999         while (pos < end) {
3000                 u8 srv_proto, srv_trans_id, status;
3001
3002                 wpa_printf(MSG_DEBUG, "P2P: Service Response TLV");
3003                 slen = WPA_GET_LE16(pos);
3004                 pos += 2;
3005                 if (pos + slen > end || slen < 3) {
3006                         wpa_printf(MSG_DEBUG, "P2P: Unexpected Response Data "
3007                                    "length");
3008                         return;
3009                 }
3010                 tlv_end = pos + slen;
3011
3012                 srv_proto = *pos++;
3013                 wpa_printf(MSG_DEBUG, "P2P: Service Protocol Type %u",
3014                            srv_proto);
3015                 srv_trans_id = *pos++;
3016                 wpa_printf(MSG_DEBUG, "P2P: Service Transaction ID %u",
3017                            srv_trans_id);
3018                 status = *pos++;
3019                 wpa_printf(MSG_DEBUG, "P2P: Status Code ID %u",
3020                            status);
3021
3022                 wpa_hexdump(MSG_MSGDUMP, "P2P: Response Data",
3023                             pos, tlv_end - pos);
3024
3025                 if (srv_proto == P2P_SERV_P2PS && pos < tlv_end) {
3026                         wpas_sd_p2ps_serv_response(wpa_s, sa, srv_trans_id,
3027                                                    pos, tlv_end);
3028                 }
3029
3030                 pos = tlv_end;
3031         }
3032
3033         wpas_notify_p2p_sd_response(wpa_s, sa, update_indic, tlvs, tlvs_len);
3034 }
3035
3036
3037 u64 wpas_p2p_sd_request(struct wpa_supplicant *wpa_s, const u8 *dst,
3038                         const struct wpabuf *tlvs)
3039 {
3040         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
3041                 return 0;
3042         return (uintptr_t) p2p_sd_request(wpa_s->global->p2p, dst, tlvs);
3043 }
3044
3045
3046 u64 wpas_p2p_sd_request_upnp(struct wpa_supplicant *wpa_s, const u8 *dst,
3047                              u8 version, const char *query)
3048 {
3049         struct wpabuf *tlvs;
3050         u64 ret;
3051
3052         tlvs = wpabuf_alloc(2 + 1 + 1 + 1 + os_strlen(query));
3053         if (tlvs == NULL)
3054                 return 0;
3055         wpabuf_put_le16(tlvs, 1 + 1 + 1 + os_strlen(query));
3056         wpabuf_put_u8(tlvs, P2P_SERV_UPNP); /* Service Protocol Type */
3057         wpabuf_put_u8(tlvs, 1); /* Service Transaction ID */
3058         wpabuf_put_u8(tlvs, version);
3059         wpabuf_put_str(tlvs, query);
3060         ret = wpas_p2p_sd_request(wpa_s, dst, tlvs);
3061         wpabuf_free(tlvs);
3062         return ret;
3063 }
3064
3065
3066 u64 wpas_p2p_sd_request_asp(struct wpa_supplicant *wpa_s, const u8 *dst, u8 id,
3067                             const char *svc_str, const char *info_substr)
3068 {
3069         struct wpabuf *tlvs;
3070         size_t plen, svc_len, substr_len = 0;
3071         u64 ret;
3072
3073         svc_len = os_strlen(svc_str);
3074         if (info_substr)
3075                 substr_len = os_strlen(info_substr);
3076
3077         if (svc_len > 0xff || substr_len > 0xff)
3078                 return 0;
3079
3080         plen = 1 + 1 + 1 + svc_len + 1 + substr_len;
3081         tlvs = wpabuf_alloc(2 + plen);
3082         if (tlvs == NULL)
3083                 return 0;
3084
3085         wpabuf_put_le16(tlvs, plen);
3086         wpabuf_put_u8(tlvs, P2P_SERV_P2PS);
3087         wpabuf_put_u8(tlvs, id); /* Service Transaction ID */
3088         wpabuf_put_u8(tlvs, (u8) svc_len); /* Service String Length */
3089         wpabuf_put_data(tlvs, svc_str, svc_len);
3090         wpabuf_put_u8(tlvs, (u8) substr_len); /* Info Substring Length */
3091         wpabuf_put_data(tlvs, info_substr, substr_len);
3092         ret = wpas_p2p_sd_request(wpa_s, dst, tlvs);
3093         wpabuf_free(tlvs);
3094
3095         return ret;
3096 }
3097
3098
3099 #ifdef CONFIG_WIFI_DISPLAY
3100
3101 static u64 wpas_p2p_sd_request_wfd(struct wpa_supplicant *wpa_s, const u8 *dst,
3102                                    const struct wpabuf *tlvs)
3103 {
3104         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
3105                 return 0;
3106         return (uintptr_t) p2p_sd_request_wfd(wpa_s->global->p2p, dst, tlvs);
3107 }
3108
3109
3110 #define MAX_WFD_SD_SUBELEMS 20
3111
3112 static void wfd_add_sd_req_role(struct wpabuf *tlvs, u8 id, u8 role,
3113                                 const char *subelems)
3114 {
3115         u8 *len;
3116         const char *pos;
3117         int val;
3118         int count = 0;
3119
3120         len = wpabuf_put(tlvs, 2);
3121         wpabuf_put_u8(tlvs, P2P_SERV_WIFI_DISPLAY); /* Service Protocol Type */
3122         wpabuf_put_u8(tlvs, id); /* Service Transaction ID */
3123
3124         wpabuf_put_u8(tlvs, role);
3125
3126         pos = subelems;
3127         while (*pos) {
3128                 val = atoi(pos);
3129                 if (val >= 0 && val < 256) {
3130                         wpabuf_put_u8(tlvs, val);
3131                         count++;
3132                         if (count == MAX_WFD_SD_SUBELEMS)
3133                                 break;
3134                 }
3135                 pos = os_strchr(pos + 1, ',');
3136                 if (pos == NULL)
3137                         break;
3138                 pos++;
3139         }
3140
3141         WPA_PUT_LE16(len, (u8 *) wpabuf_put(tlvs, 0) - len - 2);
3142 }
3143
3144
3145 u64 wpas_p2p_sd_request_wifi_display(struct wpa_supplicant *wpa_s,
3146                                      const u8 *dst, const char *role)
3147 {
3148         struct wpabuf *tlvs;
3149         u64 ret;
3150         const char *subelems;
3151         u8 id = 1;
3152
3153         subelems = os_strchr(role, ' ');
3154         if (subelems == NULL)
3155                 return 0;
3156         subelems++;
3157
3158         tlvs = wpabuf_alloc(4 * (2 + 1 + 1 + 1 + MAX_WFD_SD_SUBELEMS));
3159         if (tlvs == NULL)
3160                 return 0;
3161
3162         if (os_strstr(role, "[source]"))
3163                 wfd_add_sd_req_role(tlvs, id++, 0x00, subelems);
3164         if (os_strstr(role, "[pri-sink]"))
3165                 wfd_add_sd_req_role(tlvs, id++, 0x01, subelems);
3166         if (os_strstr(role, "[sec-sink]"))
3167                 wfd_add_sd_req_role(tlvs, id++, 0x02, subelems);
3168         if (os_strstr(role, "[source+sink]"))
3169                 wfd_add_sd_req_role(tlvs, id++, 0x03, subelems);
3170
3171         ret = wpas_p2p_sd_request_wfd(wpa_s, dst, tlvs);
3172         wpabuf_free(tlvs);
3173         return ret;
3174 }
3175
3176 #endif /* CONFIG_WIFI_DISPLAY */
3177
3178
3179 int wpas_p2p_sd_cancel_request(struct wpa_supplicant *wpa_s, u64 req)
3180 {
3181         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
3182                 return -1;
3183         return p2p_sd_cancel_request(wpa_s->global->p2p,
3184                                      (void *) (uintptr_t) req);
3185 }
3186
3187
3188 void wpas_p2p_sd_response(struct wpa_supplicant *wpa_s, int freq,
3189                           const u8 *dst, u8 dialog_token,
3190                           const struct wpabuf *resp_tlvs)
3191 {
3192         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
3193                 return;
3194         p2p_sd_response(wpa_s->global->p2p, freq, dst, dialog_token,
3195                         resp_tlvs);
3196 }
3197
3198
3199 void wpas_p2p_sd_service_update(struct wpa_supplicant *wpa_s)
3200 {
3201         if (wpa_s->global->p2p)
3202                 p2p_sd_service_update(wpa_s->global->p2p);
3203 }
3204
3205
3206 static void wpas_p2p_srv_bonjour_free(struct p2p_srv_bonjour *bsrv)
3207 {
3208         dl_list_del(&bsrv->list);
3209         wpabuf_free(bsrv->query);
3210         wpabuf_free(bsrv->resp);
3211         os_free(bsrv);
3212 }
3213
3214
3215 static void wpas_p2p_srv_upnp_free(struct p2p_srv_upnp *usrv)
3216 {
3217         dl_list_del(&usrv->list);
3218         os_free(usrv->service);
3219         os_free(usrv);
3220 }
3221
3222
3223 void wpas_p2p_service_flush(struct wpa_supplicant *wpa_s)
3224 {
3225         struct p2p_srv_bonjour *bsrv, *bn;
3226         struct p2p_srv_upnp *usrv, *un;
3227
3228         dl_list_for_each_safe(bsrv, bn, &wpa_s->global->p2p_srv_bonjour,
3229                               struct p2p_srv_bonjour, list)
3230                 wpas_p2p_srv_bonjour_free(bsrv);
3231
3232         dl_list_for_each_safe(usrv, un, &wpa_s->global->p2p_srv_upnp,
3233                               struct p2p_srv_upnp, list)
3234                 wpas_p2p_srv_upnp_free(usrv);
3235
3236         wpas_p2p_sd_service_update(wpa_s);
3237 }
3238
3239
3240 int wpas_p2p_service_p2ps_id_exists(struct wpa_supplicant *wpa_s, u32 adv_id)
3241 {
3242         if (adv_id == 0)
3243                 return 1;
3244
3245         if (p2p_service_p2ps_id(wpa_s->global->p2p, adv_id))
3246                 return 1;
3247
3248         return 0;
3249 }
3250
3251
3252 int wpas_p2p_service_del_asp(struct wpa_supplicant *wpa_s, u32 adv_id)
3253 {
3254         return p2p_service_del_asp(wpa_s->global->p2p, adv_id);
3255 }
3256
3257
3258 int wpas_p2p_service_add_asp(struct wpa_supplicant *wpa_s,
3259                              int auto_accept, u32 adv_id,
3260                              const char *adv_str, u8 svc_state,
3261                              u16 config_methods, const char *svc_info)
3262 {
3263         return p2p_service_add_asp(wpa_s->global->p2p, auto_accept, adv_id,
3264                                    adv_str, svc_state, config_methods,
3265                                    svc_info);
3266 }
3267
3268
3269 int wpas_p2p_service_add_bonjour(struct wpa_supplicant *wpa_s,
3270                                  struct wpabuf *query, struct wpabuf *resp)
3271 {
3272         struct p2p_srv_bonjour *bsrv;
3273
3274         bsrv = os_zalloc(sizeof(*bsrv));
3275         if (bsrv == NULL)
3276                 return -1;
3277         bsrv->query = query;
3278         bsrv->resp = resp;
3279         dl_list_add(&wpa_s->global->p2p_srv_bonjour, &bsrv->list);
3280
3281         wpas_p2p_sd_service_update(wpa_s);
3282         return 0;
3283 }
3284
3285
3286 int wpas_p2p_service_del_bonjour(struct wpa_supplicant *wpa_s,
3287                                  const struct wpabuf *query)
3288 {
3289         struct p2p_srv_bonjour *bsrv;
3290
3291         bsrv = wpas_p2p_service_get_bonjour(wpa_s, query);
3292         if (bsrv == NULL)
3293                 return -1;
3294         wpas_p2p_srv_bonjour_free(bsrv);
3295         wpas_p2p_sd_service_update(wpa_s);
3296         return 0;
3297 }
3298
3299
3300 int wpas_p2p_service_add_upnp(struct wpa_supplicant *wpa_s, u8 version,
3301                               const char *service)
3302 {
3303         struct p2p_srv_upnp *usrv;
3304
3305         if (wpas_p2p_service_get_upnp(wpa_s, version, service))
3306                 return 0; /* Already listed */
3307         usrv = os_zalloc(sizeof(*usrv));
3308         if (usrv == NULL)
3309                 return -1;
3310         usrv->version = version;
3311         usrv->service = os_strdup(service);
3312         if (usrv->service == NULL) {
3313                 os_free(usrv);
3314                 return -1;
3315         }
3316         dl_list_add(&wpa_s->global->p2p_srv_upnp, &usrv->list);
3317
3318         wpas_p2p_sd_service_update(wpa_s);
3319         return 0;
3320 }
3321
3322
3323 int wpas_p2p_service_del_upnp(struct wpa_supplicant *wpa_s, u8 version,
3324                               const char *service)
3325 {
3326         struct p2p_srv_upnp *usrv;
3327
3328         usrv = wpas_p2p_service_get_upnp(wpa_s, version, service);
3329         if (usrv == NULL)
3330                 return -1;
3331         wpas_p2p_srv_upnp_free(usrv);
3332         wpas_p2p_sd_service_update(wpa_s);
3333         return 0;
3334 }
3335
3336
3337 static void wpas_prov_disc_local_display(struct wpa_supplicant *wpa_s,
3338                                          const u8 *peer, const char *params,
3339                                          unsigned int generated_pin)
3340 {
3341         wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_PROV_DISC_SHOW_PIN MACSTR
3342                        " %08d%s", MAC2STR(peer), generated_pin, params);
3343 }
3344
3345
3346 static void wpas_prov_disc_local_keypad(struct wpa_supplicant *wpa_s,
3347                                         const u8 *peer, const char *params)
3348 {
3349         wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_PROV_DISC_ENTER_PIN MACSTR
3350                        "%s", MAC2STR(peer), params);
3351 }
3352
3353
3354 static void wpas_prov_disc_req(void *ctx, const u8 *peer, u16 config_methods,
3355                                const u8 *dev_addr, const u8 *pri_dev_type,
3356                                const char *dev_name, u16 supp_config_methods,
3357                                u8 dev_capab, u8 group_capab, const u8 *group_id,
3358                                size_t group_id_len)
3359 {
3360         struct wpa_supplicant *wpa_s = ctx;
3361         char devtype[WPS_DEV_TYPE_BUFSIZE];
3362         char params[300];
3363         u8 empty_dev_type[8];
3364         unsigned int generated_pin = 0;
3365         struct wpa_supplicant *group = NULL;
3366         int res;
3367
3368         if (group_id) {
3369                 for (group = wpa_s->global->ifaces; group; group = group->next)
3370                 {
3371                         struct wpa_ssid *s = group->current_ssid;
3372                         if (s != NULL &&
3373                             s->mode == WPAS_MODE_P2P_GO &&
3374                             group_id_len - ETH_ALEN == s->ssid_len &&
3375                             os_memcmp(group_id + ETH_ALEN, s->ssid,
3376                                       s->ssid_len) == 0)
3377                                 break;
3378                 }
3379         }
3380
3381         if (pri_dev_type == NULL) {
3382                 os_memset(empty_dev_type, 0, sizeof(empty_dev_type));
3383                 pri_dev_type = empty_dev_type;
3384         }
3385         res = os_snprintf(params, sizeof(params), " p2p_dev_addr=" MACSTR
3386                           " pri_dev_type=%s name='%s' config_methods=0x%x "
3387                           "dev_capab=0x%x group_capab=0x%x%s%s",
3388                           MAC2STR(dev_addr),
3389                           wps_dev_type_bin2str(pri_dev_type, devtype,
3390                                                sizeof(devtype)),
3391                           dev_name, supp_config_methods, dev_capab, group_capab,
3392                           group ? " group=" : "",
3393                           group ? group->ifname : "");
3394         if (os_snprintf_error(sizeof(params), res))
3395                 wpa_printf(MSG_DEBUG, "P2P: PD Request event truncated");
3396         params[sizeof(params) - 1] = '\0';
3397
3398         if (config_methods & WPS_CONFIG_DISPLAY) {
3399                 generated_pin = wps_generate_pin();
3400                 wpas_prov_disc_local_display(wpa_s, peer, params,
3401                                              generated_pin);
3402         } else if (config_methods & WPS_CONFIG_KEYPAD)
3403                 wpas_prov_disc_local_keypad(wpa_s, peer, params);
3404         else if (config_methods & WPS_CONFIG_PUSHBUTTON)
3405                 wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_PROV_DISC_PBC_REQ
3406                                MACSTR "%s", MAC2STR(peer), params);
3407
3408         wpas_notify_p2p_provision_discovery(wpa_s, peer, 1 /* request */,
3409                                             P2P_PROV_DISC_SUCCESS,
3410                                             config_methods, generated_pin);
3411 }
3412
3413
3414 static void wpas_prov_disc_resp(void *ctx, const u8 *peer, u16 config_methods)
3415 {
3416         struct wpa_supplicant *wpa_s = ctx;
3417         unsigned int generated_pin = 0;
3418         char params[20];
3419
3420         if (wpa_s->pending_pd_before_join &&
3421             (os_memcmp(peer, wpa_s->pending_join_dev_addr, ETH_ALEN) == 0 ||
3422              os_memcmp(peer, wpa_s->pending_join_iface_addr, ETH_ALEN) == 0)) {
3423                 wpa_s->pending_pd_before_join = 0;
3424                 wpa_printf(MSG_DEBUG, "P2P: Starting pending "
3425                            "join-existing-group operation");
3426                 wpas_p2p_join_start(wpa_s, 0, NULL, 0);
3427                 return;
3428         }
3429
3430         if (wpa_s->pending_pd_use == AUTO_PD_JOIN ||
3431             wpa_s->pending_pd_use == AUTO_PD_GO_NEG) {
3432                 int res;
3433
3434                 res = os_snprintf(params, sizeof(params), " peer_go=%d",
3435                                   wpa_s->pending_pd_use == AUTO_PD_JOIN);
3436                 if (os_snprintf_error(sizeof(params), res))
3437                         params[sizeof(params) - 1] = '\0';
3438         } else
3439                 params[0] = '\0';
3440
3441         if (config_methods & WPS_CONFIG_DISPLAY)
3442                 wpas_prov_disc_local_keypad(wpa_s, peer, params);
3443         else if (config_methods & WPS_CONFIG_KEYPAD) {
3444                 generated_pin = wps_generate_pin();
3445                 wpas_prov_disc_local_display(wpa_s, peer, params,
3446                                              generated_pin);
3447         } else if (config_methods & WPS_CONFIG_PUSHBUTTON)
3448                 wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_PROV_DISC_PBC_RESP
3449                                MACSTR "%s", MAC2STR(peer), params);
3450
3451         wpas_notify_p2p_provision_discovery(wpa_s, peer, 0 /* response */,
3452                                             P2P_PROV_DISC_SUCCESS,
3453                                             config_methods, generated_pin);
3454 }
3455
3456
3457 static void wpas_prov_disc_fail(void *ctx, const u8 *peer,
3458                                 enum p2p_prov_disc_status status)
3459 {
3460         struct wpa_supplicant *wpa_s = ctx;
3461
3462         if (wpa_s->p2p_fallback_to_go_neg) {
3463                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: PD for p2p_connect-auto "
3464                         "failed - fall back to GO Negotiation");
3465                 wpas_p2p_fallback_to_go_neg(wpa_s, 0);
3466                 return;
3467         }
3468
3469         if (status == P2P_PROV_DISC_TIMEOUT_JOIN) {
3470                 wpa_s->pending_pd_before_join = 0;
3471                 wpa_printf(MSG_DEBUG, "P2P: Starting pending "
3472                            "join-existing-group operation (no ACK for PD "
3473                            "Req attempts)");
3474                 wpas_p2p_join_start(wpa_s, 0, NULL, 0);
3475                 return;
3476         }
3477
3478         wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_PROV_DISC_FAILURE
3479                        " p2p_dev_addr=" MACSTR " status=%d",
3480                        MAC2STR(peer), status);
3481
3482         wpas_notify_p2p_provision_discovery(wpa_s, peer, 0 /* response */,
3483                                             status, 0, 0);
3484 }
3485
3486
3487 static int freq_included(const struct p2p_channels *channels, unsigned int freq)
3488 {
3489         if (channels == NULL)
3490                 return 1; /* Assume no restrictions */
3491         return p2p_channels_includes_freq(channels, freq);
3492
3493 }
3494
3495
3496 /**
3497  * Pick the best frequency to use from all the currently used frequencies.
3498  */
3499 static int wpas_p2p_pick_best_used_freq(struct wpa_supplicant *wpa_s,
3500                                         struct wpa_used_freq_data *freqs,
3501                                         unsigned int num)
3502 {
3503         unsigned int i, c;
3504
3505         /* find a candidate freq that is supported by P2P */
3506         for (c = 0; c < num; c++)
3507                 if (p2p_supported_freq(wpa_s->global->p2p, freqs[c].freq))
3508                         break;
3509
3510         if (c == num)
3511                 return 0;
3512
3513         /* once we have a candidate, try to find a 'better' one */
3514         for (i = c + 1; i < num; i++) {
3515                 if (!p2p_supported_freq(wpa_s->global->p2p, freqs[i].freq))
3516                         continue;
3517
3518                 /*
3519                  * 1. Infrastructure station interfaces have higher preference.
3520                  * 2. P2P Clients have higher preference.
3521                  * 3. All others.
3522                  */
3523                 if (freqs[i].flags & WPA_FREQ_USED_BY_INFRA_STATION) {
3524                         c = i;
3525                         break;
3526                 }
3527
3528                 if ((freqs[i].flags & WPA_FREQ_USED_BY_P2P_CLIENT))
3529                         c = i;
3530         }
3531         return freqs[c].freq;
3532 }
3533
3534
3535 static u8 wpas_invitation_process(void *ctx, const u8 *sa, const u8 *bssid,
3536                                   const u8 *go_dev_addr, const u8 *ssid,
3537                                   size_t ssid_len, int *go, u8 *group_bssid,
3538                                   int *force_freq, int persistent_group,
3539                                   const struct p2p_channels *channels,
3540                                   int dev_pw_id)
3541 {
3542         struct wpa_supplicant *wpa_s = ctx;
3543         struct wpa_ssid *s;
3544         struct wpa_used_freq_data *freqs;
3545         struct wpa_supplicant *grp;
3546         int best_freq;
3547
3548         if (!persistent_group) {
3549                 wpa_printf(MSG_DEBUG, "P2P: Invitation from " MACSTR
3550                            " to join an active group (SSID: %s)",
3551                            MAC2STR(sa), wpa_ssid_txt(ssid, ssid_len));
3552                 if (!is_zero_ether_addr(wpa_s->p2p_auth_invite) &&
3553                     (os_memcmp(go_dev_addr, wpa_s->p2p_auth_invite, ETH_ALEN)
3554                      == 0 ||
3555                      os_memcmp(sa, wpa_s->p2p_auth_invite, ETH_ALEN) == 0)) {
3556                         wpa_printf(MSG_DEBUG, "P2P: Accept previously "
3557                                    "authorized invitation");
3558                         goto accept_inv;
3559                 }
3560
3561 #ifdef CONFIG_WPS_NFC
3562                 if (dev_pw_id >= 0 && wpa_s->p2p_nfc_tag_enabled &&
3563                     dev_pw_id == wpa_s->p2p_oob_dev_pw_id) {
3564                         wpa_printf(MSG_DEBUG, "P2P: Accept invitation based on local enabled NFC Tag");
3565                         wpa_s->p2p_wps_method = WPS_NFC;
3566                         wpa_s->pending_join_wps_method = WPS_NFC;
3567                         os_memcpy(wpa_s->pending_join_dev_addr,
3568                                   go_dev_addr, ETH_ALEN);
3569                         os_memcpy(wpa_s->pending_join_iface_addr,
3570                                   bssid, ETH_ALEN);
3571                         goto accept_inv;
3572                 }
3573 #endif /* CONFIG_WPS_NFC */
3574
3575                 /*
3576                  * Do not accept the invitation automatically; notify user and
3577                  * request approval.
3578                  */
3579                 return P2P_SC_FAIL_INFO_CURRENTLY_UNAVAILABLE;
3580         }
3581
3582         grp = wpas_get_p2p_group(wpa_s, ssid, ssid_len, go);
3583         if (grp) {
3584                 wpa_printf(MSG_DEBUG, "P2P: Accept invitation to already "
3585                            "running persistent group");
3586                 if (*go)
3587                         os_memcpy(group_bssid, grp->own_addr, ETH_ALEN);
3588                 goto accept_inv;
3589         }
3590
3591         if (!is_zero_ether_addr(wpa_s->p2p_auth_invite) &&
3592             os_memcmp(sa, wpa_s->p2p_auth_invite, ETH_ALEN) == 0) {
3593                 wpa_printf(MSG_DEBUG, "P2P: Accept previously initiated "
3594                            "invitation to re-invoke a persistent group");
3595                 os_memset(wpa_s->p2p_auth_invite, 0, ETH_ALEN);
3596         } else if (!wpa_s->conf->persistent_reconnect)
3597                 return P2P_SC_FAIL_INFO_CURRENTLY_UNAVAILABLE;
3598
3599         for (s = wpa_s->conf->ssid; s; s = s->next) {
3600                 if (s->disabled == 2 &&
3601                     os_memcmp(s->bssid, go_dev_addr, ETH_ALEN) == 0 &&
3602                     s->ssid_len == ssid_len &&
3603                     os_memcmp(ssid, s->ssid, ssid_len) == 0)
3604                         break;
3605         }
3606
3607         if (!s) {
3608                 wpa_printf(MSG_DEBUG, "P2P: Invitation from " MACSTR
3609                            " requested reinvocation of an unknown group",
3610                            MAC2STR(sa));
3611                 return P2P_SC_FAIL_UNKNOWN_GROUP;
3612         }
3613
3614         if (s->mode == WPAS_MODE_P2P_GO && !wpas_p2p_create_iface(wpa_s)) {
3615                 *go = 1;
3616                 if (wpa_s->wpa_state >= WPA_AUTHENTICATING) {
3617                         wpa_printf(MSG_DEBUG, "P2P: The only available "
3618                                    "interface is already in use - reject "
3619                                    "invitation");
3620                         return P2P_SC_FAIL_UNABLE_TO_ACCOMMODATE;
3621                 }
3622                 os_memcpy(group_bssid, wpa_s->own_addr, ETH_ALEN);
3623         } else if (s->mode == WPAS_MODE_P2P_GO) {
3624                 *go = 1;
3625                 if (wpas_p2p_add_group_interface(wpa_s, WPA_IF_P2P_GO) < 0)
3626                 {
3627                         wpa_printf(MSG_ERROR, "P2P: Failed to allocate a new "
3628                                    "interface address for the group");
3629                         return P2P_SC_FAIL_UNABLE_TO_ACCOMMODATE;
3630                 }
3631                 os_memcpy(group_bssid, wpa_s->pending_interface_addr,
3632                           ETH_ALEN);
3633         }
3634
3635 accept_inv:
3636         wpas_p2p_set_own_freq_preference(wpa_s, 0);
3637
3638         best_freq = 0;
3639         freqs = os_calloc(wpa_s->num_multichan_concurrent,
3640                           sizeof(struct wpa_used_freq_data));
3641         if (freqs) {
3642                 int num_channels = wpa_s->num_multichan_concurrent;
3643                 int num = wpas_p2p_valid_oper_freqs(wpa_s, freqs, num_channels);
3644                 best_freq = wpas_p2p_pick_best_used_freq(wpa_s, freqs, num);
3645                 os_free(freqs);
3646         }
3647
3648         /* Get one of the frequencies currently in use */
3649         if (best_freq > 0) {
3650                 wpa_printf(MSG_DEBUG, "P2P: Trying to prefer a channel already used by one of the interfaces");
3651                 wpas_p2p_set_own_freq_preference(wpa_s, best_freq);
3652
3653                 if (wpa_s->num_multichan_concurrent < 2 ||
3654                     wpas_p2p_num_unused_channels(wpa_s) < 1) {
3655                         wpa_printf(MSG_DEBUG, "P2P: No extra channels available - trying to force channel to match a channel already used by one of the interfaces");
3656                         *force_freq = best_freq;
3657                 }
3658         }
3659
3660         if (*force_freq > 0 && wpa_s->num_multichan_concurrent > 1 &&
3661             wpas_p2p_num_unused_channels(wpa_s) > 0) {
3662                 if (*go == 0) {
3663                         /* We are the client */
3664                         wpa_printf(MSG_DEBUG, "P2P: Peer was found to be "
3665                                    "running a GO but we are capable of MCC, "
3666                                    "figure out the best channel to use");
3667                         *force_freq = 0;
3668                 } else if (!freq_included(channels, *force_freq)) {
3669                         /* We are the GO, and *force_freq is not in the
3670                          * intersection */
3671                         wpa_printf(MSG_DEBUG, "P2P: Forced GO freq %d MHz not "
3672                                    "in intersection but we are capable of MCC, "
3673                                    "figure out the best channel to use",
3674                                    *force_freq);
3675                         *force_freq = 0;
3676                 }
3677         }
3678
3679         return P2P_SC_SUCCESS;
3680 }
3681
3682
3683 static void wpas_invitation_received(void *ctx, const u8 *sa, const u8 *bssid,
3684                                      const u8 *ssid, size_t ssid_len,
3685                                      const u8 *go_dev_addr, u8 status,
3686                                      int op_freq)
3687 {
3688         struct wpa_supplicant *wpa_s = ctx;
3689         struct wpa_ssid *s;
3690
3691         for (s = wpa_s->conf->ssid; s; s = s->next) {
3692                 if (s->disabled == 2 &&
3693                     s->ssid_len == ssid_len &&
3694                     os_memcmp(ssid, s->ssid, ssid_len) == 0)
3695                         break;
3696         }
3697
3698         if (status == P2P_SC_SUCCESS) {
3699                 wpa_printf(MSG_DEBUG, "P2P: Invitation from peer " MACSTR
3700                            " was accepted; op_freq=%d MHz, SSID=%s",
3701                            MAC2STR(sa), op_freq, wpa_ssid_txt(ssid, ssid_len));
3702                 if (s) {
3703                         int go = s->mode == WPAS_MODE_P2P_GO;
3704                         wpas_p2p_group_add_persistent(
3705                                 wpa_s, s, go, 0, op_freq, 0, 0, NULL,
3706                                 go ? P2P_MAX_INITIAL_CONN_WAIT_GO_REINVOKE : 0);
3707                 } else if (bssid) {
3708                         wpa_s->user_initiated_pd = 0;
3709                         wpas_p2p_join(wpa_s, bssid, go_dev_addr,
3710                                       wpa_s->p2p_wps_method, 0, op_freq,
3711                                       ssid, ssid_len);
3712                 }
3713                 return;
3714         }
3715
3716         if (status != P2P_SC_FAIL_INFO_CURRENTLY_UNAVAILABLE) {
3717                 wpa_printf(MSG_DEBUG, "P2P: Invitation from peer " MACSTR
3718                            " was rejected (status %u)", MAC2STR(sa), status);
3719                 return;
3720         }
3721
3722         if (!s) {
3723                 if (bssid) {
3724                         wpa_msg_global(wpa_s, MSG_INFO,
3725                                        P2P_EVENT_INVITATION_RECEIVED
3726                                        "sa=" MACSTR " go_dev_addr=" MACSTR
3727                                        " bssid=" MACSTR " unknown-network",
3728                                        MAC2STR(sa), MAC2STR(go_dev_addr),
3729                                        MAC2STR(bssid));
3730                 } else {
3731                         wpa_msg_global(wpa_s, MSG_INFO,
3732                                        P2P_EVENT_INVITATION_RECEIVED
3733                                        "sa=" MACSTR " go_dev_addr=" MACSTR
3734                                        " unknown-network",
3735                                        MAC2STR(sa), MAC2STR(go_dev_addr));
3736                 }
3737                 return;
3738         }
3739
3740         if (s->mode == WPAS_MODE_P2P_GO && op_freq) {
3741                 wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_INVITATION_RECEIVED
3742                                "sa=" MACSTR " persistent=%d freq=%d",
3743                                MAC2STR(sa), s->id, op_freq);
3744         } else {
3745                 wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_INVITATION_RECEIVED
3746                                "sa=" MACSTR " persistent=%d",
3747                                MAC2STR(sa), s->id);
3748         }
3749 }
3750
3751
3752 static void wpas_remove_persistent_peer(struct wpa_supplicant *wpa_s,
3753                                         struct wpa_ssid *ssid,
3754                                         const u8 *peer, int inv)
3755 {
3756         size_t i;
3757
3758         if (ssid == NULL)
3759                 return;
3760
3761         for (i = 0; ssid->p2p_client_list && i < ssid->num_p2p_clients; i++) {
3762                 if (os_memcmp(ssid->p2p_client_list + i * 2 * ETH_ALEN, peer,
3763                               ETH_ALEN) == 0)
3764                         break;
3765         }
3766         if (i >= ssid->num_p2p_clients || !ssid->p2p_client_list) {
3767                 if (ssid->mode != WPAS_MODE_P2P_GO &&
3768                     os_memcmp(ssid->bssid, peer, ETH_ALEN) == 0) {
3769                         wpa_printf(MSG_DEBUG, "P2P: Remove persistent group %d "
3770                                    "due to invitation result", ssid->id);
3771                         wpas_notify_network_removed(wpa_s, ssid);
3772                         wpa_config_remove_network(wpa_s->conf, ssid->id);
3773                         return;
3774                 }
3775                 return; /* Peer not found in client list */
3776         }
3777
3778         wpa_printf(MSG_DEBUG, "P2P: Remove peer " MACSTR " from persistent "
3779                    "group %d client list%s",
3780                    MAC2STR(peer), ssid->id,
3781                    inv ? " due to invitation result" : "");
3782         os_memmove(ssid->p2p_client_list + i * 2 * ETH_ALEN,
3783                    ssid->p2p_client_list + (i + 1) * 2 * ETH_ALEN,
3784                    (ssid->num_p2p_clients - i - 1) * 2 * ETH_ALEN);
3785         ssid->num_p2p_clients--;
3786         if (wpa_s->parent->conf->update_config &&
3787             wpa_config_write(wpa_s->parent->confname, wpa_s->parent->conf))
3788                 wpa_printf(MSG_DEBUG, "P2P: Failed to update configuration");
3789 }
3790
3791
3792 static void wpas_remove_persistent_client(struct wpa_supplicant *wpa_s,
3793                                           const u8 *peer)
3794 {
3795         struct wpa_ssid *ssid;
3796
3797         wpa_s = wpa_s->global->p2p_invite_group;
3798         if (wpa_s == NULL)
3799                 return; /* No known invitation group */
3800         ssid = wpa_s->current_ssid;
3801         if (ssid == NULL || ssid->mode != WPAS_MODE_P2P_GO ||
3802             !ssid->p2p_persistent_group)
3803                 return; /* Not operating as a GO in persistent group */
3804         ssid = wpas_p2p_get_persistent(wpa_s->parent, peer,
3805                                        ssid->ssid, ssid->ssid_len);
3806         wpas_remove_persistent_peer(wpa_s, ssid, peer, 1);
3807 }
3808
3809
3810 static void wpas_invitation_result(void *ctx, int status, const u8 *bssid,
3811                                    const struct p2p_channels *channels,
3812                                    const u8 *peer, int neg_freq,
3813                                    int peer_oper_freq)
3814 {
3815         struct wpa_supplicant *wpa_s = ctx;
3816         struct wpa_ssid *ssid;
3817         int freq;
3818
3819         if (bssid) {
3820                 wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_INVITATION_RESULT
3821                                "status=%d " MACSTR,
3822                                status, MAC2STR(bssid));
3823         } else {
3824                 wpa_msg_global(wpa_s, MSG_INFO, P2P_EVENT_INVITATION_RESULT
3825                                "status=%d ", status);
3826         }
3827         wpas_notify_p2p_invitation_result(wpa_s, status, bssid);
3828
3829         wpa_printf(MSG_DEBUG, "P2P: Invitation result - status=%d peer=" MACSTR,
3830                    status, MAC2STR(peer));
3831         if (wpa_s->pending_invite_ssid_id == -1) {
3832                 if (status == P2P_SC_FAIL_UNKNOWN_GROUP)
3833                         wpas_remove_persistent_client(wpa_s, peer);
3834                 return; /* Invitation to active group */
3835         }
3836
3837         if (status == P2P_SC_FAIL_INFO_CURRENTLY_UNAVAILABLE) {
3838                 wpa_printf(MSG_DEBUG, "P2P: Waiting for peer to start another "
3839                            "invitation exchange to indicate readiness for "
3840                            "re-invocation");
3841         }
3842
3843         if (status != P2P_SC_SUCCESS) {
3844                 if (status == P2P_SC_FAIL_UNKNOWN_GROUP) {
3845                         ssid = wpa_config_get_network(
3846                                 wpa_s->conf, wpa_s->pending_invite_ssid_id);
3847                         wpas_remove_persistent_peer(wpa_s, ssid, peer, 1);
3848                 }
3849                 wpas_p2p_remove_pending_group_interface(wpa_s);
3850                 return;
3851         }
3852
3853         ssid = wpa_config_get_network(wpa_s->conf,
3854                                       wpa_s->pending_invite_ssid_id);
3855         if (ssid == NULL) {
3856                 wpa_printf(MSG_ERROR, "P2P: Could not find persistent group "
3857                            "data matching with invitation");
3858                 return;
3859         }
3860
3861         /*
3862          * The peer could have missed our ctrl::ack frame for Invitation
3863          * Response and continue retransmitting the frame. To reduce the
3864          * likelihood of the peer not getting successful TX status for the
3865          * Invitation Response frame, wait a short time here before starting
3866          * the persistent group so that we will remain on the current channel to
3867          * acknowledge any possible retransmission from the peer.
3868          */
3869         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: 50 ms wait on current channel before "
3870                 "starting persistent group");
3871         os_sleep(0, 50000);
3872
3873         if (neg_freq > 0 && ssid->mode == WPAS_MODE_P2P_GO &&
3874             freq_included(channels, neg_freq))
3875                 freq = neg_freq;
3876         else if (peer_oper_freq > 0 && ssid->mode != WPAS_MODE_P2P_GO &&
3877                  freq_included(channels, peer_oper_freq))
3878                 freq = peer_oper_freq;
3879         else
3880                 freq = 0;
3881
3882         wpa_printf(MSG_DEBUG, "P2P: Persistent group invitation success - op_freq=%d MHz SSID=%s",
3883                    freq, wpa_ssid_txt(ssid->ssid, ssid->ssid_len));
3884         wpas_p2p_group_add_persistent(wpa_s, ssid,
3885                                       ssid->mode == WPAS_MODE_P2P_GO,
3886                                       wpa_s->p2p_persistent_go_freq,
3887                                       freq,
3888                                       wpa_s->p2p_go_ht40, wpa_s->p2p_go_vht,
3889                                       channels,
3890                                       ssid->mode == WPAS_MODE_P2P_GO ?
3891                                       P2P_MAX_INITIAL_CONN_WAIT_GO_REINVOKE :
3892                                       0);
3893 }
3894
3895
3896 static int wpas_p2p_disallowed_freq(struct wpa_global *global,
3897                                     unsigned int freq)
3898 {
3899         if (freq_range_list_includes(&global->p2p_go_avoid_freq, freq))
3900                 return 1;
3901         return freq_range_list_includes(&global->p2p_disallow_freq, freq);
3902 }
3903
3904
3905 static void wpas_p2p_add_chan(struct p2p_reg_class *reg, u8 chan)
3906 {
3907         reg->channel[reg->channels] = chan;
3908         reg->channels++;
3909 }
3910
3911
3912 static int wpas_p2p_default_channels(struct wpa_supplicant *wpa_s,
3913                                      struct p2p_channels *chan,
3914                                      struct p2p_channels *cli_chan)
3915 {
3916         int i, cla = 0;
3917
3918         wpa_s->global->p2p_24ghz_social_channels = 1;
3919
3920         os_memset(cli_chan, 0, sizeof(*cli_chan));
3921
3922         wpa_printf(MSG_DEBUG, "P2P: Enable operating classes for 2.4 GHz "
3923                    "band");
3924
3925         /* Operating class 81 - 2.4 GHz band channels 1..13 */
3926         chan->reg_class[cla].reg_class = 81;
3927         chan->reg_class[cla].channels = 0;
3928         for (i = 0; i < 11; i++) {
3929                 if (!wpas_p2p_disallowed_freq(wpa_s->global, 2412 + i * 5))
3930                         wpas_p2p_add_chan(&chan->reg_class[cla], i + 1);
3931         }
3932         if (chan->reg_class[cla].channels)
3933                 cla++;
3934
3935         wpa_printf(MSG_DEBUG, "P2P: Enable operating classes for lower 5 GHz "
3936                    "band");
3937
3938         /* Operating class 115 - 5 GHz, channels 36-48 */
3939         chan->reg_class[cla].reg_class = 115;
3940         chan->reg_class[cla].channels = 0;
3941         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 36 * 5))
3942                 wpas_p2p_add_chan(&chan->reg_class[cla], 36);
3943         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 40 * 5))
3944                 wpas_p2p_add_chan(&chan->reg_class[cla], 40);
3945         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 44 * 5))
3946                 wpas_p2p_add_chan(&chan->reg_class[cla], 44);
3947         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 48 * 5))
3948                 wpas_p2p_add_chan(&chan->reg_class[cla], 48);
3949         if (chan->reg_class[cla].channels)
3950                 cla++;
3951
3952         wpa_printf(MSG_DEBUG, "P2P: Enable operating classes for higher 5 GHz "
3953                    "band");
3954
3955         /* Operating class 124 - 5 GHz, channels 149,153,157,161 */
3956         chan->reg_class[cla].reg_class = 124;
3957         chan->reg_class[cla].channels = 0;
3958         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 149 * 5))
3959                 wpas_p2p_add_chan(&chan->reg_class[cla], 149);
3960         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 153 * 5))
3961                 wpas_p2p_add_chan(&chan->reg_class[cla], 153);
3962         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 156 * 5))
3963                 wpas_p2p_add_chan(&chan->reg_class[cla], 157);
3964         if (!wpas_p2p_disallowed_freq(wpa_s->global, 5000 + 161 * 5))
3965                 wpas_p2p_add_chan(&chan->reg_class[cla], 161);
3966         if (chan->reg_class[cla].channels)
3967                 cla++;
3968
3969         chan->reg_classes = cla;
3970         return 0;
3971 }
3972
3973
3974 static struct hostapd_hw_modes * get_mode(struct hostapd_hw_modes *modes,
3975                                           u16 num_modes,
3976                                           enum hostapd_hw_mode mode)
3977 {
3978         u16 i;
3979
3980         for (i = 0; i < num_modes; i++) {
3981                 if (modes[i].mode == mode)
3982                         return &modes[i];
3983         }
3984
3985         return NULL;
3986 }
3987
3988
3989 enum chan_allowed {
3990         NOT_ALLOWED, NO_IR, ALLOWED
3991 };
3992
3993 static int has_channel(struct wpa_global *global,
3994                        struct hostapd_hw_modes *mode, u8 chan, int *flags)
3995 {
3996         int i;
3997         unsigned int freq;
3998
3999         freq = (mode->mode == HOSTAPD_MODE_IEEE80211A ? 5000 : 2407) +
4000                 chan * 5;
4001         if (wpas_p2p_disallowed_freq(global, freq))
4002                 return NOT_ALLOWED;
4003
4004         for (i = 0; i < mode->num_channels; i++) {
4005                 if (mode->channels[i].chan == chan) {
4006                         if (flags)
4007                                 *flags = mode->channels[i].flag;
4008                         if (mode->channels[i].flag &
4009                             (HOSTAPD_CHAN_DISABLED |
4010                              HOSTAPD_CHAN_RADAR))
4011                                 return NOT_ALLOWED;
4012                         if (mode->channels[i].flag & HOSTAPD_CHAN_NO_IR)
4013                                 return NO_IR;
4014                         return ALLOWED;
4015                 }
4016         }
4017
4018         return NOT_ALLOWED;
4019 }
4020
4021
4022 struct p2p_oper_class_map {
4023         enum hostapd_hw_mode mode;
4024         u8 op_class;
4025         u8 min_chan;
4026         u8 max_chan;
4027         u8 inc;
4028         enum { BW20, BW40PLUS, BW40MINUS, BW80, BW2160 } bw;
4029 };
4030
4031 static struct p2p_oper_class_map op_class[] = {
4032         { HOSTAPD_MODE_IEEE80211G, 81, 1, 13, 1, BW20 },
4033 #if 0 /* Do not enable HT40 on 2 GHz for now */
4034         { HOSTAPD_MODE_IEEE80211G, 83, 1, 9, 1, BW40PLUS },
4035         { HOSTAPD_MODE_IEEE80211G, 84, 5, 13, 1, BW40MINUS },
4036 #endif
4037         { HOSTAPD_MODE_IEEE80211A, 115, 36, 48, 4, BW20 },
4038         { HOSTAPD_MODE_IEEE80211A, 124, 149, 161, 4, BW20 },
4039         { HOSTAPD_MODE_IEEE80211A, 116, 36, 44, 8, BW40PLUS },
4040         { HOSTAPD_MODE_IEEE80211A, 117, 40, 48, 8, BW40MINUS },
4041         { HOSTAPD_MODE_IEEE80211A, 126, 149, 157, 8, BW40PLUS },
4042         { HOSTAPD_MODE_IEEE80211A, 127, 153, 161, 8, BW40MINUS },
4043
4044         /*
4045          * IEEE P802.11ac/D7.0 Table E-4 actually talks about channel center
4046          * frequency index 42, 58, 106, 122, 138, 155 with channel spacing of
4047          * 80 MHz, but currently use the following definition for simplicity
4048          * (these center frequencies are not actual channels, which makes
4049          * has_channel() fail). wpas_p2p_verify_80mhz() should take care of
4050          * removing invalid channels.
4051          */
4052         { HOSTAPD_MODE_IEEE80211A, 128, 36, 161, 4, BW80 },
4053         { HOSTAPD_MODE_IEEE80211AD, 180, 1, 4, 1, BW2160 },
4054         { -1, 0, 0, 0, 0, BW20 }
4055 };
4056
4057
4058 static int wpas_p2p_get_center_80mhz(struct wpa_supplicant *wpa_s,
4059                                      struct hostapd_hw_modes *mode,
4060                                      u8 channel)
4061 {
4062         u8 center_channels[] = { 42, 58, 106, 122, 138, 155 };
4063         unsigned int i;
4064
4065         if (mode->mode != HOSTAPD_MODE_IEEE80211A)
4066                 return 0;
4067
4068         for (i = 0; i < ARRAY_SIZE(center_channels); i++)
4069                 /*
4070                  * In 80 MHz, the bandwidth "spans" 12 channels (e.g., 36-48),
4071                  * so the center channel is 6 channels away from the start/end.
4072                  */
4073                 if (channel >= center_channels[i] - 6 &&
4074                     channel <= center_channels[i] + 6)
4075                         return center_channels[i];
4076
4077         return 0;
4078 }
4079
4080
4081 static enum chan_allowed wpas_p2p_verify_80mhz(struct wpa_supplicant *wpa_s,
4082                                                struct hostapd_hw_modes *mode,
4083                                                u8 channel, u8 bw)
4084 {
4085         u8 center_chan;
4086         int i, flags;
4087         enum chan_allowed res, ret = ALLOWED;
4088
4089         center_chan = wpas_p2p_get_center_80mhz(wpa_s, mode, channel);
4090         if (!center_chan)
4091                 return NOT_ALLOWED;
4092         if (center_chan >= 58 && center_chan <= 138)
4093                 return NOT_ALLOWED; /* Do not allow DFS channels for P2P */
4094
4095         /* check all the channels are available */
4096         for (i = 0; i < 4; i++) {
4097                 int adj_chan = center_chan - 6 + i * 4;
4098
4099                 res = has_channel(wpa_s->global, mode, adj_chan, &flags);
4100                 if (res == NOT_ALLOWED)
4101                         return NOT_ALLOWED;
4102                 if (res == NO_IR)
4103                         ret = NO_IR;
4104
4105                 if (i == 0 && !(flags & HOSTAPD_CHAN_VHT_10_70))
4106                         return NOT_ALLOWED;
4107                 if (i == 1 && !(flags & HOSTAPD_CHAN_VHT_30_50))
4108                         return NOT_ALLOWED;
4109                 if (i == 2 && !(flags & HOSTAPD_CHAN_VHT_50_30))
4110                         return NOT_ALLOWED;
4111                 if (i == 3 && !(flags & HOSTAPD_CHAN_VHT_70_10))
4112                         return NOT_ALLOWED;
4113         }
4114
4115         return ret;
4116 }
4117
4118
4119 static enum chan_allowed wpas_p2p_verify_channel(struct wpa_supplicant *wpa_s,
4120                                                  struct hostapd_hw_modes *mode,
4121                                                  u8 channel, u8 bw)
4122 {
4123         int flag = 0;
4124         enum chan_allowed res, res2;
4125
4126         res2 = res = has_channel(wpa_s->global, mode, channel, &flag);
4127         if (bw == BW40MINUS) {
4128                 if (!(flag & HOSTAPD_CHAN_HT40MINUS))
4129                         return NOT_ALLOWED;
4130                 res2 = has_channel(wpa_s->global, mode, channel - 4, NULL);
4131         } else if (bw == BW40PLUS) {
4132                 if (!(flag & HOSTAPD_CHAN_HT40PLUS))
4133                         return NOT_ALLOWED;
4134                 res2 = has_channel(wpa_s->global, mode, channel + 4, NULL);
4135         } else if (bw == BW80) {
4136                 res2 = wpas_p2p_verify_80mhz(wpa_s, mode, channel, bw);
4137         }
4138
4139         if (res == NOT_ALLOWED || res2 == NOT_ALLOWED)
4140                 return NOT_ALLOWED;
4141         if (res == NO_IR || res2 == NO_IR)
4142                 return NO_IR;
4143         return res;
4144 }
4145
4146
4147 static int wpas_p2p_setup_channels(struct wpa_supplicant *wpa_s,
4148                                    struct p2p_channels *chan,
4149                                    struct p2p_channels *cli_chan)
4150 {
4151         struct hostapd_hw_modes *mode;
4152         int cla, op, cli_cla;
4153
4154         if (wpa_s->hw.modes == NULL) {
4155                 wpa_printf(MSG_DEBUG, "P2P: Driver did not support fetching "
4156                            "of all supported channels; assume dualband "
4157                            "support");
4158                 return wpas_p2p_default_channels(wpa_s, chan, cli_chan);
4159         }
4160
4161         cla = cli_cla = 0;
4162
4163         for (op = 0; op_class[op].op_class; op++) {
4164                 struct p2p_oper_class_map *o = &op_class[op];
4165                 u8 ch;
4166                 struct p2p_reg_class *reg = NULL, *cli_reg = NULL;
4167
4168                 mode = get_mode(wpa_s->hw.modes, wpa_s->hw.num_modes, o->mode);
4169                 if (mode == NULL)
4170                         continue;
4171                 if (mode->mode == HOSTAPD_MODE_IEEE80211G)
4172                         wpa_s->global->p2p_24ghz_social_channels = 1;
4173                 for (ch = o->min_chan; ch <= o->max_chan; ch += o->inc) {
4174                         enum chan_allowed res;
4175                         res = wpas_p2p_verify_channel(wpa_s, mode, ch, o->bw);
4176                         if (res == ALLOWED) {
4177                                 if (reg == NULL) {
4178                                         wpa_printf(MSG_DEBUG, "P2P: Add operating class %u",
4179                                                    o->op_class);
4180                                         reg = &chan->reg_class[cla];
4181                                         cla++;
4182                                         reg->reg_class = o->op_class;
4183                                 }
4184                                 reg->channel[reg->channels] = ch;
4185                                 reg->channels++;
4186                         } else if (res == NO_IR &&
4187                                    wpa_s->conf->p2p_add_cli_chan) {
4188                                 if (cli_reg == NULL) {
4189                                         wpa_printf(MSG_DEBUG, "P2P: Add operating class %u (client only)",
4190                                                    o->op_class);
4191                                         cli_reg = &cli_chan->reg_class[cli_cla];
4192                                         cli_cla++;
4193                                         cli_reg->reg_class = o->op_class;
4194                                 }
4195                                 cli_reg->channel[cli_reg->channels] = ch;
4196                                 cli_reg->channels++;
4197                         }
4198                 }
4199                 if (reg) {
4200                         wpa_hexdump(MSG_DEBUG, "P2P: Channels",
4201                                     reg->channel, reg->channels);
4202                 }
4203                 if (cli_reg) {
4204                         wpa_hexdump(MSG_DEBUG, "P2P: Channels (client only)",
4205                                     cli_reg->channel, cli_reg->channels);
4206                 }
4207         }
4208
4209         chan->reg_classes = cla;
4210         cli_chan->reg_classes = cli_cla;
4211
4212         return 0;
4213 }
4214
4215
4216 int wpas_p2p_get_ht40_mode(struct wpa_supplicant *wpa_s,
4217                            struct hostapd_hw_modes *mode, u8 channel)
4218 {
4219         int op;
4220         enum chan_allowed ret;
4221
4222         for (op = 0; op_class[op].op_class; op++) {
4223                 struct p2p_oper_class_map *o = &op_class[op];
4224                 u8 ch;
4225
4226                 for (ch = o->min_chan; ch <= o->max_chan; ch += o->inc) {
4227                         if (o->mode != HOSTAPD_MODE_IEEE80211A ||
4228                             o->bw == BW20 || ch != channel)
4229                                 continue;
4230                         ret = wpas_p2p_verify_channel(wpa_s, mode, ch, o->bw);
4231                         if (ret == ALLOWED)
4232                                 return (o->bw == BW40MINUS) ? -1 : 1;
4233                 }
4234         }
4235         return 0;
4236 }
4237
4238
4239 int wpas_p2p_get_vht80_center(struct wpa_supplicant *wpa_s,
4240                               struct hostapd_hw_modes *mode, u8 channel)
4241 {
4242         if (!wpas_p2p_verify_channel(wpa_s, mode, channel, BW80))
4243                 return 0;
4244
4245         return wpas_p2p_get_center_80mhz(wpa_s, mode, channel);
4246 }
4247
4248
4249 static int wpas_get_noa(void *ctx, const u8 *interface_addr, u8 *buf,
4250                         size_t buf_len)
4251 {
4252         struct wpa_supplicant *wpa_s = ctx;
4253
4254         for (wpa_s = wpa_s->global->ifaces; wpa_s; wpa_s = wpa_s->next) {
4255                 if (os_memcmp(wpa_s->own_addr, interface_addr, ETH_ALEN) == 0)
4256                         break;
4257         }
4258         if (wpa_s == NULL)
4259                 return -1;
4260
4261         return wpa_drv_get_noa(wpa_s, buf, buf_len);
4262 }
4263
4264
4265 struct wpa_supplicant * wpas_get_p2p_go_iface(struct wpa_supplicant *wpa_s,
4266                                               const u8 *ssid, size_t ssid_len)
4267 {
4268         for (wpa_s = wpa_s->global->ifaces; wpa_s; wpa_s = wpa_s->next) {
4269                 struct wpa_ssid *s = wpa_s->current_ssid;
4270                 if (s == NULL)
4271                         continue;
4272                 if (s->mode != WPAS_MODE_P2P_GO &&
4273                     s->mode != WPAS_MODE_AP &&
4274                     s->mode != WPAS_MODE_P2P_GROUP_FORMATION)
4275                         continue;
4276                 if (s->ssid_len != ssid_len ||
4277                     os_memcmp(ssid, s->ssid, ssid_len) != 0)
4278                         continue;
4279                 return wpa_s;
4280         }
4281
4282         return NULL;
4283
4284 }
4285
4286
4287 struct wpa_supplicant * wpas_get_p2p_client_iface(struct wpa_supplicant *wpa_s,
4288                                                   const u8 *peer_dev_addr)
4289 {
4290         for (wpa_s = wpa_s->global->ifaces; wpa_s; wpa_s = wpa_s->next) {
4291                 struct wpa_ssid *ssid = wpa_s->current_ssid;
4292                 if (ssid == NULL)
4293                         continue;
4294                 if (ssid->mode != WPAS_MODE_INFRA)
4295                         continue;
4296                 if (wpa_s->wpa_state != WPA_COMPLETED &&
4297                     wpa_s->wpa_state != WPA_GROUP_HANDSHAKE)
4298                         continue;
4299                 if (os_memcmp(wpa_s->go_dev_addr, peer_dev_addr, ETH_ALEN) == 0)
4300                         return wpa_s;
4301         }
4302
4303         return NULL;
4304 }
4305
4306
4307 static int wpas_go_connected(void *ctx, const u8 *dev_addr)
4308 {
4309         struct wpa_supplicant *wpa_s = ctx;
4310
4311         return wpas_get_p2p_client_iface(wpa_s, dev_addr) != NULL;
4312 }
4313
4314
4315 static int wpas_is_concurrent_session_active(void *ctx)
4316 {
4317         struct wpa_supplicant *wpa_s = ctx;
4318         struct wpa_supplicant *ifs;
4319
4320         for (ifs = wpa_s->global->ifaces; ifs; ifs = ifs->next) {
4321                 if (ifs == wpa_s)
4322                         continue;
4323                 if (ifs->wpa_state > WPA_ASSOCIATED)
4324                         return 1;
4325         }
4326         return 0;
4327 }
4328
4329
4330 static void wpas_p2p_debug_print(void *ctx, int level, const char *msg)
4331 {
4332         struct wpa_supplicant *wpa_s = ctx;
4333         wpa_msg_global(wpa_s, level, "P2P: %s", msg);
4334 }
4335
4336
4337 int wpas_p2p_add_p2pdev_interface(struct wpa_supplicant *wpa_s,
4338                                   const char *conf_p2p_dev)
4339 {
4340         struct wpa_interface iface;
4341         struct wpa_supplicant *p2pdev_wpa_s;
4342         char ifname[100];
4343         char force_name[100];
4344         int ret;
4345
4346         ret = os_snprintf(ifname, sizeof(ifname), P2P_MGMT_DEVICE_PREFIX "%s",
4347                           wpa_s->ifname);
4348         if (os_snprintf_error(sizeof(ifname), ret))
4349                 return -1;
4350         force_name[0] = '\0';
4351         wpa_s->pending_interface_type = WPA_IF_P2P_DEVICE;
4352         ret = wpa_drv_if_add(wpa_s, WPA_IF_P2P_DEVICE, ifname, NULL, NULL,
4353                              force_name, wpa_s->pending_interface_addr, NULL);
4354         if (ret < 0) {
4355                 wpa_printf(MSG_DEBUG, "P2P: Failed to create P2P Device interface");
4356                 return ret;
4357         }
4358         os_strlcpy(wpa_s->pending_interface_name, ifname,
4359                    sizeof(wpa_s->pending_interface_name));
4360
4361         os_memset(&iface, 0, sizeof(iface));
4362         iface.p2p_mgmt = 1;
4363         iface.ifname = wpa_s->pending_interface_name;
4364         iface.driver = wpa_s->driver->name;
4365         iface.driver_param = wpa_s->conf->driver_param;
4366
4367         /*
4368          * If a P2P Device configuration file was given, use it as the interface
4369          * configuration file (instead of using parent's configuration file.
4370          */
4371         if (conf_p2p_dev) {
4372                 iface.confname = conf_p2p_dev;
4373                 iface.ctrl_interface = NULL;
4374         } else {
4375                 iface.confname = wpa_s->confname;
4376                 iface.ctrl_interface = wpa_s->conf->ctrl_interface;
4377         }
4378         iface.conf_p2p_dev = NULL;
4379
4380         p2pdev_wpa_s = wpa_supplicant_add_iface(wpa_s->global, &iface);
4381         if (!p2pdev_wpa_s) {
4382                 wpa_printf(MSG_DEBUG, "P2P: Failed to add P2P Device interface");
4383                 return -1;
4384         }
4385         p2pdev_wpa_s->parent = wpa_s;
4386         wpa_s->p2p_dev = p2pdev_wpa_s;
4387
4388         wpa_s->pending_interface_name[0] = '\0';
4389         return 0;
4390 }
4391
4392
4393 static void wpas_presence_resp(void *ctx, const u8 *src, u8 status,
4394                                const u8 *noa, size_t noa_len)
4395 {
4396         struct wpa_supplicant *wpa_s, *intf = ctx;
4397         char hex[100];
4398
4399         for (wpa_s = intf->global->ifaces; wpa_s; wpa_s = wpa_s->next) {
4400                 if (wpa_s->waiting_presence_resp)
4401                         break;
4402         }
4403         if (!wpa_s) {
4404                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: No group interface was waiting for presence response");
4405                 return;
4406         }
4407         wpa_s->waiting_presence_resp = 0;
4408
4409         wpa_snprintf_hex(hex, sizeof(hex), noa, noa_len);
4410         wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_PRESENCE_RESPONSE "src=" MACSTR
4411                 " status=%u noa=%s", MAC2STR(src), status, hex);
4412 }
4413
4414
4415 static int wpas_get_persistent_group(void *ctx, const u8 *addr, const u8 *ssid,
4416                                      size_t ssid_len, u8 *go_dev_addr,
4417                                      u8 *ret_ssid, size_t *ret_ssid_len)
4418 {
4419         struct wpa_supplicant *wpa_s = ctx;
4420         struct wpa_ssid *s;
4421
4422         s = wpas_p2p_get_persistent(wpa_s, addr, ssid, ssid_len);
4423         if (s) {
4424                 os_memcpy(ret_ssid, s->ssid, s->ssid_len);
4425                 *ret_ssid_len = s->ssid_len;
4426                 os_memcpy(go_dev_addr, s->bssid, ETH_ALEN);
4427                 return 1;
4428         }
4429
4430         return 0;
4431 }
4432
4433
4434 static int wpas_get_go_info(void *ctx, u8 *intended_addr,
4435                             u8 *ssid, size_t *ssid_len, int *group_iface)
4436 {
4437         struct wpa_supplicant *wpa_s = ctx;
4438         struct wpa_ssid *s;
4439         u8 bssid[ETH_ALEN];
4440
4441         s = wpas_p2p_group_go_ssid(wpa_s, bssid);
4442         if (!s) {
4443                 s = wpas_p2p_get_persistent_go(wpa_s);
4444                 if (s)
4445                         os_memcpy(bssid, s->bssid, ETH_ALEN);
4446         }
4447
4448         *group_iface = wpas_p2p_create_iface(wpa_s);
4449         if (!s)
4450                 return 0;
4451
4452         os_memcpy(intended_addr, bssid, ETH_ALEN);
4453         os_memcpy(ssid, s->ssid, s->ssid_len);
4454         *ssid_len = s->ssid_len;
4455
4456         return 1;
4457 }
4458
4459
4460 static int _wpas_p2p_in_progress(void *ctx)
4461 {
4462         struct wpa_supplicant *wpa_s = ctx;
4463         return wpas_p2p_in_progress(wpa_s);
4464 }
4465
4466
4467 /**
4468  * wpas_p2p_init - Initialize P2P module for %wpa_supplicant
4469  * @global: Pointer to global data from wpa_supplicant_init()
4470  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
4471  * Returns: 0 on success, -1 on failure
4472  */
4473 int wpas_p2p_init(struct wpa_global *global, struct wpa_supplicant *wpa_s)
4474 {
4475         struct p2p_config p2p;
4476         int i;
4477
4478         if (wpa_s->conf->p2p_disabled)
4479                 return 0;
4480
4481         if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_CAPABLE))
4482                 return 0;
4483
4484         if (global->p2p)
4485                 return 0;
4486
4487         os_memset(&p2p, 0, sizeof(p2p));
4488         p2p.cb_ctx = wpa_s;
4489         p2p.debug_print = wpas_p2p_debug_print;
4490         p2p.p2p_scan = wpas_p2p_scan;
4491         p2p.send_action = wpas_send_action;
4492         p2p.send_action_done = wpas_send_action_done;
4493         p2p.go_neg_completed = wpas_go_neg_completed;
4494         p2p.go_neg_req_rx = wpas_go_neg_req_rx;
4495         p2p.dev_found = wpas_dev_found;
4496         p2p.dev_lost = wpas_dev_lost;
4497         p2p.find_stopped = wpas_find_stopped;
4498         p2p.start_listen = wpas_start_listen;
4499         p2p.stop_listen = wpas_stop_listen;
4500         p2p.send_probe_resp = wpas_send_probe_resp;
4501         p2p.sd_request = wpas_sd_request;
4502         p2p.sd_response = wpas_sd_response;
4503         p2p.prov_disc_req = wpas_prov_disc_req;
4504         p2p.prov_disc_resp = wpas_prov_disc_resp;
4505         p2p.prov_disc_fail = wpas_prov_disc_fail;
4506         p2p.invitation_process = wpas_invitation_process;
4507         p2p.invitation_received = wpas_invitation_received;
4508         p2p.invitation_result = wpas_invitation_result;
4509         p2p.get_noa = wpas_get_noa;
4510         p2p.go_connected = wpas_go_connected;
4511         p2p.presence_resp = wpas_presence_resp;
4512         p2p.is_concurrent_session_active = wpas_is_concurrent_session_active;
4513         p2p.is_p2p_in_progress = _wpas_p2p_in_progress;
4514         p2p.get_persistent_group = wpas_get_persistent_group;
4515         p2p.get_go_info = wpas_get_go_info;
4516
4517         os_memcpy(wpa_s->global->p2p_dev_addr, wpa_s->own_addr, ETH_ALEN);
4518         os_memcpy(p2p.dev_addr, wpa_s->global->p2p_dev_addr, ETH_ALEN);
4519         p2p.dev_name = wpa_s->conf->device_name;
4520         p2p.manufacturer = wpa_s->conf->manufacturer;
4521         p2p.model_name = wpa_s->conf->model_name;
4522         p2p.model_number = wpa_s->conf->model_number;
4523         p2p.serial_number = wpa_s->conf->serial_number;
4524         if (wpa_s->wps) {
4525                 os_memcpy(p2p.uuid, wpa_s->wps->uuid, 16);
4526                 p2p.config_methods = wpa_s->wps->config_methods;
4527         }
4528
4529         if (wpas_p2p_setup_channels(wpa_s, &p2p.channels, &p2p.cli_channels)) {
4530                 wpa_printf(MSG_ERROR,
4531                            "P2P: Failed to configure supported channel list");
4532                 return -1;
4533         }
4534
4535         if (wpa_s->conf->p2p_listen_reg_class &&
4536             wpa_s->conf->p2p_listen_channel) {
4537                 p2p.reg_class = wpa_s->conf->p2p_listen_reg_class;
4538                 p2p.channel = wpa_s->conf->p2p_listen_channel;
4539                 p2p.channel_forced = 1;
4540         } else {
4541                 /*
4542                  * Pick one of the social channels randomly as the listen
4543                  * channel.
4544                  */
4545                 if (p2p_config_get_random_social(&p2p, &p2p.reg_class,
4546                                                  &p2p.channel) != 0) {
4547                         wpa_printf(MSG_ERROR,
4548                                    "P2P: Failed to select random social channel as listen channel");
4549                         return -1;
4550                 }
4551                 p2p.channel_forced = 0;
4552         }
4553         wpa_printf(MSG_DEBUG, "P2P: Own listen channel: %d:%d",
4554                    p2p.reg_class, p2p.channel);
4555
4556         if (wpa_s->conf->p2p_oper_reg_class &&
4557             wpa_s->conf->p2p_oper_channel) {
4558                 p2p.op_reg_class = wpa_s->conf->p2p_oper_reg_class;
4559                 p2p.op_channel = wpa_s->conf->p2p_oper_channel;
4560                 p2p.cfg_op_channel = 1;
4561                 wpa_printf(MSG_DEBUG, "P2P: Configured operating channel: "
4562                            "%d:%d", p2p.op_reg_class, p2p.op_channel);
4563
4564         } else {
4565                 /*
4566                  * Use random operation channel from 2.4 GHz band social
4567                  * channels (1, 6, 11) or band 60 GHz social channel (2) if no
4568                  * other preference is indicated.
4569                  */
4570                 if (p2p_config_get_random_social(&p2p, &p2p.op_reg_class,
4571                                                  &p2p.op_channel) != 0) {
4572                         wpa_printf(MSG_ERROR,
4573                                    "P2P: Failed to select random social channel as operation channel");
4574                         return -1;
4575                 }
4576                 p2p.cfg_op_channel = 0;
4577                 wpa_printf(MSG_DEBUG, "P2P: Random operating channel: "
4578                            "%d:%d", p2p.op_reg_class, p2p.op_channel);
4579         }
4580
4581         if (wpa_s->conf->p2p_pref_chan && wpa_s->conf->num_p2p_pref_chan) {
4582                 p2p.pref_chan = wpa_s->conf->p2p_pref_chan;
4583                 p2p.num_pref_chan = wpa_s->conf->num_p2p_pref_chan;
4584         }
4585
4586         if (wpa_s->conf->country[0] && wpa_s->conf->country[1]) {
4587                 os_memcpy(p2p.country, wpa_s->conf->country, 2);
4588                 p2p.country[2] = 0x04;
4589         } else
4590                 os_memcpy(p2p.country, "XX\x04", 3);
4591
4592         os_memcpy(p2p.pri_dev_type, wpa_s->conf->device_type,
4593                   WPS_DEV_TYPE_LEN);
4594
4595         p2p.num_sec_dev_types = wpa_s->conf->num_sec_device_types;
4596         os_memcpy(p2p.sec_dev_type, wpa_s->conf->sec_device_type,
4597                   p2p.num_sec_dev_types * WPS_DEV_TYPE_LEN);
4598
4599         p2p.concurrent_operations = !!(wpa_s->drv_flags &
4600                                        WPA_DRIVER_FLAGS_P2P_CONCURRENT);
4601
4602         p2p.max_peers = 100;
4603
4604         if (wpa_s->conf->p2p_ssid_postfix) {
4605                 p2p.ssid_postfix_len =
4606                         os_strlen(wpa_s->conf->p2p_ssid_postfix);
4607                 if (p2p.ssid_postfix_len > sizeof(p2p.ssid_postfix))
4608                         p2p.ssid_postfix_len = sizeof(p2p.ssid_postfix);
4609                 os_memcpy(p2p.ssid_postfix, wpa_s->conf->p2p_ssid_postfix,
4610                           p2p.ssid_postfix_len);
4611         }
4612
4613         p2p.p2p_intra_bss = wpa_s->conf->p2p_intra_bss;
4614
4615         p2p.max_listen = wpa_s->max_remain_on_chan;
4616
4617         if (wpa_s->conf->p2p_passphrase_len >= 8 &&
4618             wpa_s->conf->p2p_passphrase_len <= 63)
4619                 p2p.passphrase_len = wpa_s->conf->p2p_passphrase_len;
4620         else
4621                 p2p.passphrase_len = 8;
4622
4623         global->p2p = p2p_init(&p2p);
4624         if (global->p2p == NULL)
4625                 return -1;
4626         global->p2p_init_wpa_s = wpa_s;
4627
4628         for (i = 0; i < MAX_WPS_VENDOR_EXT; i++) {
4629                 if (wpa_s->conf->wps_vendor_ext[i] == NULL)
4630                         continue;
4631                 p2p_add_wps_vendor_extension(
4632                         global->p2p, wpa_s->conf->wps_vendor_ext[i]);
4633         }
4634
4635         p2p_set_no_go_freq(global->p2p, &wpa_s->conf->p2p_no_go_freq);
4636
4637         return 0;
4638 }
4639
4640
4641 /**
4642  * wpas_p2p_deinit - Deinitialize per-interface P2P data
4643  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
4644  *
4645  * This function deinitialize per-interface P2P data.
4646  */
4647 void wpas_p2p_deinit(struct wpa_supplicant *wpa_s)
4648 {
4649         if (wpa_s->driver && wpa_s->drv_priv)
4650                 wpa_drv_probe_req_report(wpa_s, 0);
4651
4652         if (wpa_s->go_params) {
4653                 /* Clear any stored provisioning info */
4654                 p2p_clear_provisioning_info(
4655                         wpa_s->global->p2p,
4656                         wpa_s->go_params->peer_device_addr);
4657         }
4658
4659         os_free(wpa_s->go_params);
4660         wpa_s->go_params = NULL;
4661         eloop_cancel_timeout(wpas_p2p_psk_failure_removal, wpa_s, NULL);
4662         eloop_cancel_timeout(wpas_p2p_group_formation_timeout, wpa_s, NULL);
4663         eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
4664         wpa_s->p2p_long_listen = 0;
4665         eloop_cancel_timeout(wpas_p2p_long_listen_timeout, wpa_s, NULL);
4666         eloop_cancel_timeout(wpas_p2p_group_idle_timeout, wpa_s, NULL);
4667         wpas_p2p_remove_pending_group_interface(wpa_s);
4668         eloop_cancel_timeout(wpas_p2p_group_freq_conflict, wpa_s, NULL);
4669         wpas_p2p_listen_work_done(wpa_s);
4670         if (wpa_s->p2p_send_action_work) {
4671                 os_free(wpa_s->p2p_send_action_work->ctx);
4672                 radio_work_done(wpa_s->p2p_send_action_work);
4673                 wpa_s->p2p_send_action_work = NULL;
4674         }
4675         eloop_cancel_timeout(wpas_p2p_send_action_work_timeout, wpa_s, NULL);
4676
4677         wpabuf_free(wpa_s->p2p_oob_dev_pw);
4678         wpa_s->p2p_oob_dev_pw = NULL;
4679
4680         os_free(wpa_s->p2p_group_common_freqs);
4681         wpa_s->p2p_group_common_freqs = NULL;
4682         wpa_s->p2p_group_common_freqs_num = 0;
4683
4684         /* TODO: remove group interface from the driver if this wpa_s instance
4685          * is on top of a P2P group interface */
4686 }
4687
4688
4689 /**
4690  * wpas_p2p_deinit_global - Deinitialize global P2P module
4691  * @global: Pointer to global data from wpa_supplicant_init()
4692  *
4693  * This function deinitializes the global (per device) P2P module.
4694  */
4695 static void wpas_p2p_deinit_global(struct wpa_global *global)
4696 {
4697         struct wpa_supplicant *wpa_s, *tmp;
4698
4699         wpa_s = global->ifaces;
4700
4701         wpas_p2p_service_flush(global->p2p_init_wpa_s);
4702
4703         /* Remove remaining P2P group interfaces */
4704         while (wpa_s && wpa_s->p2p_group_interface != NOT_P2P_GROUP_INTERFACE)
4705                 wpa_s = wpa_s->next;
4706         while (wpa_s) {
4707                 tmp = global->ifaces;
4708                 while (tmp &&
4709                        (tmp == wpa_s ||
4710                         tmp->p2p_group_interface == NOT_P2P_GROUP_INTERFACE)) {
4711                         tmp = tmp->next;
4712                 }
4713                 if (tmp == NULL)
4714                         break;
4715                 /* Disconnect from the P2P group and deinit the interface */
4716                 wpas_p2p_disconnect(tmp);
4717         }
4718
4719         /*
4720          * Deinit GO data on any possibly remaining interface (if main
4721          * interface is used as GO).
4722          */
4723         for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) {
4724                 if (wpa_s->ap_iface)
4725                         wpas_p2p_group_deinit(wpa_s);
4726         }
4727
4728         p2p_deinit(global->p2p);
4729         global->p2p = NULL;
4730         global->p2p_init_wpa_s = NULL;
4731 }
4732
4733
4734 static int wpas_p2p_create_iface(struct wpa_supplicant *wpa_s)
4735 {
4736         if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_DEDICATED_P2P_DEVICE) &&
4737             wpa_s->conf->p2p_no_group_iface)
4738                 return 0; /* separate interface disabled per configuration */
4739         if (wpa_s->drv_flags &
4740             (WPA_DRIVER_FLAGS_P2P_DEDICATED_INTERFACE |
4741              WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P))
4742                 return 1; /* P2P group requires a new interface in every case
4743                            */
4744         if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_CONCURRENT))
4745                 return 0; /* driver does not support concurrent operations */
4746         if (wpa_s->global->ifaces->next)
4747                 return 1; /* more that one interface already in use */
4748         if (wpa_s->wpa_state >= WPA_AUTHENTICATING)
4749                 return 1; /* this interface is already in use */
4750         return 0;
4751 }
4752
4753
4754 static int wpas_p2p_start_go_neg(struct wpa_supplicant *wpa_s,
4755                                  const u8 *peer_addr,
4756                                  enum p2p_wps_method wps_method,
4757                                  int go_intent, const u8 *own_interface_addr,
4758                                  unsigned int force_freq, int persistent_group,
4759                                  struct wpa_ssid *ssid, unsigned int pref_freq)
4760 {
4761         if (persistent_group && wpa_s->conf->persistent_reconnect)
4762                 persistent_group = 2;
4763
4764         /*
4765          * Increase GO config timeout if HT40 is used since it takes some time
4766          * to scan channels for coex purposes before the BSS can be started.
4767          */
4768         p2p_set_config_timeout(wpa_s->global->p2p,
4769                                wpa_s->p2p_go_ht40 ? 255 : 100, 20);
4770
4771         return p2p_connect(wpa_s->global->p2p, peer_addr, wps_method,
4772                            go_intent, own_interface_addr, force_freq,
4773                            persistent_group, ssid ? ssid->ssid : NULL,
4774                            ssid ? ssid->ssid_len : 0,
4775                            wpa_s->p2p_pd_before_go_neg, pref_freq,
4776                            wps_method == WPS_NFC ? wpa_s->p2p_oob_dev_pw_id :
4777                            0);
4778 }
4779
4780
4781 static int wpas_p2p_auth_go_neg(struct wpa_supplicant *wpa_s,
4782                                 const u8 *peer_addr,
4783                                 enum p2p_wps_method wps_method,
4784                                 int go_intent, const u8 *own_interface_addr,
4785                                 unsigned int force_freq, int persistent_group,
4786                                 struct wpa_ssid *ssid, unsigned int pref_freq)
4787 {
4788         if (persistent_group && wpa_s->conf->persistent_reconnect)
4789                 persistent_group = 2;
4790
4791         return p2p_authorize(wpa_s->global->p2p, peer_addr, wps_method,
4792                              go_intent, own_interface_addr, force_freq,
4793                              persistent_group, ssid ? ssid->ssid : NULL,
4794                              ssid ? ssid->ssid_len : 0, pref_freq,
4795                              wps_method == WPS_NFC ? wpa_s->p2p_oob_dev_pw_id :
4796                              0);
4797 }
4798
4799
4800 static void wpas_p2p_check_join_scan_limit(struct wpa_supplicant *wpa_s)
4801 {
4802         wpa_s->p2p_join_scan_count++;
4803         wpa_printf(MSG_DEBUG, "P2P: Join scan attempt %d",
4804                    wpa_s->p2p_join_scan_count);
4805         if (wpa_s->p2p_join_scan_count > P2P_MAX_JOIN_SCAN_ATTEMPTS) {
4806                 wpa_printf(MSG_DEBUG, "P2P: Failed to find GO " MACSTR
4807                            " for join operationg - stop join attempt",
4808                            MAC2STR(wpa_s->pending_join_iface_addr));
4809                 eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
4810                 if (wpa_s->p2p_auto_pd) {
4811                         wpa_s->p2p_auto_pd = 0;
4812                         wpa_msg_global(wpa_s, MSG_INFO,
4813                                        P2P_EVENT_PROV_DISC_FAILURE
4814                                        " p2p_dev_addr=" MACSTR " status=N/A",
4815                                        MAC2STR(wpa_s->pending_join_dev_addr));
4816                         return;
4817                 }
4818                 wpa_msg_global(wpa_s->parent, MSG_INFO,
4819                                P2P_EVENT_GROUP_FORMATION_FAILURE);
4820         }
4821 }
4822
4823
4824 static int wpas_check_freq_conflict(struct wpa_supplicant *wpa_s, int freq)
4825 {
4826         int res;
4827         unsigned int num, i;
4828         struct wpa_used_freq_data *freqs;
4829
4830         if (wpas_p2p_num_unused_channels(wpa_s) > 0) {
4831                 /* Multiple channels are supported and not all are in use */
4832                 return 0;
4833         }
4834
4835         freqs = os_calloc(wpa_s->num_multichan_concurrent,
4836                           sizeof(struct wpa_used_freq_data));
4837         if (!freqs)
4838                 return 1;
4839
4840         num = wpas_p2p_valid_oper_freqs(wpa_s, freqs,
4841                                         wpa_s->num_multichan_concurrent);
4842
4843         for (i = 0; i < num; i++) {
4844                 if (freqs[i].freq == freq) {
4845                         wpa_printf(MSG_DEBUG, "P2P: Frequency %d MHz in use by another virtual interface and can be used",
4846                                    freq);
4847                         res = 0;
4848                         goto exit_free;
4849                 }
4850         }
4851
4852         wpa_printf(MSG_DEBUG, "P2P: No valid operating frequencies");
4853         res = 1;
4854
4855 exit_free:
4856         os_free(freqs);
4857         return res;
4858 }
4859
4860
4861 static int wpas_p2p_peer_go(struct wpa_supplicant *wpa_s,
4862                             const u8 *peer_dev_addr)
4863 {
4864         struct wpa_bss *bss;
4865         int updated;
4866
4867         bss = wpa_bss_get_p2p_dev_addr(wpa_s, peer_dev_addr);
4868         if (bss == NULL)
4869                 return -1;
4870         if (bss->last_update_idx < wpa_s->bss_update_idx) {
4871                 wpa_printf(MSG_DEBUG, "P2P: Peer BSS entry not updated in the "
4872                            "last scan");
4873                 return 0;
4874         }
4875
4876         updated = os_reltime_before(&wpa_s->p2p_auto_started,
4877                                     &bss->last_update);
4878         wpa_printf(MSG_DEBUG, "P2P: Current BSS entry for peer updated at "
4879                    "%ld.%06ld (%supdated in last scan)",
4880                    bss->last_update.sec, bss->last_update.usec,
4881                    updated ? "": "not ");
4882
4883         return updated;
4884 }
4885
4886
4887 static void wpas_p2p_scan_res_join(struct wpa_supplicant *wpa_s,
4888                                    struct wpa_scan_results *scan_res)
4889 {
4890         struct wpa_bss *bss = NULL;
4891         int freq;
4892         u8 iface_addr[ETH_ALEN];
4893
4894         eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
4895
4896         if (wpa_s->global->p2p_disabled)
4897                 return;
4898
4899         wpa_printf(MSG_DEBUG, "P2P: Scan results received (%d BSS) for %sjoin",
4900                    scan_res ? (int) scan_res->num : -1,
4901                    wpa_s->p2p_auto_join ? "auto_" : "");
4902
4903         if (scan_res)
4904                 wpas_p2p_scan_res_handler(wpa_s, scan_res);
4905
4906         if (wpa_s->p2p_auto_pd) {
4907                 int join = wpas_p2p_peer_go(wpa_s,
4908                                             wpa_s->pending_join_dev_addr);
4909                 if (join == 0 &&
4910                     wpa_s->auto_pd_scan_retry < P2P_AUTO_PD_SCAN_ATTEMPTS) {
4911                         wpa_s->auto_pd_scan_retry++;
4912                         bss = wpa_bss_get_bssid_latest(
4913                                 wpa_s, wpa_s->pending_join_dev_addr);
4914                         if (bss) {
4915                                 freq = bss->freq;
4916                                 wpa_printf(MSG_DEBUG, "P2P: Scan retry %d for "
4917                                            "the peer " MACSTR " at %d MHz",
4918                                            wpa_s->auto_pd_scan_retry,
4919                                            MAC2STR(wpa_s->
4920                                                    pending_join_dev_addr),
4921                                            freq);
4922                                 wpas_p2p_join_scan_req(wpa_s, freq, NULL, 0);
4923                                 return;
4924                         }
4925                 }
4926
4927                 if (join < 0)
4928                         join = 0;
4929
4930                 wpa_s->p2p_auto_pd = 0;
4931                 wpa_s->pending_pd_use = join ? AUTO_PD_JOIN : AUTO_PD_GO_NEG;
4932                 wpa_printf(MSG_DEBUG, "P2P: Auto PD with " MACSTR " join=%d",
4933                            MAC2STR(wpa_s->pending_join_dev_addr), join);
4934                 if (p2p_prov_disc_req(wpa_s->global->p2p,
4935                                       wpa_s->pending_join_dev_addr, NULL,
4936                                       wpa_s->pending_pd_config_methods, join,
4937                                       0, wpa_s->user_initiated_pd) < 0) {
4938                         wpa_s->p2p_auto_pd = 0;
4939                         wpa_msg_global(wpa_s, MSG_INFO,
4940                                        P2P_EVENT_PROV_DISC_FAILURE
4941                                        " p2p_dev_addr=" MACSTR " status=N/A",
4942                                        MAC2STR(wpa_s->pending_join_dev_addr));
4943                 }
4944                 return;
4945         }
4946
4947         if (wpa_s->p2p_auto_join) {
4948                 int join = wpas_p2p_peer_go(wpa_s,
4949                                             wpa_s->pending_join_dev_addr);
4950                 if (join < 0) {
4951                         wpa_printf(MSG_DEBUG, "P2P: Peer was not found to be "
4952                                    "running a GO -> use GO Negotiation");
4953                         wpas_p2p_connect(wpa_s, wpa_s->pending_join_dev_addr,
4954                                          wpa_s->p2p_pin, wpa_s->p2p_wps_method,
4955                                          wpa_s->p2p_persistent_group, 0, 0, 0,
4956                                          wpa_s->p2p_go_intent,
4957                                          wpa_s->p2p_connect_freq,
4958                                          wpa_s->p2p_persistent_id,
4959                                          wpa_s->p2p_pd_before_go_neg,
4960                                          wpa_s->p2p_go_ht40,
4961                                          wpa_s->p2p_go_vht);
4962                         return;
4963                 }
4964
4965                 wpa_printf(MSG_DEBUG, "P2P: Peer was found running GO%s -> "
4966                            "try to join the group", join ? "" :
4967                            " in older scan");
4968                 if (!join)
4969                         wpa_s->p2p_fallback_to_go_neg = 1;
4970         }
4971
4972         freq = p2p_get_oper_freq(wpa_s->global->p2p,
4973                                  wpa_s->pending_join_iface_addr);
4974         if (freq < 0 &&
4975             p2p_get_interface_addr(wpa_s->global->p2p,
4976                                    wpa_s->pending_join_dev_addr,
4977                                    iface_addr) == 0 &&
4978             os_memcmp(iface_addr, wpa_s->pending_join_dev_addr, ETH_ALEN) != 0
4979             && !wpa_bss_get_bssid(wpa_s, wpa_s->pending_join_iface_addr)) {
4980                 wpa_printf(MSG_DEBUG, "P2P: Overwrite pending interface "
4981                            "address for join from " MACSTR " to " MACSTR
4982                            " based on newly discovered P2P peer entry",
4983                            MAC2STR(wpa_s->pending_join_iface_addr),
4984                            MAC2STR(iface_addr));
4985                 os_memcpy(wpa_s->pending_join_iface_addr, iface_addr,
4986                           ETH_ALEN);
4987
4988                 freq = p2p_get_oper_freq(wpa_s->global->p2p,
4989                                          wpa_s->pending_join_iface_addr);
4990         }
4991         if (freq >= 0) {
4992                 wpa_printf(MSG_DEBUG, "P2P: Target GO operating frequency "
4993                            "from P2P peer table: %d MHz", freq);
4994         }
4995         if (wpa_s->p2p_join_ssid_len) {
4996                 wpa_printf(MSG_DEBUG, "P2P: Trying to find target GO BSS entry based on BSSID "
4997                            MACSTR " and SSID %s",
4998                            MAC2STR(wpa_s->pending_join_iface_addr),
4999                            wpa_ssid_txt(wpa_s->p2p_join_ssid,
5000                                         wpa_s->p2p_join_ssid_len));
5001                 bss = wpa_bss_get(wpa_s, wpa_s->pending_join_iface_addr,
5002                                   wpa_s->p2p_join_ssid,
5003                                   wpa_s->p2p_join_ssid_len);
5004         }
5005         if (!bss) {
5006                 wpa_printf(MSG_DEBUG, "P2P: Trying to find target GO BSS entry based on BSSID "
5007                            MACSTR, MAC2STR(wpa_s->pending_join_iface_addr));
5008                 bss = wpa_bss_get_bssid_latest(wpa_s,
5009                                                wpa_s->pending_join_iface_addr);
5010         }
5011         if (bss) {
5012                 freq = bss->freq;
5013                 wpa_printf(MSG_DEBUG, "P2P: Target GO operating frequency "
5014                            "from BSS table: %d MHz (SSID %s)", freq,
5015                            wpa_ssid_txt(bss->ssid, bss->ssid_len));
5016         }
5017         if (freq > 0) {
5018                 u16 method;
5019
5020                 if (wpas_check_freq_conflict(wpa_s, freq) > 0) {
5021                         wpa_msg_global(wpa_s->parent, MSG_INFO,
5022                                        P2P_EVENT_GROUP_FORMATION_FAILURE
5023                                        "reason=FREQ_CONFLICT");
5024                         return;
5025                 }
5026
5027                 wpa_printf(MSG_DEBUG, "P2P: Send Provision Discovery Request "
5028                            "prior to joining an existing group (GO " MACSTR
5029                            " freq=%u MHz)",
5030                            MAC2STR(wpa_s->pending_join_dev_addr), freq);
5031                 wpa_s->pending_pd_before_join = 1;
5032
5033                 switch (wpa_s->pending_join_wps_method) {
5034                 case WPS_PIN_DISPLAY:
5035                         method = WPS_CONFIG_KEYPAD;
5036                         break;
5037                 case WPS_PIN_KEYPAD:
5038                         method = WPS_CONFIG_DISPLAY;
5039                         break;
5040                 case WPS_PBC:
5041                         method = WPS_CONFIG_PUSHBUTTON;
5042                         break;
5043                 default:
5044                         method = 0;
5045                         break;
5046                 }
5047
5048                 if ((p2p_get_provisioning_info(wpa_s->global->p2p,
5049                                                wpa_s->pending_join_dev_addr) ==
5050                      method)) {
5051                         /*
5052                          * We have already performed provision discovery for
5053                          * joining the group. Proceed directly to join
5054                          * operation without duplicated provision discovery. */
5055                         wpa_printf(MSG_DEBUG, "P2P: Provision discovery "
5056                                    "with " MACSTR " already done - proceed to "
5057                                    "join",
5058                                    MAC2STR(wpa_s->pending_join_dev_addr));
5059                         wpa_s->pending_pd_before_join = 0;
5060                         goto start;
5061                 }
5062
5063                 if (p2p_prov_disc_req(wpa_s->global->p2p,
5064                                       wpa_s->pending_join_dev_addr,
5065                                       NULL, method, 1,
5066                                       freq, wpa_s->user_initiated_pd) < 0) {
5067                         wpa_printf(MSG_DEBUG, "P2P: Failed to send Provision "
5068                                    "Discovery Request before joining an "
5069                                    "existing group");
5070                         wpa_s->pending_pd_before_join = 0;
5071                         goto start;
5072                 }
5073                 return;
5074         }
5075
5076         wpa_printf(MSG_DEBUG, "P2P: Failed to find BSS/GO - try again later");
5077         eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
5078         eloop_register_timeout(1, 0, wpas_p2p_join_scan, wpa_s, NULL);
5079         wpas_p2p_check_join_scan_limit(wpa_s);
5080         return;
5081
5082 start:
5083         /* Start join operation immediately */
5084         wpas_p2p_join_start(wpa_s, 0, NULL, 0);
5085 }
5086
5087
5088 static void wpas_p2p_join_scan_req(struct wpa_supplicant *wpa_s, int freq,
5089                                    const u8 *ssid, size_t ssid_len)
5090 {
5091         int ret;
5092         struct wpa_driver_scan_params params;
5093         struct wpabuf *wps_ie, *ies;
5094         size_t ielen;
5095         int freqs[2] = { 0, 0 };
5096
5097         os_memset(&params, 0, sizeof(params));
5098
5099         /* P2P Wildcard SSID */
5100         params.num_ssids = 1;
5101         if (ssid && ssid_len) {
5102                 params.ssids[0].ssid = ssid;
5103                 params.ssids[0].ssid_len = ssid_len;
5104                 os_memcpy(wpa_s->p2p_join_ssid, ssid, ssid_len);
5105                 wpa_s->p2p_join_ssid_len = ssid_len;
5106         } else {
5107                 params.ssids[0].ssid = (u8 *) P2P_WILDCARD_SSID;
5108                 params.ssids[0].ssid_len = P2P_WILDCARD_SSID_LEN;
5109                 wpa_s->p2p_join_ssid_len = 0;
5110         }
5111
5112         wpa_s->wps->dev.p2p = 1;
5113         wps_ie = wps_build_probe_req_ie(DEV_PW_DEFAULT, &wpa_s->wps->dev,
5114                                         wpa_s->wps->uuid, WPS_REQ_ENROLLEE, 0,
5115                                         NULL);
5116         if (wps_ie == NULL) {
5117                 wpas_p2p_scan_res_join(wpa_s, NULL);
5118                 return;
5119         }
5120
5121         ielen = p2p_scan_ie_buf_len(wpa_s->global->p2p);
5122         ies = wpabuf_alloc(wpabuf_len(wps_ie) + ielen);
5123         if (ies == NULL) {
5124                 wpabuf_free(wps_ie);
5125                 wpas_p2p_scan_res_join(wpa_s, NULL);
5126                 return;
5127         }
5128         wpabuf_put_buf(ies, wps_ie);
5129         wpabuf_free(wps_ie);
5130
5131         p2p_scan_ie(wpa_s->global->p2p, ies, NULL);
5132
5133         params.p2p_probe = 1;
5134         params.extra_ies = wpabuf_head(ies);
5135         params.extra_ies_len = wpabuf_len(ies);
5136
5137         if (!freq) {
5138                 int oper_freq;
5139                 /*
5140                  * If freq is not provided, check the operating freq of the GO
5141                  * and use a single channel scan on if possible.
5142                  */
5143                 oper_freq = p2p_get_oper_freq(wpa_s->global->p2p,
5144                                               wpa_s->pending_join_iface_addr);
5145                 if (oper_freq > 0)
5146                         freq = oper_freq;
5147         }
5148         if (freq > 0) {
5149                 freqs[0] = freq;
5150                 params.freqs = freqs;
5151         }
5152
5153         /*
5154          * Run a scan to update BSS table and start Provision Discovery once
5155          * the new scan results become available.
5156          */
5157         ret = wpa_drv_scan(wpa_s, &params);
5158         if (!ret) {
5159                 os_get_reltime(&wpa_s->scan_trigger_time);
5160                 wpa_s->scan_res_handler = wpas_p2p_scan_res_join;
5161                 wpa_s->own_scan_requested = 1;
5162         }
5163
5164         wpabuf_free(ies);
5165
5166         if (ret) {
5167                 wpa_printf(MSG_DEBUG, "P2P: Failed to start scan for join - "
5168                            "try again later");
5169                 eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
5170                 eloop_register_timeout(1, 0, wpas_p2p_join_scan, wpa_s, NULL);
5171                 wpas_p2p_check_join_scan_limit(wpa_s);
5172         }
5173 }
5174
5175
5176 static void wpas_p2p_join_scan(void *eloop_ctx, void *timeout_ctx)
5177 {
5178         struct wpa_supplicant *wpa_s = eloop_ctx;
5179         wpas_p2p_join_scan_req(wpa_s, 0, NULL, 0);
5180 }
5181
5182
5183 static int wpas_p2p_join(struct wpa_supplicant *wpa_s, const u8 *iface_addr,
5184                          const u8 *dev_addr, enum p2p_wps_method wps_method,
5185                          int auto_join, int op_freq,
5186                          const u8 *ssid, size_t ssid_len)
5187 {
5188         wpa_printf(MSG_DEBUG, "P2P: Request to join existing group (iface "
5189                    MACSTR " dev " MACSTR " op_freq=%d)%s",
5190                    MAC2STR(iface_addr), MAC2STR(dev_addr), op_freq,
5191                    auto_join ? " (auto_join)" : "");
5192         if (ssid && ssid_len) {
5193                 wpa_printf(MSG_DEBUG, "P2P: Group SSID specified: %s",
5194                            wpa_ssid_txt(ssid, ssid_len));
5195         }
5196
5197         wpa_s->p2p_auto_pd = 0;
5198         wpa_s->p2p_auto_join = !!auto_join;
5199         os_memcpy(wpa_s->pending_join_iface_addr, iface_addr, ETH_ALEN);
5200         os_memcpy(wpa_s->pending_join_dev_addr, dev_addr, ETH_ALEN);
5201         wpa_s->pending_join_wps_method = wps_method;
5202
5203         /* Make sure we are not running find during connection establishment */
5204         wpas_p2p_stop_find(wpa_s);
5205
5206         wpa_s->p2p_join_scan_count = 0;
5207         wpas_p2p_join_scan_req(wpa_s, op_freq, ssid, ssid_len);
5208         return 0;
5209 }
5210
5211
5212 static int wpas_p2p_join_start(struct wpa_supplicant *wpa_s, int freq,
5213                                const u8 *ssid, size_t ssid_len)
5214 {
5215         struct wpa_supplicant *group;
5216         struct p2p_go_neg_results res;
5217         struct wpa_bss *bss;
5218
5219         group = wpas_p2p_get_group_iface(wpa_s, 0, 0);
5220         if (group == NULL)
5221                 return -1;
5222         if (group != wpa_s) {
5223                 os_memcpy(group->p2p_pin, wpa_s->p2p_pin,
5224                           sizeof(group->p2p_pin));
5225                 group->p2p_wps_method = wpa_s->p2p_wps_method;
5226         } else {
5227                 /*
5228                  * Need to mark the current interface for p2p_group_formation
5229                  * when a separate group interface is not used. This is needed
5230                  * to allow p2p_cancel stop a pending p2p_connect-join.
5231                  * wpas_p2p_init_group_interface() addresses this for the case
5232                  * where a separate group interface is used.
5233                  */
5234                 wpa_s->global->p2p_group_formation = wpa_s;
5235         }
5236
5237         group->p2p_in_provisioning = 1;
5238         group->p2p_fallback_to_go_neg = wpa_s->p2p_fallback_to_go_neg;
5239
5240         os_memset(&res, 0, sizeof(res));
5241         os_memcpy(res.peer_device_addr, wpa_s->pending_join_dev_addr, ETH_ALEN);
5242         os_memcpy(res.peer_interface_addr, wpa_s->pending_join_iface_addr,
5243                   ETH_ALEN);
5244         res.wps_method = wpa_s->pending_join_wps_method;
5245         if (freq && ssid && ssid_len) {
5246                 res.freq = freq;
5247                 res.ssid_len = ssid_len;
5248                 os_memcpy(res.ssid, ssid, ssid_len);
5249         } else {
5250                 bss = wpa_bss_get_bssid_latest(wpa_s,
5251                                                wpa_s->pending_join_iface_addr);
5252                 if (bss) {
5253                         res.freq = bss->freq;
5254                         res.ssid_len = bss->ssid_len;
5255                         os_memcpy(res.ssid, bss->ssid, bss->ssid_len);
5256                         wpa_printf(MSG_DEBUG, "P2P: Join target GO operating frequency from BSS table: %d MHz (SSID %s)",
5257                                    bss->freq,
5258                                    wpa_ssid_txt(bss->ssid, bss->ssid_len));
5259                 }
5260         }
5261
5262         if (wpa_s->off_channel_freq || wpa_s->roc_waiting_drv_freq) {
5263                 wpa_printf(MSG_DEBUG, "P2P: Cancel remain-on-channel prior to "
5264                            "starting client");
5265                 wpa_drv_cancel_remain_on_channel(wpa_s);
5266                 wpa_s->off_channel_freq = 0;
5267                 wpa_s->roc_waiting_drv_freq = 0;
5268         }
5269         wpas_start_wps_enrollee(group, &res);
5270
5271         /*
5272          * Allow a longer timeout for join-a-running-group than normal 15
5273          * second group formation timeout since the GO may not have authorized
5274          * our connection yet.
5275          */
5276         eloop_cancel_timeout(wpas_p2p_group_formation_timeout, wpa_s, NULL);
5277         eloop_register_timeout(60, 0, wpas_p2p_group_formation_timeout,
5278                                wpa_s, NULL);
5279
5280         return 0;
5281 }
5282
5283
5284 static int wpas_p2p_setup_freqs(struct wpa_supplicant *wpa_s, int freq,
5285                                 int *force_freq, int *pref_freq, int go)
5286 {
5287         struct wpa_used_freq_data *freqs;
5288         int res, best_freq, num_unused;
5289         unsigned int freq_in_use = 0, num, i;
5290
5291         freqs = os_calloc(wpa_s->num_multichan_concurrent,
5292                           sizeof(struct wpa_used_freq_data));
5293         if (!freqs)
5294                 return -1;
5295
5296         num = wpas_p2p_valid_oper_freqs(wpa_s, freqs,
5297                                         wpa_s->num_multichan_concurrent);
5298
5299         /*
5300          * It is possible that the total number of used frequencies is bigger
5301          * than the number of frequencies used for P2P, so get the system wide
5302          * number of unused frequencies.
5303          */
5304         num_unused = wpas_p2p_num_unused_channels(wpa_s);
5305
5306         wpa_printf(MSG_DEBUG,
5307                    "P2P: Setup freqs: freq=%d num_MCC=%d shared_freqs=%u num_unused=%d",
5308                    freq, wpa_s->num_multichan_concurrent, num, num_unused);
5309
5310         if (freq > 0) {
5311                 int ret;
5312                 if (go)
5313                         ret = p2p_supported_freq(wpa_s->global->p2p, freq);
5314                 else
5315                         ret = p2p_supported_freq_cli(wpa_s->global->p2p, freq);
5316                 if (!ret) {
5317                         wpa_printf(MSG_DEBUG, "P2P: The forced channel "
5318                                    "(%u MHz) is not supported for P2P uses",
5319                                    freq);
5320                         res = -3;
5321                         goto exit_free;
5322                 }
5323
5324                 for (i = 0; i < num; i++) {
5325                         if (freqs[i].freq == freq)
5326                                 freq_in_use = 1;
5327                 }
5328
5329                 if (num_unused <= 0 && !freq_in_use) {
5330                         wpa_printf(MSG_DEBUG, "P2P: Cannot start P2P group on %u MHz as there are no available channels",
5331                                    freq);
5332                         res = -2;
5333                         goto exit_free;
5334                 }
5335                 wpa_printf(MSG_DEBUG, "P2P: Trying to force us to use the "
5336                            "requested channel (%u MHz)", freq);
5337                 *force_freq = freq;
5338                 goto exit_ok;
5339         }
5340
5341         best_freq = wpas_p2p_pick_best_used_freq(wpa_s, freqs, num);
5342
5343         /* We have a candidate frequency to use */
5344         if (best_freq > 0) {
5345                 if (*pref_freq == 0 && num_unused > 0) {
5346                         wpa_printf(MSG_DEBUG, "P2P: Try to prefer a frequency (%u MHz) we are already using",
5347                                    best_freq);
5348                         *pref_freq = best_freq;
5349                 } else {
5350                         wpa_printf(MSG_DEBUG, "P2P: Try to force us to use frequency (%u MHz) which is already in use",
5351                                    best_freq);
5352                         *force_freq = best_freq;
5353                 }
5354         } else if (num_unused > 0) {
5355                 wpa_printf(MSG_DEBUG,
5356                            "P2P: Current operating channels are not available for P2P. Try to use another channel");
5357                 *force_freq = 0;
5358         } else {
5359                 wpa_printf(MSG_DEBUG,
5360                            "P2P: All channels are in use and none of them are P2P enabled. Cannot start P2P group");
5361                 res = -2;
5362                 goto exit_free;
5363         }
5364
5365 exit_ok:
5366         res = 0;
5367 exit_free:
5368         os_free(freqs);
5369         return res;
5370 }
5371
5372
5373 /**
5374  * wpas_p2p_connect - Request P2P Group Formation to be started
5375  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
5376  * @peer_addr: Address of the peer P2P Device
5377  * @pin: PIN to use during provisioning or %NULL to indicate PBC mode
5378  * @persistent_group: Whether to create a persistent group
5379  * @auto_join: Whether to select join vs. GO Negotiation automatically
5380  * @join: Whether to join an existing group (as a client) instead of starting
5381  *      Group Owner negotiation; @peer_addr is BSSID in that case
5382  * @auth: Whether to only authorize the connection instead of doing that and
5383  *      initiating Group Owner negotiation
5384  * @go_intent: GO Intent or -1 to use default
5385  * @freq: Frequency for the group or 0 for auto-selection
5386  * @persistent_id: Persistent group credentials to use for forcing GO
5387  *      parameters or -1 to generate new values (SSID/passphrase)
5388  * @pd: Whether to send Provision Discovery prior to GO Negotiation as an
5389  *      interoperability workaround when initiating group formation
5390  * @ht40: Start GO with 40 MHz channel width
5391  * @vht:  Start GO with VHT support
5392  * Returns: 0 or new PIN (if pin was %NULL) on success, -1 on unspecified
5393  *      failure, -2 on failure due to channel not currently available,
5394  *      -3 if forced channel is not supported
5395  */
5396 int wpas_p2p_connect(struct wpa_supplicant *wpa_s, const u8 *peer_addr,
5397                      const char *pin, enum p2p_wps_method wps_method,
5398                      int persistent_group, int auto_join, int join, int auth,
5399                      int go_intent, int freq, int persistent_id, int pd,
5400                      int ht40, int vht)
5401 {
5402         int force_freq = 0, pref_freq = 0;
5403         int ret = 0, res;
5404         enum wpa_driver_if_type iftype;
5405         const u8 *if_addr;
5406         struct wpa_ssid *ssid = NULL;
5407
5408         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5409                 return -1;
5410
5411         if (persistent_id >= 0) {
5412                 ssid = wpa_config_get_network(wpa_s->conf, persistent_id);
5413                 if (ssid == NULL || ssid->disabled != 2 ||
5414                     ssid->mode != WPAS_MODE_P2P_GO)
5415                         return -1;
5416         }
5417
5418         os_free(wpa_s->global->add_psk);
5419         wpa_s->global->add_psk = NULL;
5420
5421         wpa_s->global->p2p_fail_on_wps_complete = 0;
5422
5423         if (go_intent < 0)
5424                 go_intent = wpa_s->conf->p2p_go_intent;
5425
5426         if (!auth)
5427                 wpa_s->p2p_long_listen = 0;
5428
5429         wpa_s->p2p_wps_method = wps_method;
5430         wpa_s->p2p_persistent_group = !!persistent_group;
5431         wpa_s->p2p_persistent_id = persistent_id;
5432         wpa_s->p2p_go_intent = go_intent;
5433         wpa_s->p2p_connect_freq = freq;
5434         wpa_s->p2p_fallback_to_go_neg = 0;
5435         wpa_s->p2p_pd_before_go_neg = !!pd;
5436         wpa_s->p2p_go_ht40 = !!ht40;
5437         wpa_s->p2p_go_vht = !!vht;
5438
5439         if (pin)
5440                 os_strlcpy(wpa_s->p2p_pin, pin, sizeof(wpa_s->p2p_pin));
5441         else if (wps_method == WPS_PIN_DISPLAY) {
5442                 ret = wps_generate_pin();
5443                 res = os_snprintf(wpa_s->p2p_pin, sizeof(wpa_s->p2p_pin),
5444                                   "%08d", ret);
5445                 if (os_snprintf_error(sizeof(wpa_s->p2p_pin), res))
5446                         wpa_s->p2p_pin[sizeof(wpa_s->p2p_pin) - 1] = '\0';
5447                 wpa_printf(MSG_DEBUG, "P2P: Randomly generated PIN: %s",
5448                            wpa_s->p2p_pin);
5449         } else
5450                 wpa_s->p2p_pin[0] = '\0';
5451
5452         if (join || auto_join) {
5453                 u8 iface_addr[ETH_ALEN], dev_addr[ETH_ALEN];
5454                 if (auth) {
5455                         wpa_printf(MSG_DEBUG, "P2P: Authorize invitation to "
5456                                    "connect a running group from " MACSTR,
5457                                    MAC2STR(peer_addr));
5458                         os_memcpy(wpa_s->p2p_auth_invite, peer_addr, ETH_ALEN);
5459                         return ret;
5460                 }
5461                 os_memcpy(dev_addr, peer_addr, ETH_ALEN);
5462                 if (p2p_get_interface_addr(wpa_s->global->p2p, peer_addr,
5463                                            iface_addr) < 0) {
5464                         os_memcpy(iface_addr, peer_addr, ETH_ALEN);
5465                         p2p_get_dev_addr(wpa_s->global->p2p, peer_addr,
5466                                          dev_addr);
5467                 }
5468                 if (auto_join) {
5469                         os_get_reltime(&wpa_s->p2p_auto_started);
5470                         wpa_printf(MSG_DEBUG, "P2P: Auto join started at "
5471                                    "%ld.%06ld",
5472                                    wpa_s->p2p_auto_started.sec,
5473                                    wpa_s->p2p_auto_started.usec);
5474                 }
5475                 wpa_s->user_initiated_pd = 1;
5476                 if (wpas_p2p_join(wpa_s, iface_addr, dev_addr, wps_method,
5477                                   auto_join, freq, NULL, 0) < 0)
5478                         return -1;
5479                 return ret;
5480         }
5481
5482         res = wpas_p2p_setup_freqs(wpa_s, freq, &force_freq, &pref_freq,
5483                                    go_intent == 15);
5484         if (res)
5485                 return res;
5486         wpas_p2p_set_own_freq_preference(wpa_s,
5487                                          force_freq ? force_freq : pref_freq);
5488
5489         wpa_s->create_p2p_iface = wpas_p2p_create_iface(wpa_s);
5490
5491         if (wpa_s->create_p2p_iface) {
5492                 /* Prepare to add a new interface for the group */
5493                 iftype = WPA_IF_P2P_GROUP;
5494                 if (go_intent == 15)
5495                         iftype = WPA_IF_P2P_GO;
5496                 if (wpas_p2p_add_group_interface(wpa_s, iftype) < 0) {
5497                         wpa_printf(MSG_ERROR, "P2P: Failed to allocate a new "
5498                                    "interface for the group");
5499                         return -1;
5500                 }
5501
5502                 if_addr = wpa_s->pending_interface_addr;
5503         } else
5504                 if_addr = wpa_s->own_addr;
5505
5506         if (auth) {
5507                 if (wpas_p2p_auth_go_neg(wpa_s, peer_addr, wps_method,
5508                                          go_intent, if_addr,
5509                                          force_freq, persistent_group, ssid,
5510                                          pref_freq) < 0)
5511                         return -1;
5512                 return ret;
5513         }
5514
5515         if (wpas_p2p_start_go_neg(wpa_s, peer_addr, wps_method,
5516                                   go_intent, if_addr, force_freq,
5517                                   persistent_group, ssid, pref_freq) < 0) {
5518                 if (wpa_s->create_p2p_iface)
5519                         wpas_p2p_remove_pending_group_interface(wpa_s);
5520                 return -1;
5521         }
5522         return ret;
5523 }
5524
5525
5526 /**
5527  * wpas_p2p_remain_on_channel_cb - Indication of remain-on-channel start
5528  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
5529  * @freq: Frequency of the channel in MHz
5530  * @duration: Duration of the stay on the channel in milliseconds
5531  *
5532  * This callback is called when the driver indicates that it has started the
5533  * requested remain-on-channel duration.
5534  */
5535 void wpas_p2p_remain_on_channel_cb(struct wpa_supplicant *wpa_s,
5536                                    unsigned int freq, unsigned int duration)
5537 {
5538         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5539                 return;
5540         wpa_printf(MSG_DEBUG, "P2P: remain-on-channel callback (off_channel_freq=%u pending_listen_freq=%d roc_waiting_drv_freq=%d freq=%u duration=%u)",
5541                    wpa_s->off_channel_freq, wpa_s->pending_listen_freq,
5542                    wpa_s->roc_waiting_drv_freq, freq, duration);
5543         if (wpa_s->off_channel_freq &&
5544             wpa_s->off_channel_freq == wpa_s->pending_listen_freq) {
5545                 p2p_listen_cb(wpa_s->global->p2p, wpa_s->pending_listen_freq,
5546                               wpa_s->pending_listen_duration);
5547                 wpa_s->pending_listen_freq = 0;
5548         } else {
5549                 wpa_printf(MSG_DEBUG, "P2P: Ignore remain-on-channel callback (off_channel_freq=%u pending_listen_freq=%d freq=%u duration=%u)",
5550                            wpa_s->off_channel_freq, wpa_s->pending_listen_freq,
5551                            freq, duration);
5552         }
5553 }
5554
5555
5556 int wpas_p2p_listen_start(struct wpa_supplicant *wpa_s, unsigned int timeout)
5557 {
5558         /* Limit maximum Listen state time based on driver limitation. */
5559         if (timeout > wpa_s->max_remain_on_chan)
5560                 timeout = wpa_s->max_remain_on_chan;
5561
5562         return p2p_listen(wpa_s->global->p2p, timeout);
5563 }
5564
5565
5566 /**
5567  * wpas_p2p_cancel_remain_on_channel_cb - Remain-on-channel timeout
5568  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
5569  * @freq: Frequency of the channel in MHz
5570  *
5571  * This callback is called when the driver indicates that a remain-on-channel
5572  * operation has been completed, i.e., the duration on the requested channel
5573  * has timed out.
5574  */
5575 void wpas_p2p_cancel_remain_on_channel_cb(struct wpa_supplicant *wpa_s,
5576                                           unsigned int freq)
5577 {
5578         wpa_printf(MSG_DEBUG, "P2P: Cancel remain-on-channel callback "
5579                    "(p2p_long_listen=%d ms pending_action_tx=%p)",
5580                    wpa_s->p2p_long_listen, offchannel_pending_action_tx(wpa_s));
5581         wpas_p2p_listen_work_done(wpa_s);
5582         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5583                 return;
5584         if (wpa_s->p2p_long_listen > 0)
5585                 wpa_s->p2p_long_listen -= wpa_s->max_remain_on_chan;
5586         if (p2p_listen_end(wpa_s->global->p2p, freq) > 0)
5587                 return; /* P2P module started a new operation */
5588         if (offchannel_pending_action_tx(wpa_s))
5589                 return;
5590         if (wpa_s->p2p_long_listen > 0) {
5591                 wpa_printf(MSG_DEBUG, "P2P: Continuing long Listen state");
5592                 wpas_p2p_listen_start(wpa_s, wpa_s->p2p_long_listen);
5593         } else {
5594                 /*
5595                  * When listen duration is over, stop listen & update p2p_state
5596                  * to IDLE.
5597                  */
5598                 p2p_stop_listen(wpa_s->global->p2p);
5599         }
5600 }
5601
5602
5603 /**
5604  * wpas_p2p_group_remove - Remove a P2P group
5605  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
5606  * @ifname: Network interface name of the group interface or "*" to remove all
5607  *      groups
5608  * Returns: 0 on success, -1 on failure
5609  *
5610  * This function is used to remove a P2P group. This can be used to disconnect
5611  * from a group in which the local end is a P2P Client or to end a P2P Group in
5612  * case the local end is the Group Owner. If a virtual network interface was
5613  * created for this group, that interface will be removed. Otherwise, only the
5614  * configured P2P group network will be removed from the interface.
5615  */
5616 int wpas_p2p_group_remove(struct wpa_supplicant *wpa_s, const char *ifname)
5617 {
5618         struct wpa_global *global = wpa_s->global;
5619         struct wpa_supplicant *calling_wpa_s = wpa_s;
5620
5621         if (os_strcmp(ifname, "*") == 0) {
5622                 struct wpa_supplicant *prev;
5623                 wpa_s = global->ifaces;
5624                 while (wpa_s) {
5625                         prev = wpa_s;
5626                         wpa_s = wpa_s->next;
5627                         if (prev->p2p_group_interface !=
5628                             NOT_P2P_GROUP_INTERFACE ||
5629                             (prev->current_ssid &&
5630                              prev->current_ssid->p2p_group))
5631                                 wpas_p2p_disconnect_safely(prev, calling_wpa_s);
5632                 }
5633                 return 0;
5634         }
5635
5636         for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) {
5637                 if (os_strcmp(wpa_s->ifname, ifname) == 0)
5638                         break;
5639         }
5640
5641         return wpas_p2p_disconnect_safely(wpa_s, calling_wpa_s);
5642 }
5643
5644
5645 static int wpas_p2p_select_go_freq(struct wpa_supplicant *wpa_s, int freq)
5646 {
5647         unsigned int r;
5648
5649         if (freq == 2) {
5650                 wpa_printf(MSG_DEBUG, "P2P: Request to start GO on 2.4 GHz "
5651                            "band");
5652                 if (wpa_s->best_24_freq > 0 &&
5653                     p2p_supported_freq_go(wpa_s->global->p2p,
5654                                           wpa_s->best_24_freq)) {
5655                         freq = wpa_s->best_24_freq;
5656                         wpa_printf(MSG_DEBUG, "P2P: Use best 2.4 GHz band "
5657                                    "channel: %d MHz", freq);
5658                 } else {
5659                         if (os_get_random((u8 *) &r, sizeof(r)) < 0)
5660                                 return -1;
5661                         freq = 2412 + (r % 3) * 25;
5662                         wpa_printf(MSG_DEBUG, "P2P: Use random 2.4 GHz band "
5663                                    "channel: %d MHz", freq);
5664                 }
5665         }
5666
5667         if (freq == 5) {
5668                 wpa_printf(MSG_DEBUG, "P2P: Request to start GO on 5 GHz "
5669                            "band");
5670                 if (wpa_s->best_5_freq > 0 &&
5671                     p2p_supported_freq_go(wpa_s->global->p2p,
5672                                        wpa_s->best_5_freq)) {
5673                         freq = wpa_s->best_5_freq;
5674                         wpa_printf(MSG_DEBUG, "P2P: Use best 5 GHz band "
5675                                    "channel: %d MHz", freq);
5676                 } else {
5677                         if (os_get_random((u8 *) &r, sizeof(r)) < 0)
5678                                 return -1;
5679                         freq = 5180 + (r % 4) * 20;
5680                         if (!p2p_supported_freq_go(wpa_s->global->p2p, freq)) {
5681                                 wpa_printf(MSG_DEBUG, "P2P: Could not select "
5682                                            "5 GHz channel for P2P group");
5683                                 return -1;
5684                         }
5685                         wpa_printf(MSG_DEBUG, "P2P: Use random 5 GHz band "
5686                                    "channel: %d MHz", freq);
5687                 }
5688         }
5689
5690         if (freq > 0 && !p2p_supported_freq_go(wpa_s->global->p2p, freq)) {
5691                 wpa_printf(MSG_DEBUG, "P2P: The forced channel for GO "
5692                            "(%u MHz) is not supported for P2P uses",
5693                            freq);
5694                 return -1;
5695         }
5696
5697         return freq;
5698 }
5699
5700
5701 static int wpas_p2p_select_freq_no_pref(struct wpa_supplicant *wpa_s,
5702                                         struct p2p_go_neg_results *params,
5703                                         const struct p2p_channels *channels)
5704 {
5705         unsigned int i, r;
5706
5707         /* first try some random selection of the social channels */
5708         if (os_get_random((u8 *) &r, sizeof(r)) < 0)
5709                 return -1;
5710
5711         for (i = 0; i < 3; i++) {
5712                 params->freq = 2412 + ((r + i) % 3) * 25;
5713                 if (!wpas_p2p_disallowed_freq(wpa_s->global, params->freq) &&
5714                     freq_included(channels, params->freq) &&
5715                     p2p_supported_freq(wpa_s->global->p2p, params->freq))
5716                         goto out;
5717         }
5718
5719         /* try all channels in reg. class 81 */
5720         for (i = 0; i < 11; i++) {
5721                 params->freq = 2412 + i * 5;
5722                 if (!wpas_p2p_disallowed_freq(wpa_s->global, params->freq) &&
5723                     freq_included(channels, params->freq) &&
5724                     p2p_supported_freq(wpa_s->global->p2p, params->freq))
5725                         goto out;
5726         }
5727
5728         /* try social channel class 180 channel 2 */
5729         params->freq = 58320 + 1 * 2160;
5730         if (!wpas_p2p_disallowed_freq(wpa_s->global, params->freq) &&
5731             freq_included(channels, params->freq) &&
5732             p2p_supported_freq(wpa_s->global->p2p, params->freq))
5733                 goto out;
5734
5735         /* try all channels in reg. class 180 */
5736         for (i = 0; i < 4; i++) {
5737                 params->freq = 58320 + i * 2160;
5738                 if (!wpas_p2p_disallowed_freq(wpa_s->global, params->freq) &&
5739                     freq_included(channels, params->freq) &&
5740                     p2p_supported_freq(wpa_s->global->p2p, params->freq))
5741                         goto out;
5742         }
5743
5744         wpa_printf(MSG_DEBUG, "P2P: No 2.4 and 60 GHz channel allowed");
5745         return -1;
5746 out:
5747         wpa_printf(MSG_DEBUG, "P2P: Set GO freq %d MHz (no preference known)",
5748                    params->freq);
5749         return 0;
5750 }
5751
5752
5753 static int wpas_p2p_init_go_params(struct wpa_supplicant *wpa_s,
5754                                    struct p2p_go_neg_results *params,
5755                                    int freq, int ht40, int vht,
5756                                    const struct p2p_channels *channels)
5757 {
5758         struct wpa_used_freq_data *freqs;
5759         unsigned int pref_freq, cand_freq;
5760         unsigned int num, i;
5761
5762         os_memset(params, 0, sizeof(*params));
5763         params->role_go = 1;
5764         params->ht40 = ht40;
5765         params->vht = vht;
5766         if (freq) {
5767                 if (!freq_included(channels, freq)) {
5768                         wpa_printf(MSG_DEBUG, "P2P: Forced GO freq %d MHz not "
5769                                    "accepted", freq);
5770                         return -1;
5771                 }
5772                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on forced "
5773                            "frequency %d MHz", freq);
5774                 params->freq = freq;
5775         } else if (wpa_s->conf->p2p_oper_reg_class == 81 &&
5776                    wpa_s->conf->p2p_oper_channel >= 1 &&
5777                    wpa_s->conf->p2p_oper_channel <= 11 &&
5778                    freq_included(channels,
5779                                  2407 + 5 * wpa_s->conf->p2p_oper_channel)) {
5780                 params->freq = 2407 + 5 * wpa_s->conf->p2p_oper_channel;
5781                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on configured "
5782                            "frequency %d MHz", params->freq);
5783         } else if ((wpa_s->conf->p2p_oper_reg_class == 115 ||
5784                     wpa_s->conf->p2p_oper_reg_class == 116 ||
5785                     wpa_s->conf->p2p_oper_reg_class == 117 ||
5786                     wpa_s->conf->p2p_oper_reg_class == 124 ||
5787                     wpa_s->conf->p2p_oper_reg_class == 126 ||
5788                     wpa_s->conf->p2p_oper_reg_class == 127) &&
5789                    freq_included(channels,
5790                                  5000 + 5 * wpa_s->conf->p2p_oper_channel)) {
5791                 params->freq = 5000 + 5 * wpa_s->conf->p2p_oper_channel;
5792                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on configured "
5793                            "frequency %d MHz", params->freq);
5794         } else if (wpa_s->conf->p2p_oper_channel == 0 &&
5795                    wpa_s->best_overall_freq > 0 &&
5796                    p2p_supported_freq_go(wpa_s->global->p2p,
5797                                          wpa_s->best_overall_freq) &&
5798                    freq_included(channels, wpa_s->best_overall_freq)) {
5799                 params->freq = wpa_s->best_overall_freq;
5800                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on best overall "
5801                            "channel %d MHz", params->freq);
5802         } else if (wpa_s->conf->p2p_oper_channel == 0 &&
5803                    wpa_s->best_24_freq > 0 &&
5804                    p2p_supported_freq_go(wpa_s->global->p2p,
5805                                          wpa_s->best_24_freq) &&
5806                    freq_included(channels, wpa_s->best_24_freq)) {
5807                 params->freq = wpa_s->best_24_freq;
5808                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on best 2.4 GHz "
5809                            "channel %d MHz", params->freq);
5810         } else if (wpa_s->conf->p2p_oper_channel == 0 &&
5811                    wpa_s->best_5_freq > 0 &&
5812                    p2p_supported_freq_go(wpa_s->global->p2p,
5813                                          wpa_s->best_5_freq) &&
5814                    freq_included(channels, wpa_s->best_5_freq)) {
5815                 params->freq = wpa_s->best_5_freq;
5816                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on best 5 GHz "
5817                            "channel %d MHz", params->freq);
5818         } else if ((pref_freq = p2p_get_pref_freq(wpa_s->global->p2p,
5819                                                   channels))) {
5820                 params->freq = pref_freq;
5821                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq %d MHz from preferred "
5822                            "channels", params->freq);
5823         } else {
5824                 /* no preference, select some channel */
5825                 if (wpas_p2p_select_freq_no_pref(wpa_s, params, channels) < 0)
5826                         return -1;
5827         }
5828
5829         freqs = os_calloc(wpa_s->num_multichan_concurrent,
5830                           sizeof(struct wpa_used_freq_data));
5831         if (!freqs)
5832                 return -1;
5833
5834         num = wpas_p2p_valid_oper_freqs(wpa_s, freqs,
5835                                         wpa_s->num_multichan_concurrent);
5836
5837         cand_freq = wpas_p2p_pick_best_used_freq(wpa_s, freqs, num);
5838
5839         /* First try the best used frequency if possible */
5840         if (!freq && cand_freq > 0 && freq_included(channels, cand_freq)) {
5841                 params->freq = cand_freq;
5842         } else if (!freq) {
5843                 /* Try any of the used frequencies */
5844                 for (i = 0; i < num; i++) {
5845                         if (freq_included(channels, freqs[i].freq)) {
5846                                 wpa_printf(MSG_DEBUG, "P2P: Force GO on a channel we are already using (%u MHz)",
5847                                            freqs[i].freq);
5848                                 params->freq = freqs[i].freq;
5849                                 break;
5850                         }
5851                 }
5852
5853                 if (i == num) {
5854                         if (wpas_p2p_num_unused_channels(wpa_s) <= 0) {
5855                                 wpa_printf(MSG_DEBUG, "P2P: Cannot force GO on any of the channels we are already using");
5856                                 os_free(freqs);
5857                                 return -1;
5858                         } else {
5859                                 wpa_printf(MSG_DEBUG, "P2P: Cannot force GO on any of the channels we are already using. Use one of the free channels");
5860                         }
5861                 }
5862         } else {
5863                 for (i = 0; i < num; i++) {
5864                         if (freqs[i].freq == freq)
5865                                 break;
5866                 }
5867
5868                 if (i == num) {
5869                         if (wpas_p2p_num_unused_channels(wpa_s) <= 0) {
5870                                 if (freq)
5871                                         wpa_printf(MSG_DEBUG, "P2P: Cannot force GO on freq (%u MHz) as all the channels are in use", freq);
5872                                 os_free(freqs);
5873                                 return -1;
5874                         } else {
5875                                 wpa_printf(MSG_DEBUG, "P2P: Use one of the free channels");
5876                         }
5877                 }
5878         }
5879
5880         os_free(freqs);
5881         return 0;
5882 }
5883
5884
5885 static struct wpa_supplicant *
5886 wpas_p2p_get_group_iface(struct wpa_supplicant *wpa_s, int addr_allocated,
5887                          int go)
5888 {
5889         struct wpa_supplicant *group_wpa_s;
5890
5891         if (!wpas_p2p_create_iface(wpa_s)) {
5892                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Use same interface for group "
5893                         "operations");
5894                 wpa_s->p2p_first_connection_timeout = 0;
5895                 return wpa_s;
5896         }
5897
5898         if (wpas_p2p_add_group_interface(wpa_s, go ? WPA_IF_P2P_GO :
5899                                          WPA_IF_P2P_CLIENT) < 0) {
5900                 wpa_msg_global(wpa_s, MSG_ERROR,
5901                                "P2P: Failed to add group interface");
5902                 return NULL;
5903         }
5904         group_wpa_s = wpas_p2p_init_group_interface(wpa_s, go);
5905         if (group_wpa_s == NULL) {
5906                 wpa_msg_global(wpa_s, MSG_ERROR,
5907                                "P2P: Failed to initialize group interface");
5908                 wpas_p2p_remove_pending_group_interface(wpa_s);
5909                 return NULL;
5910         }
5911
5912         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Use separate group interface %s",
5913                 group_wpa_s->ifname);
5914         group_wpa_s->p2p_first_connection_timeout = 0;
5915         return group_wpa_s;
5916 }
5917
5918
5919 /**
5920  * wpas_p2p_group_add - Add a new P2P group with local end as Group Owner
5921  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
5922  * @persistent_group: Whether to create a persistent group
5923  * @freq: Frequency for the group or 0 to indicate no hardcoding
5924  * @ht40: Start GO with 40 MHz channel width
5925  * @vht:  Start GO with VHT support
5926  * Returns: 0 on success, -1 on failure
5927  *
5928  * This function creates a new P2P group with the local end as the Group Owner,
5929  * i.e., without using Group Owner Negotiation.
5930  */
5931 int wpas_p2p_group_add(struct wpa_supplicant *wpa_s, int persistent_group,
5932                        int freq, int ht40, int vht)
5933 {
5934         struct p2p_go_neg_results params;
5935
5936         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5937                 return -1;
5938
5939         os_free(wpa_s->global->add_psk);
5940         wpa_s->global->add_psk = NULL;
5941
5942         /* Make sure we are not running find during connection establishment */
5943         wpa_printf(MSG_DEBUG, "P2P: Stop any on-going P2P FIND");
5944         wpas_p2p_stop_find_oper(wpa_s);
5945
5946         freq = wpas_p2p_select_go_freq(wpa_s, freq);
5947         if (freq < 0)
5948                 return -1;
5949
5950         if (wpas_p2p_init_go_params(wpa_s, &params, freq, ht40, vht, NULL))
5951                 return -1;
5952         if (params.freq &&
5953             !p2p_supported_freq_go(wpa_s->global->p2p, params.freq)) {
5954                 wpa_printf(MSG_DEBUG, "P2P: The selected channel for GO "
5955                            "(%u MHz) is not supported for P2P uses",
5956                            params.freq);
5957                 return -1;
5958         }
5959         p2p_go_params(wpa_s->global->p2p, &params);
5960         params.persistent_group = persistent_group;
5961
5962         wpa_s = wpas_p2p_get_group_iface(wpa_s, 0, 1);
5963         if (wpa_s == NULL)
5964                 return -1;
5965         wpas_start_wps_go(wpa_s, &params, 0);
5966
5967         return 0;
5968 }
5969
5970
5971 static int wpas_start_p2p_client(struct wpa_supplicant *wpa_s,
5972                                  struct wpa_ssid *params, int addr_allocated,
5973                                  int freq)
5974 {
5975         struct wpa_ssid *ssid;
5976
5977         wpa_s = wpas_p2p_get_group_iface(wpa_s, addr_allocated, 0);
5978         if (wpa_s == NULL)
5979                 return -1;
5980         wpa_s->p2p_last_4way_hs_fail = NULL;
5981
5982         wpa_supplicant_ap_deinit(wpa_s);
5983
5984         ssid = wpa_config_add_network(wpa_s->conf);
5985         if (ssid == NULL)
5986                 return -1;
5987         wpa_config_set_network_defaults(ssid);
5988         ssid->temporary = 1;
5989         ssid->proto = WPA_PROTO_RSN;
5990         ssid->pairwise_cipher = WPA_CIPHER_CCMP;
5991         ssid->group_cipher = WPA_CIPHER_CCMP;
5992         ssid->key_mgmt = WPA_KEY_MGMT_PSK;
5993         ssid->ssid = os_malloc(params->ssid_len);
5994         if (ssid->ssid == NULL) {
5995                 wpa_config_remove_network(wpa_s->conf, ssid->id);
5996                 return -1;
5997         }
5998         os_memcpy(ssid->ssid, params->ssid, params->ssid_len);
5999         ssid->ssid_len = params->ssid_len;
6000         ssid->p2p_group = 1;
6001         ssid->export_keys = 1;
6002         if (params->psk_set) {
6003                 os_memcpy(ssid->psk, params->psk, 32);
6004                 ssid->psk_set = 1;
6005         }
6006         if (params->passphrase)
6007                 ssid->passphrase = os_strdup(params->passphrase);
6008
6009         wpa_s->show_group_started = 1;
6010         wpa_s->p2p_in_invitation = 1;
6011         wpa_s->p2p_invite_go_freq = freq;
6012
6013         eloop_cancel_timeout(wpas_p2p_group_formation_timeout, wpa_s->parent,
6014                              NULL);
6015         eloop_register_timeout(P2P_MAX_INITIAL_CONN_WAIT, 0,
6016                                wpas_p2p_group_formation_timeout,
6017                                wpa_s->parent, NULL);
6018         wpa_supplicant_select_network(wpa_s, ssid);
6019
6020         return 0;
6021 }
6022
6023
6024 int wpas_p2p_group_add_persistent(struct wpa_supplicant *wpa_s,
6025                                   struct wpa_ssid *ssid, int addr_allocated,
6026                                   int force_freq, int neg_freq, int ht40,
6027                                   int vht, const struct p2p_channels *channels,
6028                                   int connection_timeout)
6029 {
6030         struct p2p_go_neg_results params;
6031         int go = 0, freq;
6032
6033         if (ssid->disabled != 2 || ssid->ssid == NULL)
6034                 return -1;
6035
6036         if (wpas_get_p2p_group(wpa_s, ssid->ssid, ssid->ssid_len, &go) &&
6037             go == (ssid->mode == WPAS_MODE_P2P_GO)) {
6038                 wpa_printf(MSG_DEBUG, "P2P: Requested persistent group is "
6039                            "already running");
6040                 return 0;
6041         }
6042
6043         os_free(wpa_s->global->add_psk);
6044         wpa_s->global->add_psk = NULL;
6045
6046         /* Make sure we are not running find during connection establishment */
6047         wpas_p2p_stop_find_oper(wpa_s);
6048
6049         wpa_s->p2p_fallback_to_go_neg = 0;
6050
6051         if (ssid->mode == WPAS_MODE_P2P_GO) {
6052                 if (force_freq > 0) {
6053                         freq = wpas_p2p_select_go_freq(wpa_s, force_freq);
6054                         if (freq < 0)
6055                                 return -1;
6056                 } else {
6057                         freq = wpas_p2p_select_go_freq(wpa_s, neg_freq);
6058                         if (freq < 0 ||
6059                             (freq > 0 && !freq_included(channels, freq)))
6060                                 freq = 0;
6061                 }
6062         } else {
6063                 freq = neg_freq;
6064                 if (freq < 0 ||
6065                     (freq > 0 && !freq_included(channels, freq)))
6066                         freq = 0;
6067         }
6068
6069         if (ssid->mode == WPAS_MODE_INFRA)
6070                 return wpas_start_p2p_client(wpa_s, ssid, addr_allocated, freq);
6071
6072         if (ssid->mode != WPAS_MODE_P2P_GO)
6073                 return -1;
6074
6075         if (wpas_p2p_init_go_params(wpa_s, &params, freq, ht40, vht, channels))
6076                 return -1;
6077
6078         params.role_go = 1;
6079         params.psk_set = ssid->psk_set;
6080         if (params.psk_set)
6081                 os_memcpy(params.psk, ssid->psk, sizeof(params.psk));
6082         if (ssid->passphrase) {
6083                 if (os_strlen(ssid->passphrase) >= sizeof(params.passphrase)) {
6084                         wpa_printf(MSG_ERROR, "P2P: Invalid passphrase in "
6085                                    "persistent group");
6086                         return -1;
6087                 }
6088                 os_strlcpy(params.passphrase, ssid->passphrase,
6089                            sizeof(params.passphrase));
6090         }
6091         os_memcpy(params.ssid, ssid->ssid, ssid->ssid_len);
6092         params.ssid_len = ssid->ssid_len;
6093         params.persistent_group = 1;
6094
6095         wpa_s = wpas_p2p_get_group_iface(wpa_s, addr_allocated, 1);
6096         if (wpa_s == NULL)
6097                 return -1;
6098
6099         p2p_channels_to_freqs(channels, params.freq_list, P2P_MAX_CHANNELS);
6100
6101         wpa_s->p2p_first_connection_timeout = connection_timeout;
6102         wpas_start_wps_go(wpa_s, &params, 0);
6103
6104         return 0;
6105 }
6106
6107
6108 static void wpas_p2p_ie_update(void *ctx, struct wpabuf *beacon_ies,
6109                                struct wpabuf *proberesp_ies)
6110 {
6111         struct wpa_supplicant *wpa_s = ctx;
6112         if (wpa_s->ap_iface) {
6113                 struct hostapd_data *hapd = wpa_s->ap_iface->bss[0];
6114                 if (!(hapd->conf->p2p & P2P_GROUP_OWNER)) {
6115                         wpabuf_free(beacon_ies);
6116                         wpabuf_free(proberesp_ies);
6117                         return;
6118                 }
6119                 if (beacon_ies) {
6120                         wpabuf_free(hapd->p2p_beacon_ie);
6121                         hapd->p2p_beacon_ie = beacon_ies;
6122                 }
6123                 wpabuf_free(hapd->p2p_probe_resp_ie);
6124                 hapd->p2p_probe_resp_ie = proberesp_ies;
6125         } else {
6126                 wpabuf_free(beacon_ies);
6127                 wpabuf_free(proberesp_ies);
6128         }
6129         wpa_supplicant_ap_update_beacon(wpa_s);
6130 }
6131
6132
6133 static void wpas_p2p_idle_update(void *ctx, int idle)
6134 {
6135         struct wpa_supplicant *wpa_s = ctx;
6136         if (!wpa_s->ap_iface)
6137                 return;
6138         wpa_printf(MSG_DEBUG, "P2P: GO - group %sidle", idle ? "" : "not ");
6139         if (idle) {
6140                 if (wpa_s->global->p2p_fail_on_wps_complete &&
6141                     wpa_s->p2p_in_provisioning) {
6142                         wpas_p2p_grpform_fail_after_wps(wpa_s);
6143                         return;
6144                 }
6145                 wpas_p2p_set_group_idle_timeout(wpa_s);
6146         } else
6147                 eloop_cancel_timeout(wpas_p2p_group_idle_timeout, wpa_s, NULL);
6148 }
6149
6150
6151 struct p2p_group * wpas_p2p_group_init(struct wpa_supplicant *wpa_s,
6152                                        struct wpa_ssid *ssid)
6153 {
6154         struct p2p_group *group;
6155         struct p2p_group_config *cfg;
6156
6157         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6158                 return NULL;
6159
6160         cfg = os_zalloc(sizeof(*cfg));
6161         if (cfg == NULL)
6162                 return NULL;
6163
6164         if (ssid->p2p_persistent_group && wpa_s->conf->persistent_reconnect)
6165                 cfg->persistent_group = 2;
6166         else if (ssid->p2p_persistent_group)
6167                 cfg->persistent_group = 1;
6168         os_memcpy(cfg->interface_addr, wpa_s->own_addr, ETH_ALEN);
6169         if (wpa_s->max_stations &&
6170             wpa_s->max_stations < wpa_s->conf->max_num_sta)
6171                 cfg->max_clients = wpa_s->max_stations;
6172         else
6173                 cfg->max_clients = wpa_s->conf->max_num_sta;
6174         os_memcpy(cfg->ssid, ssid->ssid, ssid->ssid_len);
6175         cfg->ssid_len = ssid->ssid_len;
6176         cfg->freq = ssid->frequency;
6177         cfg->cb_ctx = wpa_s;
6178         cfg->ie_update = wpas_p2p_ie_update;
6179         cfg->idle_update = wpas_p2p_idle_update;
6180
6181         group = p2p_group_init(wpa_s->global->p2p, cfg);
6182         if (group == NULL)
6183                 os_free(cfg);
6184         if (ssid->mode != WPAS_MODE_P2P_GROUP_FORMATION)
6185                 p2p_group_notif_formation_done(group);
6186         wpa_s->p2p_group = group;
6187         return group;
6188 }
6189
6190
6191 void wpas_p2p_wps_success(struct wpa_supplicant *wpa_s, const u8 *peer_addr,
6192                           int registrar)
6193 {
6194         struct wpa_ssid *ssid = wpa_s->current_ssid;
6195
6196         if (!wpa_s->p2p_in_provisioning) {
6197                 wpa_printf(MSG_DEBUG, "P2P: Ignore WPS success event - P2P "
6198                            "provisioning not in progress");
6199                 return;
6200         }
6201
6202         if (ssid && ssid->mode == WPAS_MODE_INFRA) {
6203                 u8 go_dev_addr[ETH_ALEN];
6204                 os_memcpy(go_dev_addr, wpa_s->bssid, ETH_ALEN);
6205                 wpas_p2p_persistent_group(wpa_s, go_dev_addr, ssid->ssid,
6206                                           ssid->ssid_len);
6207                 /* Clear any stored provisioning info */
6208                 p2p_clear_provisioning_info(wpa_s->global->p2p, go_dev_addr);
6209         }
6210
6211         eloop_cancel_timeout(wpas_p2p_group_formation_timeout, wpa_s->parent,
6212                              NULL);
6213         wpa_s->p2p_go_group_formation_completed = 1;
6214         if (ssid && ssid->mode == WPAS_MODE_INFRA) {
6215                 /*
6216                  * Use a separate timeout for initial data connection to
6217                  * complete to allow the group to be removed automatically if
6218                  * something goes wrong in this step before the P2P group idle
6219                  * timeout mechanism is taken into use.
6220                  */
6221                 wpa_dbg(wpa_s, MSG_DEBUG,
6222                         "P2P: Re-start group formation timeout (%d seconds) as client for initial connection",
6223                         P2P_MAX_INITIAL_CONN_WAIT);
6224                 eloop_register_timeout(P2P_MAX_INITIAL_CONN_WAIT, 0,
6225                                        wpas_p2p_group_formation_timeout,
6226                                        wpa_s->parent, NULL);
6227         } else if (ssid) {
6228                 /*
6229                  * Use a separate timeout for initial data connection to
6230                  * complete to allow the group to be removed automatically if
6231                  * the client does not complete data connection successfully.
6232                  */
6233                 wpa_dbg(wpa_s, MSG_DEBUG,
6234                         "P2P: Re-start group formation timeout (%d seconds) as GO for initial connection",
6235                         P2P_MAX_INITIAL_CONN_WAIT_GO);
6236                 eloop_register_timeout(P2P_MAX_INITIAL_CONN_WAIT_GO, 0,
6237                                        wpas_p2p_group_formation_timeout,
6238                                        wpa_s->parent, NULL);
6239                 /*
6240                  * Complete group formation on first successful data connection
6241                  */
6242                 wpa_s->p2p_go_group_formation_completed = 0;
6243         }
6244         if (wpa_s->global->p2p)
6245                 p2p_wps_success_cb(wpa_s->global->p2p, peer_addr);
6246         wpas_group_formation_completed(wpa_s, 1);
6247 }
6248
6249
6250 void wpas_p2p_wps_failed(struct wpa_supplicant *wpa_s,
6251                          struct wps_event_fail *fail)
6252 {
6253         if (!wpa_s->p2p_in_provisioning) {
6254                 wpa_printf(MSG_DEBUG, "P2P: Ignore WPS fail event - P2P "
6255                            "provisioning not in progress");
6256                 return;
6257         }
6258
6259         if (wpa_s->go_params) {
6260                 p2p_clear_provisioning_info(
6261                         wpa_s->global->p2p,
6262                         wpa_s->go_params->peer_device_addr);
6263         }
6264
6265         wpas_notify_p2p_wps_failed(wpa_s, fail);
6266
6267         if (wpa_s == wpa_s->global->p2p_group_formation) {
6268                 /*
6269                  * Allow some time for the failed WPS negotiation exchange to
6270                  * complete, but remove the group since group formation cannot
6271                  * succeed after provisioning failure.
6272                  */
6273                 wpa_printf(MSG_DEBUG, "P2P: WPS step failed during group formation - reject connection from timeout");
6274                 wpa_s->global->p2p_fail_on_wps_complete = 1;
6275                 eloop_deplete_timeout(0, 50000,
6276                                       wpas_p2p_group_formation_timeout,
6277                                       wpa_s->parent, NULL);
6278         }
6279 }
6280
6281
6282 int wpas_p2p_wps_eapol_cb(struct wpa_supplicant *wpa_s)
6283 {
6284         if (!wpa_s->global->p2p_fail_on_wps_complete ||
6285             !wpa_s->p2p_in_provisioning)
6286                 return 0;
6287
6288         wpas_p2p_grpform_fail_after_wps(wpa_s);
6289
6290         return 1;
6291 }
6292
6293
6294 int wpas_p2p_prov_disc(struct wpa_supplicant *wpa_s, const u8 *peer_addr,
6295                        const char *config_method,
6296                        enum wpas_p2p_prov_disc_use use)
6297 {
6298         u16 config_methods;
6299
6300         wpa_s->p2p_fallback_to_go_neg = 0;
6301         wpa_s->pending_pd_use = NORMAL_PD;
6302         if (os_strncmp(config_method, "display", 7) == 0)
6303                 config_methods = WPS_CONFIG_DISPLAY;
6304         else if (os_strncmp(config_method, "keypad", 6) == 0)
6305                 config_methods = WPS_CONFIG_KEYPAD;
6306         else if (os_strncmp(config_method, "pbc", 3) == 0 ||
6307                  os_strncmp(config_method, "pushbutton", 10) == 0)
6308                 config_methods = WPS_CONFIG_PUSHBUTTON;
6309         else {
6310                 wpa_printf(MSG_DEBUG, "P2P: Unknown config method");
6311                 return -1;
6312         }
6313
6314         if (use == WPAS_P2P_PD_AUTO) {
6315                 os_memcpy(wpa_s->pending_join_dev_addr, peer_addr, ETH_ALEN);
6316                 wpa_s->pending_pd_config_methods = config_methods;
6317                 wpa_s->p2p_auto_pd = 1;
6318                 wpa_s->p2p_auto_join = 0;
6319                 wpa_s->pending_pd_before_join = 0;
6320                 wpa_s->auto_pd_scan_retry = 0;
6321                 wpas_p2p_stop_find(wpa_s);
6322                 wpa_s->p2p_join_scan_count = 0;
6323                 os_get_reltime(&wpa_s->p2p_auto_started);
6324                 wpa_printf(MSG_DEBUG, "P2P: Auto PD started at %ld.%06ld",
6325                            wpa_s->p2p_auto_started.sec,
6326                            wpa_s->p2p_auto_started.usec);
6327                 wpas_p2p_join_scan(wpa_s, NULL);
6328                 return 0;
6329         }
6330
6331         if (wpa_s->global->p2p == NULL || wpa_s->global->p2p_disabled)
6332                 return -1;
6333
6334         return p2p_prov_disc_req(wpa_s->global->p2p, peer_addr, NULL,
6335                                  config_methods, use == WPAS_P2P_PD_FOR_JOIN,
6336                                  0, 1);
6337 }
6338
6339
6340 int wpas_p2p_scan_result_text(const u8 *ies, size_t ies_len, char *buf,
6341                               char *end)
6342 {
6343         return p2p_scan_result_text(ies, ies_len, buf, end);
6344 }
6345
6346
6347 static void wpas_p2p_clear_pending_action_tx(struct wpa_supplicant *wpa_s)
6348 {
6349         if (!offchannel_pending_action_tx(wpa_s))
6350                 return;
6351
6352         wpas_p2p_action_tx_clear(wpa_s);
6353
6354         wpa_printf(MSG_DEBUG, "P2P: Drop pending Action TX due to new "
6355                    "operation request");
6356         offchannel_clear_pending_action_tx(wpa_s);
6357 }
6358
6359
6360 int wpas_p2p_find(struct wpa_supplicant *wpa_s, unsigned int timeout,
6361                   enum p2p_discovery_type type,
6362                   unsigned int num_req_dev_types, const u8 *req_dev_types,
6363                   const u8 *dev_id, unsigned int search_delay,
6364                   u8 seek_cnt, const char **seek_string)
6365 {
6366         wpas_p2p_clear_pending_action_tx(wpa_s);
6367         wpa_s->p2p_long_listen = 0;
6368
6369         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL ||
6370             wpa_s->p2p_in_provisioning)
6371                 return -1;
6372
6373         wpa_supplicant_cancel_sched_scan(wpa_s);
6374
6375         return p2p_find(wpa_s->global->p2p, timeout, type,
6376                         num_req_dev_types, req_dev_types, dev_id,
6377                         search_delay, seek_cnt, seek_string);
6378 }
6379
6380
6381 static void wpas_p2p_scan_res_ignore_search(struct wpa_supplicant *wpa_s,
6382                                             struct wpa_scan_results *scan_res)
6383 {
6384         wpa_printf(MSG_DEBUG, "P2P: Ignore scan results");
6385
6386         if (wpa_s->p2p_scan_work) {
6387                 struct wpa_radio_work *work = wpa_s->p2p_scan_work;
6388                 wpa_s->p2p_scan_work = NULL;
6389                 radio_work_done(work);
6390         }
6391
6392         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6393                 return;
6394
6395         /*
6396          * Indicate that results have been processed so that the P2P module can
6397          * continue pending tasks.
6398          */
6399         p2p_scan_res_handled(wpa_s->global->p2p);
6400 }
6401
6402
6403 static void wpas_p2p_stop_find_oper(struct wpa_supplicant *wpa_s)
6404 {
6405         wpas_p2p_clear_pending_action_tx(wpa_s);
6406         wpa_s->p2p_long_listen = 0;
6407         eloop_cancel_timeout(wpas_p2p_long_listen_timeout, wpa_s, NULL);
6408         eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
6409
6410         if (wpa_s->global->p2p)
6411                 p2p_stop_find(wpa_s->global->p2p);
6412
6413         if (wpa_s->scan_res_handler == wpas_p2p_scan_res_handler) {
6414                 wpa_printf(MSG_DEBUG,
6415                            "P2P: Do not consider the scan results after stop_find");
6416                 wpa_s->scan_res_handler = wpas_p2p_scan_res_ignore_search;
6417         }
6418 }
6419
6420
6421 void wpas_p2p_stop_find(struct wpa_supplicant *wpa_s)
6422 {
6423         wpas_p2p_stop_find_oper(wpa_s);
6424         wpas_p2p_remove_pending_group_interface(wpa_s);
6425 }
6426
6427
6428 static void wpas_p2p_long_listen_timeout(void *eloop_ctx, void *timeout_ctx)
6429 {
6430         struct wpa_supplicant *wpa_s = eloop_ctx;
6431         wpa_s->p2p_long_listen = 0;
6432 }
6433
6434
6435 int wpas_p2p_listen(struct wpa_supplicant *wpa_s, unsigned int timeout)
6436 {
6437         int res;
6438
6439         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6440                 return -1;
6441
6442         wpa_supplicant_cancel_sched_scan(wpa_s);
6443         wpas_p2p_clear_pending_action_tx(wpa_s);
6444
6445         if (timeout == 0) {
6446                 /*
6447                  * This is a request for unlimited Listen state. However, at
6448                  * least for now, this is mapped to a Listen state for one
6449                  * hour.
6450                  */
6451                 timeout = 3600;
6452         }
6453         eloop_cancel_timeout(wpas_p2p_long_listen_timeout, wpa_s, NULL);
6454         wpa_s->p2p_long_listen = 0;
6455
6456         /*
6457          * Stop previous find/listen operation to avoid trying to request a new
6458          * remain-on-channel operation while the driver is still running the
6459          * previous one.
6460          */
6461         if (wpa_s->global->p2p)
6462                 p2p_stop_find(wpa_s->global->p2p);
6463
6464         res = wpas_p2p_listen_start(wpa_s, timeout * 1000);
6465         if (res == 0 && timeout * 1000 > wpa_s->max_remain_on_chan) {
6466                 wpa_s->p2p_long_listen = timeout * 1000;
6467                 eloop_register_timeout(timeout, 0,
6468                                        wpas_p2p_long_listen_timeout,
6469                                        wpa_s, NULL);
6470         }
6471
6472         return res;
6473 }
6474
6475
6476 int wpas_p2p_assoc_req_ie(struct wpa_supplicant *wpa_s, struct wpa_bss *bss,
6477                           u8 *buf, size_t len, int p2p_group)
6478 {
6479         struct wpabuf *p2p_ie;
6480         int ret;
6481
6482         if (wpa_s->global->p2p_disabled)
6483                 return -1;
6484         if (wpa_s->conf->p2p_disabled)
6485                 return -1;
6486         if (wpa_s->global->p2p == NULL)
6487                 return -1;
6488         if (bss == NULL)
6489                 return -1;
6490
6491         p2p_ie = wpa_bss_get_vendor_ie_multi(bss, P2P_IE_VENDOR_TYPE);
6492         ret = p2p_assoc_req_ie(wpa_s->global->p2p, bss->bssid, buf, len,
6493                                p2p_group, p2p_ie);
6494         wpabuf_free(p2p_ie);
6495
6496         return ret;
6497 }
6498
6499
6500 int wpas_p2p_probe_req_rx(struct wpa_supplicant *wpa_s, const u8 *addr,
6501                           const u8 *dst, const u8 *bssid,
6502                           const u8 *ie, size_t ie_len, int ssi_signal)
6503 {
6504         if (wpa_s->global->p2p_disabled)
6505                 return 0;
6506         if (wpa_s->global->p2p == NULL)
6507                 return 0;
6508
6509         switch (p2p_probe_req_rx(wpa_s->global->p2p, addr, dst, bssid,
6510                                  ie, ie_len)) {
6511         case P2P_PREQ_NOT_P2P:
6512                 wpas_notify_preq(wpa_s, addr, dst, bssid, ie, ie_len,
6513                                  ssi_signal);
6514                 /* fall through */
6515         case P2P_PREQ_MALFORMED:
6516         case P2P_PREQ_NOT_LISTEN:
6517         case P2P_PREQ_NOT_PROCESSED:
6518         default: /* make gcc happy */
6519                 return 0;
6520         case P2P_PREQ_PROCESSED:
6521                 return 1;
6522         }
6523 }
6524
6525
6526 void wpas_p2p_rx_action(struct wpa_supplicant *wpa_s, const u8 *da,
6527                         const u8 *sa, const u8 *bssid,
6528                         u8 category, const u8 *data, size_t len, int freq)
6529 {
6530         if (wpa_s->global->p2p_disabled)
6531                 return;
6532         if (wpa_s->global->p2p == NULL)
6533                 return;
6534
6535         p2p_rx_action(wpa_s->global->p2p, da, sa, bssid, category, data, len,
6536                       freq);
6537 }
6538
6539
6540 void wpas_p2p_scan_ie(struct wpa_supplicant *wpa_s, struct wpabuf *ies)
6541 {
6542         if (wpa_s->global->p2p_disabled)
6543                 return;
6544         if (wpa_s->global->p2p == NULL)
6545                 return;
6546
6547         p2p_scan_ie(wpa_s->global->p2p, ies, NULL);
6548 }
6549
6550
6551 static void wpas_p2p_group_deinit(struct wpa_supplicant *wpa_s)
6552 {
6553         p2p_group_deinit(wpa_s->p2p_group);
6554         wpa_s->p2p_group = NULL;
6555
6556         wpa_s->ap_configured_cb = NULL;
6557         wpa_s->ap_configured_cb_ctx = NULL;
6558         wpa_s->ap_configured_cb_data = NULL;
6559         wpa_s->connect_without_scan = NULL;
6560 }
6561
6562
6563 int wpas_p2p_reject(struct wpa_supplicant *wpa_s, const u8 *addr)
6564 {
6565         wpa_s->p2p_long_listen = 0;
6566
6567         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6568                 return -1;
6569
6570         return p2p_reject(wpa_s->global->p2p, addr);
6571 }
6572
6573
6574 /* Invite to reinvoke a persistent group */
6575 int wpas_p2p_invite(struct wpa_supplicant *wpa_s, const u8 *peer_addr,
6576                     struct wpa_ssid *ssid, const u8 *go_dev_addr, int freq,
6577                     int ht40, int vht, int pref_freq)
6578 {
6579         enum p2p_invite_role role;
6580         u8 *bssid = NULL;
6581         int force_freq = 0;
6582         int res;
6583         int no_pref_freq_given = pref_freq == 0;
6584
6585         wpa_s->global->p2p_invite_group = NULL;
6586         if (peer_addr)
6587                 os_memcpy(wpa_s->p2p_auth_invite, peer_addr, ETH_ALEN);
6588         else
6589                 os_memset(wpa_s->p2p_auth_invite, 0, ETH_ALEN);
6590
6591         wpa_s->p2p_persistent_go_freq = freq;
6592         wpa_s->p2p_go_ht40 = !!ht40;
6593         if (ssid->mode == WPAS_MODE_P2P_GO) {
6594                 role = P2P_INVITE_ROLE_GO;
6595                 if (peer_addr == NULL) {
6596                         wpa_printf(MSG_DEBUG, "P2P: Missing peer "
6597                                    "address in invitation command");
6598                         return -1;
6599                 }
6600                 if (wpas_p2p_create_iface(wpa_s)) {
6601                         if (wpas_p2p_add_group_interface(wpa_s,
6602                                                          WPA_IF_P2P_GO) < 0) {
6603                                 wpa_printf(MSG_ERROR, "P2P: Failed to "
6604                                            "allocate a new interface for the "
6605                                            "group");
6606                                 return -1;
6607                         }
6608                         bssid = wpa_s->pending_interface_addr;
6609                 } else
6610                         bssid = wpa_s->own_addr;
6611         } else {
6612                 role = P2P_INVITE_ROLE_CLIENT;
6613                 peer_addr = ssid->bssid;
6614         }
6615         wpa_s->pending_invite_ssid_id = ssid->id;
6616
6617         res = wpas_p2p_setup_freqs(wpa_s, freq, &force_freq, &pref_freq,
6618                                    role == P2P_INVITE_ROLE_GO);
6619         if (res)
6620                 return res;
6621
6622         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6623                 return -1;
6624
6625         if (wpa_s->parent->conf->p2p_ignore_shared_freq &&
6626             no_pref_freq_given && pref_freq > 0 &&
6627             wpa_s->num_multichan_concurrent > 1 &&
6628             wpas_p2p_num_unused_channels(wpa_s) > 0) {
6629                 wpa_printf(MSG_DEBUG, "P2P: Ignore own channel preference %d MHz for invitation due to p2p_ignore_shared_freq=1 configuration",
6630                            pref_freq);
6631                 pref_freq = 0;
6632         }
6633
6634         /*
6635          * Stop any find/listen operations before invitation and possibly
6636          * connection establishment.
6637          */
6638         wpas_p2p_stop_find_oper(wpa_s);
6639
6640         return p2p_invite(wpa_s->global->p2p, peer_addr, role, bssid,
6641                           ssid->ssid, ssid->ssid_len, force_freq, go_dev_addr,
6642                           1, pref_freq, -1);
6643 }
6644
6645
6646 /* Invite to join an active group */
6647 int wpas_p2p_invite_group(struct wpa_supplicant *wpa_s, const char *ifname,
6648                           const u8 *peer_addr, const u8 *go_dev_addr)
6649 {
6650         struct wpa_global *global = wpa_s->global;
6651         enum p2p_invite_role role;
6652         u8 *bssid = NULL;
6653         struct wpa_ssid *ssid;
6654         int persistent;
6655         int freq = 0, force_freq = 0, pref_freq = 0;
6656         int res;
6657
6658         wpa_s->p2p_persistent_go_freq = 0;
6659         wpa_s->p2p_go_ht40 = 0;
6660         wpa_s->p2p_go_vht = 0;
6661
6662         for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) {
6663                 if (os_strcmp(wpa_s->ifname, ifname) == 0)
6664                         break;
6665         }
6666         if (wpa_s == NULL) {
6667                 wpa_printf(MSG_DEBUG, "P2P: Interface '%s' not found", ifname);
6668                 return -1;
6669         }
6670
6671         ssid = wpa_s->current_ssid;
6672         if (ssid == NULL) {
6673                 wpa_printf(MSG_DEBUG, "P2P: No current SSID to use for "
6674                            "invitation");
6675                 return -1;
6676         }
6677
6678         wpa_s->global->p2p_invite_group = wpa_s;
6679         persistent = ssid->p2p_persistent_group &&
6680                 wpas_p2p_get_persistent(wpa_s->parent, peer_addr,
6681                                         ssid->ssid, ssid->ssid_len);
6682
6683         if (ssid->mode == WPAS_MODE_P2P_GO) {
6684                 role = P2P_INVITE_ROLE_ACTIVE_GO;
6685                 bssid = wpa_s->own_addr;
6686                 if (go_dev_addr == NULL)
6687                         go_dev_addr = wpa_s->global->p2p_dev_addr;
6688                 freq = ssid->frequency;
6689         } else {
6690                 role = P2P_INVITE_ROLE_CLIENT;
6691                 if (wpa_s->wpa_state < WPA_ASSOCIATED) {
6692                         wpa_printf(MSG_DEBUG, "P2P: Not associated - cannot "
6693                                    "invite to current group");
6694                         return -1;
6695                 }
6696                 bssid = wpa_s->bssid;
6697                 if (go_dev_addr == NULL &&
6698                     !is_zero_ether_addr(wpa_s->go_dev_addr))
6699                         go_dev_addr = wpa_s->go_dev_addr;
6700                 freq = wpa_s->current_bss ? wpa_s->current_bss->freq :
6701                         (int) wpa_s->assoc_freq;
6702         }
6703         wpa_s->parent->pending_invite_ssid_id = -1;
6704
6705         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6706                 return -1;
6707
6708         res = wpas_p2p_setup_freqs(wpa_s, freq, &force_freq, &pref_freq,
6709                                    role == P2P_INVITE_ROLE_ACTIVE_GO);
6710         if (res)
6711                 return res;
6712         wpas_p2p_set_own_freq_preference(wpa_s, force_freq);
6713
6714         return p2p_invite(wpa_s->global->p2p, peer_addr, role, bssid,
6715                           ssid->ssid, ssid->ssid_len, force_freq,
6716                           go_dev_addr, persistent, pref_freq, -1);
6717 }
6718
6719
6720 void wpas_p2p_completed(struct wpa_supplicant *wpa_s)
6721 {
6722         struct wpa_ssid *ssid = wpa_s->current_ssid;
6723         u8 go_dev_addr[ETH_ALEN];
6724         int network_id = -1;
6725         int persistent;
6726         int freq;
6727         u8 ip[3 * 4];
6728         char ip_addr[100];
6729
6730         if (ssid == NULL || ssid->mode != WPAS_MODE_P2P_GROUP_FORMATION) {
6731                 eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
6732                                      wpa_s->parent, NULL);
6733         }
6734
6735         if (!wpa_s->show_group_started || !ssid)
6736                 return;
6737
6738         wpa_s->show_group_started = 0;
6739
6740         os_memset(go_dev_addr, 0, ETH_ALEN);
6741         if (ssid->bssid_set)
6742                 os_memcpy(go_dev_addr, ssid->bssid, ETH_ALEN);
6743         persistent = wpas_p2p_persistent_group(wpa_s, go_dev_addr, ssid->ssid,
6744                                                ssid->ssid_len);
6745         os_memcpy(wpa_s->go_dev_addr, go_dev_addr, ETH_ALEN);
6746
6747         if (wpa_s->global->p2p_group_formation == wpa_s)
6748                 wpa_s->global->p2p_group_formation = NULL;
6749
6750         freq = wpa_s->current_bss ? wpa_s->current_bss->freq :
6751                 (int) wpa_s->assoc_freq;
6752
6753         ip_addr[0] = '\0';
6754         if (wpa_sm_get_p2p_ip_addr(wpa_s->wpa, ip) == 0) {
6755                 int res;
6756
6757                 res = os_snprintf(ip_addr, sizeof(ip_addr),
6758                                   " ip_addr=%u.%u.%u.%u "
6759                                   "ip_mask=%u.%u.%u.%u go_ip_addr=%u.%u.%u.%u",
6760                                   ip[0], ip[1], ip[2], ip[3],
6761                                   ip[4], ip[5], ip[6], ip[7],
6762                                   ip[8], ip[9], ip[10], ip[11]);
6763                 if (os_snprintf_error(sizeof(ip_addr), res))
6764                         ip_addr[0] = '\0';
6765         }
6766
6767         wpas_p2p_group_started(wpa_s, 0, ssid, freq,
6768                                ssid->passphrase == NULL && ssid->psk_set ?
6769                                ssid->psk : NULL,
6770                                ssid->passphrase, go_dev_addr, persistent,
6771                                ip_addr);
6772
6773         if (persistent)
6774                 network_id = wpas_p2p_store_persistent_group(wpa_s->parent,
6775                                                              ssid, go_dev_addr);
6776         if (network_id < 0)
6777                 network_id = ssid->id;
6778         wpas_notify_p2p_group_started(wpa_s, ssid, network_id, 1);
6779 }
6780
6781
6782 int wpas_p2p_presence_req(struct wpa_supplicant *wpa_s, u32 duration1,
6783                           u32 interval1, u32 duration2, u32 interval2)
6784 {
6785         int ret;
6786
6787         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6788                 return -1;
6789
6790         if (wpa_s->wpa_state < WPA_ASSOCIATED ||
6791             wpa_s->current_ssid == NULL ||
6792             wpa_s->current_ssid->mode != WPAS_MODE_INFRA)
6793                 return -1;
6794
6795         ret = p2p_presence_req(wpa_s->global->p2p, wpa_s->bssid,
6796                                wpa_s->own_addr, wpa_s->assoc_freq,
6797                                duration1, interval1, duration2, interval2);
6798         if (ret == 0)
6799                 wpa_s->waiting_presence_resp = 1;
6800
6801         return ret;
6802 }
6803
6804
6805 int wpas_p2p_ext_listen(struct wpa_supplicant *wpa_s, unsigned int period,
6806                         unsigned int interval)
6807 {
6808         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6809                 return -1;
6810
6811         return p2p_ext_listen(wpa_s->global->p2p, period, interval);
6812 }
6813
6814
6815 static int wpas_p2p_is_client(struct wpa_supplicant *wpa_s)
6816 {
6817         if (wpa_s->current_ssid == NULL) {
6818                 /*
6819                  * current_ssid can be cleared when P2P client interface gets
6820                  * disconnected, so assume this interface was used as P2P
6821                  * client.
6822                  */
6823                 return 1;
6824         }
6825         return wpa_s->current_ssid->p2p_group &&
6826                 wpa_s->current_ssid->mode == WPAS_MODE_INFRA;
6827 }
6828
6829
6830 static void wpas_p2p_group_idle_timeout(void *eloop_ctx, void *timeout_ctx)
6831 {
6832         struct wpa_supplicant *wpa_s = eloop_ctx;
6833
6834         if (wpa_s->conf->p2p_group_idle == 0 && !wpas_p2p_is_client(wpa_s)) {
6835                 wpa_printf(MSG_DEBUG, "P2P: Ignore group idle timeout - "
6836                            "disabled");
6837                 return;
6838         }
6839
6840         wpa_printf(MSG_DEBUG, "P2P: Group idle timeout reached - terminate "
6841                    "group");
6842         wpas_p2p_group_delete(wpa_s, P2P_GROUP_REMOVAL_IDLE_TIMEOUT);
6843 }
6844
6845
6846 static void wpas_p2p_set_group_idle_timeout(struct wpa_supplicant *wpa_s)
6847 {
6848         int timeout;
6849
6850         if (eloop_cancel_timeout(wpas_p2p_group_idle_timeout, wpa_s, NULL) > 0)
6851                 wpa_printf(MSG_DEBUG, "P2P: Cancelled P2P group idle timeout");
6852
6853         if (wpa_s->current_ssid == NULL || !wpa_s->current_ssid->p2p_group)
6854                 return;
6855
6856         timeout = wpa_s->conf->p2p_group_idle;
6857         if (wpa_s->current_ssid->mode == WPAS_MODE_INFRA &&
6858             (timeout == 0 || timeout > P2P_MAX_CLIENT_IDLE))
6859             timeout = P2P_MAX_CLIENT_IDLE;
6860
6861         if (timeout == 0)
6862                 return;
6863
6864         if (timeout < 0) {
6865                 if (wpa_s->current_ssid->mode == WPAS_MODE_INFRA)
6866                         timeout = 0; /* special client mode no-timeout */
6867                 else
6868                         return;
6869         }
6870
6871         if (wpa_s->p2p_in_provisioning) {
6872                 /*
6873                  * Use the normal group formation timeout during the
6874                  * provisioning phase to avoid terminating this process too
6875                  * early due to group idle timeout.
6876                  */
6877                 wpa_printf(MSG_DEBUG, "P2P: Do not use P2P group idle timeout "
6878                            "during provisioning");
6879                 return;
6880         }
6881
6882         if (wpa_s->show_group_started) {
6883                 /*
6884                  * Use the normal group formation timeout between the end of
6885                  * the provisioning phase and completion of 4-way handshake to
6886                  * avoid terminating this process too early due to group idle
6887                  * timeout.
6888                  */
6889                 wpa_printf(MSG_DEBUG, "P2P: Do not use P2P group idle timeout "
6890                            "while waiting for initial 4-way handshake to "
6891                            "complete");
6892                 return;
6893         }
6894
6895         wpa_printf(MSG_DEBUG, "P2P: Set P2P group idle timeout to %u seconds",
6896                    timeout);
6897         eloop_register_timeout(timeout, 0, wpas_p2p_group_idle_timeout,
6898                                wpa_s, NULL);
6899 }
6900
6901
6902 /* Returns 1 if the interface was removed */
6903 int wpas_p2p_deauth_notif(struct wpa_supplicant *wpa_s, const u8 *bssid,
6904                           u16 reason_code, const u8 *ie, size_t ie_len,
6905                           int locally_generated)
6906 {
6907         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6908                 return 0;
6909
6910         if (!locally_generated)
6911                 p2p_deauth_notif(wpa_s->global->p2p, bssid, reason_code, ie,
6912                                  ie_len);
6913
6914         if (reason_code == WLAN_REASON_DEAUTH_LEAVING && !locally_generated &&
6915             wpa_s->current_ssid &&
6916             wpa_s->current_ssid->p2p_group &&
6917             wpa_s->current_ssid->mode == WPAS_MODE_INFRA) {
6918                 wpa_printf(MSG_DEBUG, "P2P: GO indicated that the P2P Group "
6919                            "session is ending");
6920                 if (wpas_p2p_group_delete(wpa_s,
6921                                           P2P_GROUP_REMOVAL_GO_ENDING_SESSION)
6922                     > 0)
6923                         return 1;
6924         }
6925
6926         return 0;
6927 }
6928
6929
6930 void wpas_p2p_disassoc_notif(struct wpa_supplicant *wpa_s, const u8 *bssid,
6931                              u16 reason_code, const u8 *ie, size_t ie_len,
6932                              int locally_generated)
6933 {
6934         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6935                 return;
6936
6937         if (!locally_generated)
6938                 p2p_disassoc_notif(wpa_s->global->p2p, bssid, reason_code, ie,
6939                                    ie_len);
6940 }
6941
6942
6943 void wpas_p2p_update_config(struct wpa_supplicant *wpa_s)
6944 {
6945         struct p2p_data *p2p = wpa_s->global->p2p;
6946
6947         if (p2p == NULL)
6948                 return;
6949
6950         if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_CAPABLE))
6951                 return;
6952
6953         if (wpa_s->conf->changed_parameters & CFG_CHANGED_DEVICE_NAME)
6954                 p2p_set_dev_name(p2p, wpa_s->conf->device_name);
6955
6956         if (wpa_s->conf->changed_parameters & CFG_CHANGED_DEVICE_TYPE)
6957                 p2p_set_pri_dev_type(p2p, wpa_s->conf->device_type);
6958
6959         if (wpa_s->wps &&
6960             (wpa_s->conf->changed_parameters & CFG_CHANGED_CONFIG_METHODS))
6961                 p2p_set_config_methods(p2p, wpa_s->wps->config_methods);
6962
6963         if (wpa_s->wps && (wpa_s->conf->changed_parameters & CFG_CHANGED_UUID))
6964                 p2p_set_uuid(p2p, wpa_s->wps->uuid);
6965
6966         if (wpa_s->conf->changed_parameters & CFG_CHANGED_WPS_STRING) {
6967                 p2p_set_manufacturer(p2p, wpa_s->conf->manufacturer);
6968                 p2p_set_model_name(p2p, wpa_s->conf->model_name);
6969                 p2p_set_model_number(p2p, wpa_s->conf->model_number);
6970                 p2p_set_serial_number(p2p, wpa_s->conf->serial_number);
6971         }
6972
6973         if (wpa_s->conf->changed_parameters & CFG_CHANGED_SEC_DEVICE_TYPE)
6974                 p2p_set_sec_dev_types(p2p,
6975                                       (void *) wpa_s->conf->sec_device_type,
6976                                       wpa_s->conf->num_sec_device_types);
6977
6978         if (wpa_s->conf->changed_parameters & CFG_CHANGED_VENDOR_EXTENSION) {
6979                 int i;
6980                 p2p_remove_wps_vendor_extensions(p2p);
6981                 for (i = 0; i < MAX_WPS_VENDOR_EXT; i++) {
6982                         if (wpa_s->conf->wps_vendor_ext[i] == NULL)
6983                                 continue;
6984                         p2p_add_wps_vendor_extension(
6985                                 p2p, wpa_s->conf->wps_vendor_ext[i]);
6986                 }
6987         }
6988
6989         if ((wpa_s->conf->changed_parameters & CFG_CHANGED_COUNTRY) &&
6990             wpa_s->conf->country[0] && wpa_s->conf->country[1]) {
6991                 char country[3];
6992                 country[0] = wpa_s->conf->country[0];
6993                 country[1] = wpa_s->conf->country[1];
6994                 country[2] = 0x04;
6995                 p2p_set_country(p2p, country);
6996         }
6997
6998         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_SSID_POSTFIX) {
6999                 p2p_set_ssid_postfix(p2p, (u8 *) wpa_s->conf->p2p_ssid_postfix,
7000                                      wpa_s->conf->p2p_ssid_postfix ?
7001                                      os_strlen(wpa_s->conf->p2p_ssid_postfix) :
7002                                      0);
7003         }
7004
7005         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_INTRA_BSS)
7006                 p2p_set_intra_bss_dist(p2p, wpa_s->conf->p2p_intra_bss);
7007
7008         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_LISTEN_CHANNEL) {
7009                 u8 reg_class, channel;
7010                 int ret;
7011                 unsigned int r;
7012                 u8 channel_forced;
7013
7014                 if (wpa_s->conf->p2p_listen_reg_class &&
7015                     wpa_s->conf->p2p_listen_channel) {
7016                         reg_class = wpa_s->conf->p2p_listen_reg_class;
7017                         channel = wpa_s->conf->p2p_listen_channel;
7018                         channel_forced = 1;
7019                 } else {
7020                         reg_class = 81;
7021                         /*
7022                          * Pick one of the social channels randomly as the
7023                          * listen channel.
7024                          */
7025                         if (os_get_random((u8 *) &r, sizeof(r)) < 0)
7026                                 channel = 1;
7027                         else
7028                                 channel = 1 + (r % 3) * 5;
7029                         channel_forced = 0;
7030                 }
7031                 ret = p2p_set_listen_channel(p2p, reg_class, channel,
7032                                              channel_forced);
7033                 if (ret)
7034                         wpa_printf(MSG_ERROR, "P2P: Own listen channel update "
7035                                    "failed: %d", ret);
7036         }
7037         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_OPER_CHANNEL) {
7038                 u8 op_reg_class, op_channel, cfg_op_channel;
7039                 int ret = 0;
7040                 unsigned int r;
7041                 if (wpa_s->conf->p2p_oper_reg_class &&
7042                     wpa_s->conf->p2p_oper_channel) {
7043                         op_reg_class = wpa_s->conf->p2p_oper_reg_class;
7044                         op_channel = wpa_s->conf->p2p_oper_channel;
7045                         cfg_op_channel = 1;
7046                 } else {
7047                         op_reg_class = 81;
7048                         /*
7049                          * Use random operation channel from (1, 6, 11)
7050                          *if no other preference is indicated.
7051                          */
7052                         if (os_get_random((u8 *) &r, sizeof(r)) < 0)
7053                                 op_channel = 1;
7054                         else
7055                                 op_channel = 1 + (r % 3) * 5;
7056                         cfg_op_channel = 0;
7057                 }
7058                 ret = p2p_set_oper_channel(p2p, op_reg_class, op_channel,
7059                                            cfg_op_channel);
7060                 if (ret)
7061                         wpa_printf(MSG_ERROR, "P2P: Own oper channel update "
7062                                    "failed: %d", ret);
7063         }
7064
7065         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_PREF_CHAN) {
7066                 if (p2p_set_pref_chan(p2p, wpa_s->conf->num_p2p_pref_chan,
7067                                       wpa_s->conf->p2p_pref_chan) < 0) {
7068                         wpa_printf(MSG_ERROR, "P2P: Preferred channel list "
7069                                    "update failed");
7070                 }
7071
7072                 if (p2p_set_no_go_freq(p2p, &wpa_s->conf->p2p_no_go_freq) < 0) {
7073                         wpa_printf(MSG_ERROR, "P2P: No GO channel list "
7074                                    "update failed");
7075                 }
7076         }
7077
7078         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_PASSPHRASE_LEN)
7079                 p2p_set_passphrase_len(p2p, wpa_s->conf->p2p_passphrase_len);
7080 }
7081
7082
7083 int wpas_p2p_set_noa(struct wpa_supplicant *wpa_s, u8 count, int start,
7084                      int duration)
7085 {
7086         if (!wpa_s->ap_iface)
7087                 return -1;
7088         return hostapd_p2p_set_noa(wpa_s->ap_iface->bss[0], count, start,
7089                                    duration);
7090 }
7091
7092
7093 int wpas_p2p_set_cross_connect(struct wpa_supplicant *wpa_s, int enabled)
7094 {
7095         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
7096                 return -1;
7097
7098         wpa_s->global->cross_connection = enabled;
7099         p2p_set_cross_connect(wpa_s->global->p2p, enabled);
7100
7101         if (!enabled) {
7102                 struct wpa_supplicant *iface;
7103
7104                 for (iface = wpa_s->global->ifaces; iface; iface = iface->next)
7105                 {
7106                         if (iface->cross_connect_enabled == 0)
7107                                 continue;
7108
7109                         iface->cross_connect_enabled = 0;
7110                         iface->cross_connect_in_use = 0;
7111                         wpa_msg_global(iface->parent, MSG_INFO,
7112                                        P2P_EVENT_CROSS_CONNECT_DISABLE "%s %s",
7113                                        iface->ifname,
7114                                        iface->cross_connect_uplink);
7115                 }
7116         }
7117
7118         return 0;
7119 }
7120
7121
7122 static void wpas_p2p_enable_cross_connect(struct wpa_supplicant *uplink)
7123 {
7124         struct wpa_supplicant *iface;
7125
7126         if (!uplink->global->cross_connection)
7127                 return;
7128
7129         for (iface = uplink->global->ifaces; iface; iface = iface->next) {
7130                 if (!iface->cross_connect_enabled)
7131                         continue;
7132                 if (os_strcmp(uplink->ifname, iface->cross_connect_uplink) !=
7133                     0)
7134                         continue;
7135                 if (iface->ap_iface == NULL)
7136                         continue;
7137                 if (iface->cross_connect_in_use)
7138                         continue;
7139
7140                 iface->cross_connect_in_use = 1;
7141                 wpa_msg_global(iface->parent, MSG_INFO,
7142                                P2P_EVENT_CROSS_CONNECT_ENABLE "%s %s",
7143                                iface->ifname, iface->cross_connect_uplink);
7144         }
7145 }
7146
7147
7148 static void wpas_p2p_disable_cross_connect(struct wpa_supplicant *uplink)
7149 {
7150         struct wpa_supplicant *iface;
7151
7152         for (iface = uplink->global->ifaces; iface; iface = iface->next) {
7153                 if (!iface->cross_connect_enabled)
7154                         continue;
7155                 if (os_strcmp(uplink->ifname, iface->cross_connect_uplink) !=
7156                     0)
7157                         continue;
7158                 if (!iface->cross_connect_in_use)
7159                         continue;
7160
7161                 wpa_msg_global(iface->parent, MSG_INFO,
7162                                P2P_EVENT_CROSS_CONNECT_DISABLE "%s %s",
7163                                iface->ifname, iface->cross_connect_uplink);
7164                 iface->cross_connect_in_use = 0;
7165         }
7166 }
7167
7168
7169 void wpas_p2p_notif_connected(struct wpa_supplicant *wpa_s)
7170 {
7171         if (wpa_s->ap_iface || wpa_s->current_ssid == NULL ||
7172             wpa_s->current_ssid->mode != WPAS_MODE_INFRA ||
7173             wpa_s->cross_connect_disallowed)
7174                 wpas_p2p_disable_cross_connect(wpa_s);
7175         else
7176                 wpas_p2p_enable_cross_connect(wpa_s);
7177         if (!wpa_s->ap_iface &&
7178             eloop_cancel_timeout(wpas_p2p_group_idle_timeout, wpa_s, NULL) > 0)
7179                 wpa_printf(MSG_DEBUG, "P2P: Cancelled P2P group idle timeout");
7180 }
7181
7182
7183 void wpas_p2p_notif_disconnected(struct wpa_supplicant *wpa_s)
7184 {
7185         wpas_p2p_disable_cross_connect(wpa_s);
7186         if (!wpa_s->ap_iface &&
7187             !eloop_is_timeout_registered(wpas_p2p_group_idle_timeout,
7188                                          wpa_s, NULL))
7189                 wpas_p2p_set_group_idle_timeout(wpa_s);
7190 }
7191
7192
7193 static void wpas_p2p_cross_connect_setup(struct wpa_supplicant *wpa_s)
7194 {
7195         struct wpa_supplicant *iface;
7196
7197         if (!wpa_s->global->cross_connection)
7198                 return;
7199
7200         for (iface = wpa_s->global->ifaces; iface; iface = iface->next) {
7201                 if (iface == wpa_s)
7202                         continue;
7203                 if (iface->drv_flags &
7204                     WPA_DRIVER_FLAGS_P2P_DEDICATED_INTERFACE)
7205                         continue;
7206                 if ((iface->drv_flags & WPA_DRIVER_FLAGS_P2P_CAPABLE) &&
7207                     iface != wpa_s->parent)
7208                         continue;
7209
7210                 wpa_s->cross_connect_enabled = 1;
7211                 os_strlcpy(wpa_s->cross_connect_uplink, iface->ifname,
7212                            sizeof(wpa_s->cross_connect_uplink));
7213                 wpa_printf(MSG_DEBUG, "P2P: Enable cross connection from "
7214                            "%s to %s whenever uplink is available",
7215                            wpa_s->ifname, wpa_s->cross_connect_uplink);
7216
7217                 if (iface->ap_iface || iface->current_ssid == NULL ||
7218                     iface->current_ssid->mode != WPAS_MODE_INFRA ||
7219                     iface->cross_connect_disallowed ||
7220                     iface->wpa_state != WPA_COMPLETED)
7221                         break;
7222
7223                 wpa_s->cross_connect_in_use = 1;
7224                 wpa_msg_global(wpa_s->parent, MSG_INFO,
7225                                P2P_EVENT_CROSS_CONNECT_ENABLE "%s %s",
7226                                wpa_s->ifname, wpa_s->cross_connect_uplink);
7227                 break;
7228         }
7229 }
7230
7231
7232 int wpas_p2p_notif_pbc_overlap(struct wpa_supplicant *wpa_s)
7233 {
7234         if (wpa_s->p2p_group_interface != P2P_GROUP_INTERFACE_CLIENT &&
7235             !wpa_s->p2p_in_provisioning)
7236                 return 0; /* not P2P client operation */
7237
7238         wpa_printf(MSG_DEBUG, "P2P: Terminate connection due to WPS PBC "
7239                    "session overlap");
7240         if (wpa_s != wpa_s->parent)
7241                 wpa_msg_ctrl(wpa_s->parent, MSG_INFO, WPS_EVENT_OVERLAP);
7242         wpas_p2p_group_formation_failed(wpa_s);
7243         return 1;
7244 }
7245
7246
7247 void wpas_p2p_pbc_overlap_cb(void *eloop_ctx, void *timeout_ctx)
7248 {
7249         struct wpa_supplicant *wpa_s = eloop_ctx;
7250         wpas_p2p_notif_pbc_overlap(wpa_s);
7251 }
7252
7253
7254 void wpas_p2p_update_channel_list(struct wpa_supplicant *wpa_s)
7255 {
7256         struct p2p_channels chan, cli_chan;
7257         struct wpa_supplicant *ifs;
7258
7259         if (wpa_s->global == NULL || wpa_s->global->p2p == NULL)
7260                 return;
7261
7262         os_memset(&chan, 0, sizeof(chan));
7263         os_memset(&cli_chan, 0, sizeof(cli_chan));
7264         if (wpas_p2p_setup_channels(wpa_s, &chan, &cli_chan)) {
7265                 wpa_printf(MSG_ERROR, "P2P: Failed to update supported "
7266                            "channel list");
7267                 return;
7268         }
7269
7270         p2p_update_channel_list(wpa_s->global->p2p, &chan, &cli_chan);
7271
7272         for (ifs = wpa_s->global->ifaces; ifs; ifs = ifs->next) {
7273                 int freq;
7274                 if (!ifs->current_ssid ||
7275                     !ifs->current_ssid->p2p_group ||
7276                     (ifs->current_ssid->mode != WPAS_MODE_P2P_GO &&
7277                      ifs->current_ssid->mode != WPAS_MODE_P2P_GROUP_FORMATION))
7278                                 continue;
7279                 freq = ifs->current_ssid->frequency;
7280                 if (freq_included(&chan, freq)) {
7281                         wpa_dbg(ifs, MSG_DEBUG,
7282                                 "P2P GO operating frequency %d MHz in valid range",
7283                                 freq);
7284                         continue;
7285                 }
7286
7287                 wpa_dbg(ifs, MSG_DEBUG,
7288                         "P2P GO operating in invalid frequency %d MHz", freq);
7289                 /* TODO: Consider using CSA or removing the group within
7290                  * wpa_supplicant */
7291                 wpa_msg(ifs, MSG_INFO, P2P_EVENT_REMOVE_AND_REFORM_GROUP);
7292         }
7293 }
7294
7295
7296 static void wpas_p2p_scan_res_ignore(struct wpa_supplicant *wpa_s,
7297                                      struct wpa_scan_results *scan_res)
7298 {
7299         wpa_printf(MSG_DEBUG, "P2P: Ignore scan results");
7300 }
7301
7302
7303 int wpas_p2p_cancel(struct wpa_supplicant *wpa_s)
7304 {
7305         struct wpa_global *global = wpa_s->global;
7306         int found = 0;
7307         const u8 *peer;
7308
7309         if (global->p2p == NULL)
7310                 return -1;
7311
7312         wpa_printf(MSG_DEBUG, "P2P: Request to cancel group formation");
7313
7314         if (wpa_s->pending_interface_name[0] &&
7315             !is_zero_ether_addr(wpa_s->pending_interface_addr))
7316                 found = 1;
7317
7318         peer = p2p_get_go_neg_peer(global->p2p);
7319         if (peer) {
7320                 wpa_printf(MSG_DEBUG, "P2P: Unauthorize pending GO Neg peer "
7321                            MACSTR, MAC2STR(peer));
7322                 p2p_unauthorize(global->p2p, peer);
7323                 found = 1;
7324         }
7325
7326         if (wpa_s->scan_res_handler == wpas_p2p_scan_res_join) {
7327                 wpa_printf(MSG_DEBUG, "P2P: Stop pending scan for join");
7328                 wpa_s->scan_res_handler = wpas_p2p_scan_res_ignore;
7329                 found = 1;
7330         }
7331
7332         if (wpa_s->pending_pd_before_join) {
7333                 wpa_printf(MSG_DEBUG, "P2P: Stop pending PD before join");
7334                 wpa_s->pending_pd_before_join = 0;
7335                 found = 1;
7336         }
7337
7338         wpas_p2p_stop_find(wpa_s);
7339
7340         for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) {
7341                 if (wpa_s == global->p2p_group_formation &&
7342                     (wpa_s->p2p_in_provisioning ||
7343                      wpa_s->parent->pending_interface_type ==
7344                      WPA_IF_P2P_CLIENT)) {
7345                         wpa_printf(MSG_DEBUG, "P2P: Interface %s in group "
7346                                    "formation found - cancelling",
7347                                    wpa_s->ifname);
7348                         found = 1;
7349                         eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
7350                                              wpa_s->parent, NULL);
7351                         if (wpa_s->p2p_in_provisioning) {
7352                                 wpas_group_formation_completed(wpa_s, 0);
7353                                 break;
7354                         }
7355                         wpas_p2p_group_delete(wpa_s,
7356                                               P2P_GROUP_REMOVAL_REQUESTED);
7357                         break;
7358                 } else if (wpa_s->p2p_in_invitation) {
7359                         wpa_printf(MSG_DEBUG, "P2P: Interface %s in invitation found - cancelling",
7360                                    wpa_s->ifname);
7361                         found = 1;
7362                         wpas_p2p_group_formation_failed(wpa_s);
7363                 }
7364         }
7365
7366         if (!found) {
7367                 wpa_printf(MSG_DEBUG, "P2P: No ongoing group formation found");
7368                 return -1;
7369         }
7370
7371         return 0;
7372 }
7373
7374
7375 void wpas_p2p_interface_unavailable(struct wpa_supplicant *wpa_s)
7376 {
7377         if (wpa_s->current_ssid == NULL || !wpa_s->current_ssid->p2p_group)
7378                 return;
7379
7380         wpa_printf(MSG_DEBUG, "P2P: Remove group due to driver resource not "
7381                    "being available anymore");
7382         wpas_p2p_group_delete(wpa_s, P2P_GROUP_REMOVAL_UNAVAILABLE);
7383 }
7384
7385
7386 void wpas_p2p_update_best_channels(struct wpa_supplicant *wpa_s,
7387                                    int freq_24, int freq_5, int freq_overall)
7388 {
7389         struct p2p_data *p2p = wpa_s->global->p2p;
7390         if (p2p == NULL)
7391                 return;
7392         p2p_set_best_channels(p2p, freq_24, freq_5, freq_overall);
7393 }
7394
7395
7396 int wpas_p2p_unauthorize(struct wpa_supplicant *wpa_s, const char *addr)
7397 {
7398         u8 peer[ETH_ALEN];
7399         struct p2p_data *p2p = wpa_s->global->p2p;
7400
7401         if (p2p == NULL)
7402                 return -1;
7403
7404         if (hwaddr_aton(addr, peer))
7405                 return -1;
7406
7407         return p2p_unauthorize(p2p, peer);
7408 }
7409
7410
7411 /**
7412  * wpas_p2p_disconnect - Disconnect from a P2P Group
7413  * @wpa_s: Pointer to wpa_supplicant data
7414  * Returns: 0 on success, -1 on failure
7415  *
7416  * This can be used to disconnect from a group in which the local end is a P2P
7417  * Client or to end a P2P Group in case the local end is the Group Owner. If a
7418  * virtual network interface was created for this group, that interface will be
7419  * removed. Otherwise, only the configured P2P group network will be removed
7420  * from the interface.
7421  */
7422 int wpas_p2p_disconnect(struct wpa_supplicant *wpa_s)
7423 {
7424
7425         if (wpa_s == NULL)
7426                 return -1;
7427
7428         return wpas_p2p_group_delete(wpa_s, P2P_GROUP_REMOVAL_REQUESTED) < 0 ?
7429                 -1 : 0;
7430 }
7431
7432
7433 int wpas_p2p_in_progress(struct wpa_supplicant *wpa_s)
7434 {
7435         int ret;
7436
7437         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
7438                 return 0;
7439
7440         ret = p2p_in_progress(wpa_s->global->p2p);
7441         if (ret == 0) {
7442                 /*
7443                  * Check whether there is an ongoing WPS provisioning step (or
7444                  * other parts of group formation) on another interface since
7445                  * p2p_in_progress() does not report this to avoid issues for
7446                  * scans during such provisioning step.
7447                  */
7448                 if (wpa_s->global->p2p_group_formation &&
7449                     wpa_s->global->p2p_group_formation != wpa_s) {
7450                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Another interface (%s) "
7451                                 "in group formation",
7452                                 wpa_s->global->p2p_group_formation->ifname);
7453                         ret = 1;
7454                 }
7455         }
7456
7457         if (!ret && wpa_s->global->p2p_go_wait_client.sec) {
7458                 struct os_reltime now;
7459                 os_get_reltime(&now);
7460                 if (os_reltime_expired(&now, &wpa_s->global->p2p_go_wait_client,
7461                                        P2P_MAX_INITIAL_CONN_WAIT_GO)) {
7462                         /* Wait for the first client has expired */
7463                         wpa_s->global->p2p_go_wait_client.sec = 0;
7464                 } else {
7465                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Waiting for initial client connection during group formation");
7466                         ret = 1;
7467                 }
7468         }
7469
7470         return ret;
7471 }
7472
7473
7474 void wpas_p2p_network_removed(struct wpa_supplicant *wpa_s,
7475                               struct wpa_ssid *ssid)
7476 {
7477         if (wpa_s->p2p_in_provisioning && ssid->p2p_group &&
7478             eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
7479                                  wpa_s->parent, NULL) > 0) {
7480                 /**
7481                  * Remove the network by scheduling the group formation
7482                  * timeout to happen immediately. The teardown code
7483                  * needs to be scheduled to run asynch later so that we
7484                  * don't delete data from under ourselves unexpectedly.
7485                  * Calling wpas_p2p_group_formation_timeout directly
7486                  * causes a series of crashes in WPS failure scenarios.
7487                  */
7488                 wpa_printf(MSG_DEBUG, "P2P: Canceled group formation due to "
7489                            "P2P group network getting removed");
7490                 eloop_register_timeout(0, 0, wpas_p2p_group_formation_timeout,
7491                                        wpa_s->parent, NULL);
7492         }
7493 }
7494
7495
7496 struct wpa_ssid * wpas_p2p_get_persistent(struct wpa_supplicant *wpa_s,
7497                                           const u8 *addr, const u8 *ssid,
7498                                           size_t ssid_len)
7499 {
7500         struct wpa_ssid *s;
7501         size_t i;
7502
7503         for (s = wpa_s->conf->ssid; s; s = s->next) {
7504                 if (s->disabled != 2)
7505                         continue;
7506                 if (ssid &&
7507                     (ssid_len != s->ssid_len ||
7508                      os_memcmp(ssid, s->ssid, ssid_len) != 0))
7509                         continue;
7510                 if (addr == NULL) {
7511                         if (s->mode == WPAS_MODE_P2P_GO)
7512                                 return s;
7513                         continue;
7514                 }
7515                 if (os_memcmp(s->bssid, addr, ETH_ALEN) == 0)
7516                         return s; /* peer is GO in the persistent group */
7517                 if (s->mode != WPAS_MODE_P2P_GO || s->p2p_client_list == NULL)
7518                         continue;
7519                 for (i = 0; i < s->num_p2p_clients; i++) {
7520                         if (os_memcmp(s->p2p_client_list + i * 2 * ETH_ALEN,
7521                                       addr, ETH_ALEN) == 0)
7522                                 return s; /* peer is P2P client in persistent
7523                                            * group */
7524                 }
7525         }
7526
7527         return NULL;
7528 }
7529
7530
7531 void wpas_p2p_notify_ap_sta_authorized(struct wpa_supplicant *wpa_s,
7532                                        const u8 *addr)
7533 {
7534         if (eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
7535                                  wpa_s->parent, NULL) > 0) {
7536                 /*
7537                  * This can happen if WPS provisioning step is not terminated
7538                  * cleanly (e.g., P2P Client does not send WSC_Done). Since the
7539                  * peer was able to connect, there is no need to time out group
7540                  * formation after this, though. In addition, this is used with
7541                  * the initial connection wait on the GO as a separate formation
7542                  * timeout and as such, expected to be hit after the initial WPS
7543                  * provisioning step.
7544                  */
7545                 wpa_printf(MSG_DEBUG, "P2P: Canceled P2P group formation timeout on data connection");
7546
7547                 if (!wpa_s->p2p_go_group_formation_completed &&
7548                     !wpa_s->group_formation_reported) {
7549                         /*
7550                          * GO has not yet notified group formation success since
7551                          * the WPS step was not completed cleanly. Do that
7552                          * notification now since the P2P Client was able to
7553                          * connect and as such, must have received the
7554                          * credential from the WPS step.
7555                          */
7556                         if (wpa_s->global->p2p)
7557                                 p2p_wps_success_cb(wpa_s->global->p2p, addr);
7558                         wpas_group_formation_completed(wpa_s, 1);
7559                 }
7560         }
7561         if (!wpa_s->p2p_go_group_formation_completed) {
7562                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Marking group formation completed on GO on first data connection");
7563                 wpa_s->p2p_go_group_formation_completed = 1;
7564                 wpa_s->global->p2p_group_formation = NULL;
7565                 wpa_s->p2p_in_provisioning = 0;
7566                 wpa_s->p2p_in_invitation = 0;
7567         }
7568         wpa_s->global->p2p_go_wait_client.sec = 0;
7569         if (addr == NULL)
7570                 return;
7571         wpas_p2p_add_persistent_group_client(wpa_s, addr);
7572 }
7573
7574
7575 static void wpas_p2p_fallback_to_go_neg(struct wpa_supplicant *wpa_s,
7576                                         int group_added)
7577 {
7578         struct wpa_supplicant *group = wpa_s;
7579         if (wpa_s->global->p2p_group_formation)
7580                 group = wpa_s->global->p2p_group_formation;
7581         wpa_s = wpa_s->parent;
7582         offchannel_send_action_done(wpa_s);
7583         if (group_added)
7584                 wpas_p2p_group_delete(group, P2P_GROUP_REMOVAL_SILENT);
7585         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Fall back to GO Negotiation");
7586         wpas_p2p_connect(wpa_s, wpa_s->pending_join_dev_addr, wpa_s->p2p_pin,
7587                          wpa_s->p2p_wps_method, wpa_s->p2p_persistent_group, 0,
7588                          0, 0, wpa_s->p2p_go_intent, wpa_s->p2p_connect_freq,
7589                          wpa_s->p2p_persistent_id,
7590                          wpa_s->p2p_pd_before_go_neg,
7591                          wpa_s->p2p_go_ht40,
7592                          wpa_s->p2p_go_vht);
7593 }
7594
7595
7596 int wpas_p2p_scan_no_go_seen(struct wpa_supplicant *wpa_s)
7597 {
7598         if (!wpa_s->p2p_fallback_to_go_neg ||
7599             wpa_s->p2p_in_provisioning <= 5)
7600                 return 0;
7601
7602         if (wpas_p2p_peer_go(wpa_s, wpa_s->pending_join_dev_addr) > 0)
7603                 return 0; /* peer operating as a GO */
7604
7605         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: GO not found for p2p_connect-auto - "
7606                 "fallback to GO Negotiation");
7607         wpas_p2p_fallback_to_go_neg(wpa_s, 1);
7608
7609         return 1;
7610 }
7611
7612
7613 unsigned int wpas_p2p_search_delay(struct wpa_supplicant *wpa_s)
7614 {
7615         struct wpa_supplicant *ifs;
7616
7617         if (wpa_s->wpa_state > WPA_SCANNING) {
7618                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Use %u ms search delay due to "
7619                         "concurrent operation",
7620                         wpa_s->conf->p2p_search_delay);
7621                 return wpa_s->conf->p2p_search_delay;
7622         }
7623
7624         dl_list_for_each(ifs, &wpa_s->radio->ifaces, struct wpa_supplicant,
7625                          radio_list) {
7626                 if (ifs != wpa_s && ifs->wpa_state > WPA_SCANNING) {
7627                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Use %u ms search "
7628                                 "delay due to concurrent operation on "
7629                                 "interface %s",
7630                                 wpa_s->conf->p2p_search_delay,
7631                                 ifs->ifname);
7632                         return wpa_s->conf->p2p_search_delay;
7633                 }
7634         }
7635
7636         return 0;
7637 }
7638
7639
7640 static int wpas_p2p_remove_psk_entry(struct wpa_supplicant *wpa_s,
7641                                      struct wpa_ssid *s, const u8 *addr,
7642                                      int iface_addr)
7643 {
7644         struct psk_list_entry *psk, *tmp;
7645         int changed = 0;
7646
7647         dl_list_for_each_safe(psk, tmp, &s->psk_list, struct psk_list_entry,
7648                               list) {
7649                 if ((iface_addr && !psk->p2p &&
7650                      os_memcmp(addr, psk->addr, ETH_ALEN) == 0) ||
7651                     (!iface_addr && psk->p2p &&
7652                      os_memcmp(addr, psk->addr, ETH_ALEN) == 0)) {
7653                         wpa_dbg(wpa_s, MSG_DEBUG,
7654                                 "P2P: Remove persistent group PSK list entry for "
7655                                 MACSTR " p2p=%u",
7656                                 MAC2STR(psk->addr), psk->p2p);
7657                         dl_list_del(&psk->list);
7658                         os_free(psk);
7659                         changed++;
7660                 }
7661         }
7662
7663         return changed;
7664 }
7665
7666
7667 void wpas_p2p_new_psk_cb(struct wpa_supplicant *wpa_s, const u8 *mac_addr,
7668                          const u8 *p2p_dev_addr,
7669                          const u8 *psk, size_t psk_len)
7670 {
7671         struct wpa_ssid *ssid = wpa_s->current_ssid;
7672         struct wpa_ssid *persistent;
7673         struct psk_list_entry *p, *last;
7674
7675         if (psk_len != sizeof(p->psk))
7676                 return;
7677
7678         if (p2p_dev_addr) {
7679                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: New PSK for addr=" MACSTR
7680                         " p2p_dev_addr=" MACSTR,
7681                         MAC2STR(mac_addr), MAC2STR(p2p_dev_addr));
7682                 if (is_zero_ether_addr(p2p_dev_addr))
7683                         p2p_dev_addr = NULL;
7684         } else {
7685                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: New PSK for addr=" MACSTR,
7686                         MAC2STR(mac_addr));
7687         }
7688
7689         if (ssid->mode == WPAS_MODE_P2P_GROUP_FORMATION) {
7690                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: new_psk_cb during group formation");
7691                 /* To be added to persistent group once created */
7692                 if (wpa_s->global->add_psk == NULL) {
7693                         wpa_s->global->add_psk = os_zalloc(sizeof(*p));
7694                         if (wpa_s->global->add_psk == NULL)
7695                                 return;
7696                 }
7697                 p = wpa_s->global->add_psk;
7698                 if (p2p_dev_addr) {
7699                         p->p2p = 1;
7700                         os_memcpy(p->addr, p2p_dev_addr, ETH_ALEN);
7701                 } else {
7702                         p->p2p = 0;
7703                         os_memcpy(p->addr, mac_addr, ETH_ALEN);
7704                 }
7705                 os_memcpy(p->psk, psk, psk_len);
7706                 return;
7707         }
7708
7709         if (ssid->mode != WPAS_MODE_P2P_GO || !ssid->p2p_persistent_group) {
7710                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Ignore new_psk_cb on not-persistent GO");
7711                 return;
7712         }
7713
7714         persistent = wpas_p2p_get_persistent(wpa_s->parent, NULL, ssid->ssid,
7715                                              ssid->ssid_len);
7716         if (!persistent) {
7717                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Could not find persistent group information to store the new PSK");
7718                 return;
7719         }
7720
7721         p = os_zalloc(sizeof(*p));
7722         if (p == NULL)
7723                 return;
7724         if (p2p_dev_addr) {
7725                 p->p2p = 1;
7726                 os_memcpy(p->addr, p2p_dev_addr, ETH_ALEN);
7727         } else {
7728                 p->p2p = 0;
7729                 os_memcpy(p->addr, mac_addr, ETH_ALEN);
7730         }
7731         os_memcpy(p->psk, psk, psk_len);
7732
7733         if (dl_list_len(&persistent->psk_list) > P2P_MAX_STORED_CLIENTS &&
7734             (last = dl_list_last(&persistent->psk_list,
7735                                  struct psk_list_entry, list))) {
7736                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Remove oldest PSK entry for "
7737                         MACSTR " (p2p=%u) to make room for a new one",
7738                         MAC2STR(last->addr), last->p2p);
7739                 dl_list_del(&last->list);
7740                 os_free(last);
7741         }
7742
7743         wpas_p2p_remove_psk_entry(wpa_s->parent, persistent,
7744                                   p2p_dev_addr ? p2p_dev_addr : mac_addr,
7745                                   p2p_dev_addr == NULL);
7746         if (p2p_dev_addr) {
7747                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Add new PSK for p2p_dev_addr="
7748                         MACSTR, MAC2STR(p2p_dev_addr));
7749         } else {
7750                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Add new PSK for addr=" MACSTR,
7751                         MAC2STR(mac_addr));
7752         }
7753         dl_list_add(&persistent->psk_list, &p->list);
7754
7755         if (wpa_s->parent->conf->update_config &&
7756             wpa_config_write(wpa_s->parent->confname, wpa_s->parent->conf))
7757                 wpa_printf(MSG_DEBUG, "P2P: Failed to update configuration");
7758 }
7759
7760
7761 static void wpas_p2p_remove_psk(struct wpa_supplicant *wpa_s,
7762                                 struct wpa_ssid *s, const u8 *addr,
7763                                 int iface_addr)
7764 {
7765         int res;
7766
7767         res = wpas_p2p_remove_psk_entry(wpa_s, s, addr, iface_addr);
7768         if (res > 0 && wpa_s->conf->update_config &&
7769             wpa_config_write(wpa_s->confname, wpa_s->conf))
7770                 wpa_dbg(wpa_s, MSG_DEBUG,
7771                         "P2P: Failed to update configuration");
7772 }
7773
7774
7775 static void wpas_p2p_remove_client_go(struct wpa_supplicant *wpa_s,
7776                                       const u8 *peer, int iface_addr)
7777 {
7778         struct hostapd_data *hapd;
7779         struct hostapd_wpa_psk *psk, *prev, *rem;
7780         struct sta_info *sta;
7781
7782         if (wpa_s->ap_iface == NULL || wpa_s->current_ssid == NULL ||
7783             wpa_s->current_ssid->mode != WPAS_MODE_P2P_GO)
7784                 return;
7785
7786         /* Remove per-station PSK entry */
7787         hapd = wpa_s->ap_iface->bss[0];
7788         prev = NULL;
7789         psk = hapd->conf->ssid.wpa_psk;
7790         while (psk) {
7791                 if ((iface_addr && os_memcmp(peer, psk->addr, ETH_ALEN) == 0) ||
7792                     (!iface_addr &&
7793                      os_memcmp(peer, psk->p2p_dev_addr, ETH_ALEN) == 0)) {
7794                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Remove operating group PSK entry for "
7795                                 MACSTR " iface_addr=%d",
7796                                 MAC2STR(peer), iface_addr);
7797                         if (prev)
7798                                 prev->next = psk->next;
7799                         else
7800                                 hapd->conf->ssid.wpa_psk = psk->next;
7801                         rem = psk;
7802                         psk = psk->next;
7803                         os_free(rem);
7804                 } else {
7805                         prev = psk;
7806                         psk = psk->next;
7807                 }
7808         }
7809
7810         /* Disconnect from group */
7811         if (iface_addr)
7812                 sta = ap_get_sta(hapd, peer);
7813         else
7814                 sta = ap_get_sta_p2p(hapd, peer);
7815         if (sta) {
7816                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Disconnect peer " MACSTR
7817                         " (iface_addr=%d) from group",
7818                         MAC2STR(peer), iface_addr);
7819                 hostapd_drv_sta_deauth(hapd, sta->addr,
7820                                        WLAN_REASON_DEAUTH_LEAVING);
7821                 ap_sta_deauthenticate(hapd, sta, WLAN_REASON_DEAUTH_LEAVING);
7822         }
7823 }
7824
7825
7826 void wpas_p2p_remove_client(struct wpa_supplicant *wpa_s, const u8 *peer,
7827                             int iface_addr)
7828 {
7829         struct wpa_ssid *s;
7830         struct wpa_supplicant *w;
7831
7832         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Remove client " MACSTR, MAC2STR(peer));
7833
7834         /* Remove from any persistent group */
7835         for (s = wpa_s->parent->conf->ssid; s; s = s->next) {
7836                 if (s->disabled != 2 || s->mode != WPAS_MODE_P2P_GO)
7837                         continue;
7838                 if (!iface_addr)
7839                         wpas_remove_persistent_peer(wpa_s, s, peer, 0);
7840                 wpas_p2p_remove_psk(wpa_s->parent, s, peer, iface_addr);
7841         }
7842
7843         /* Remove from any operating group */
7844         for (w = wpa_s->global->ifaces; w; w = w->next)
7845                 wpas_p2p_remove_client_go(w, peer, iface_addr);
7846 }
7847
7848
7849 static void wpas_p2p_psk_failure_removal(void *eloop_ctx, void *timeout_ctx)
7850 {
7851         struct wpa_supplicant *wpa_s = eloop_ctx;
7852         wpas_p2p_group_delete(wpa_s, P2P_GROUP_REMOVAL_PSK_FAILURE);
7853 }
7854
7855
7856 static void wpas_p2p_group_freq_conflict(void *eloop_ctx, void *timeout_ctx)
7857 {
7858         struct wpa_supplicant *wpa_s = eloop_ctx;
7859
7860         wpa_printf(MSG_DEBUG, "P2P: Frequency conflict - terminate group");
7861         wpas_p2p_group_delete(wpa_s, P2P_GROUP_REMOVAL_FREQ_CONFLICT);
7862 }
7863
7864
7865 int wpas_p2p_handle_frequency_conflicts(struct wpa_supplicant *wpa_s, int freq,
7866                                         struct wpa_ssid *ssid)
7867 {
7868         struct wpa_supplicant *iface;
7869
7870         for (iface = wpa_s->global->ifaces; iface; iface = iface->next) {
7871                 if (!iface->current_ssid ||
7872                     iface->current_ssid->frequency == freq ||
7873                     (iface->p2p_group_interface == NOT_P2P_GROUP_INTERFACE &&
7874                      !iface->current_ssid->p2p_group))
7875                         continue;
7876
7877                 /* Remove the connection with least priority */
7878                 if (!wpas_is_p2p_prioritized(iface)) {
7879                         /* STA connection has priority over existing
7880                          * P2P connection, so remove the interface. */
7881                         wpa_printf(MSG_DEBUG, "P2P: Removing P2P connection due to single channel concurrent mode frequency conflict");
7882                         eloop_register_timeout(0, 0,
7883                                                wpas_p2p_group_freq_conflict,
7884                                                iface, NULL);
7885                         /* If connection in progress is P2P connection, do not
7886                          * proceed for the connection. */
7887                         if (wpa_s == iface)
7888                                 return -1;
7889                         else
7890                                 return 0;
7891                 } else {
7892                         /* P2P connection has priority, disable the STA network
7893                          */
7894                         wpa_supplicant_disable_network(wpa_s->global->ifaces,
7895                                                        ssid);
7896                         wpa_msg(wpa_s->global->ifaces, MSG_INFO,
7897                                 WPA_EVENT_FREQ_CONFLICT " id=%d", ssid->id);
7898                         os_memset(wpa_s->global->ifaces->pending_bssid, 0,
7899                                   ETH_ALEN);
7900                         /* If P2P connection is in progress, continue
7901                          * connecting...*/
7902                         if (wpa_s == iface)
7903                                 return 0;
7904                         else
7905                                 return -1;
7906                 }
7907         }
7908
7909         return 0;
7910 }
7911
7912
7913 int wpas_p2p_4way_hs_failed(struct wpa_supplicant *wpa_s)
7914 {
7915         struct wpa_ssid *ssid = wpa_s->current_ssid;
7916
7917         if (ssid == NULL || !ssid->p2p_group)
7918                 return 0;
7919
7920         if (wpa_s->p2p_last_4way_hs_fail &&
7921             wpa_s->p2p_last_4way_hs_fail == ssid) {
7922                 u8 go_dev_addr[ETH_ALEN];
7923                 struct wpa_ssid *persistent;
7924
7925                 if (wpas_p2p_persistent_group(wpa_s, go_dev_addr,
7926                                               ssid->ssid,
7927                                               ssid->ssid_len) <= 0) {
7928                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Could not determine whether 4-way handshake failures were for a persistent group");
7929                         goto disconnect;
7930                 }
7931
7932                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Two 4-way handshake failures for a P2P group - go_dev_addr="
7933                         MACSTR, MAC2STR(go_dev_addr));
7934                 persistent = wpas_p2p_get_persistent(wpa_s->parent, go_dev_addr,
7935                                                      ssid->ssid,
7936                                                      ssid->ssid_len);
7937                 if (persistent == NULL || persistent->mode != WPAS_MODE_INFRA) {
7938                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: No matching persistent group stored");
7939                         goto disconnect;
7940                 }
7941                 wpa_msg_global(wpa_s->parent, MSG_INFO,
7942                                P2P_EVENT_PERSISTENT_PSK_FAIL "%d",
7943                                persistent->id);
7944         disconnect:
7945                 wpa_s->p2p_last_4way_hs_fail = NULL;
7946                 /*
7947                  * Remove the group from a timeout to avoid issues with caller
7948                  * continuing to use the interface if this is on a P2P group
7949                  * interface.
7950                  */
7951                 eloop_register_timeout(0, 0, wpas_p2p_psk_failure_removal,
7952                                        wpa_s, NULL);
7953                 return 1;
7954         }
7955
7956         wpa_s->p2p_last_4way_hs_fail = ssid;
7957         return 0;
7958 }
7959
7960
7961 #ifdef CONFIG_WPS_NFC
7962
7963 static struct wpabuf * wpas_p2p_nfc_handover(int ndef, struct wpabuf *wsc,
7964                                              struct wpabuf *p2p)
7965 {
7966         struct wpabuf *ret;
7967         size_t wsc_len;
7968
7969         if (p2p == NULL) {
7970                 wpabuf_free(wsc);
7971                 wpa_printf(MSG_DEBUG, "P2P: No p2p buffer for handover");
7972                 return NULL;
7973         }
7974
7975         wsc_len = wsc ? wpabuf_len(wsc) : 0;
7976         ret = wpabuf_alloc(2 + wsc_len + 2 + wpabuf_len(p2p));
7977         if (ret == NULL) {
7978                 wpabuf_free(wsc);
7979                 wpabuf_free(p2p);
7980                 return NULL;
7981         }
7982
7983         wpabuf_put_be16(ret, wsc_len);
7984         if (wsc)
7985                 wpabuf_put_buf(ret, wsc);
7986         wpabuf_put_be16(ret, wpabuf_len(p2p));
7987         wpabuf_put_buf(ret, p2p);
7988
7989         wpabuf_free(wsc);
7990         wpabuf_free(p2p);
7991         wpa_hexdump_buf(MSG_DEBUG,
7992                         "P2P: Generated NFC connection handover message", ret);
7993
7994         if (ndef && ret) {
7995                 struct wpabuf *tmp;
7996                 tmp = ndef_build_p2p(ret);
7997                 wpabuf_free(ret);
7998                 if (tmp == NULL) {
7999                         wpa_printf(MSG_DEBUG, "P2P: Failed to NDEF encapsulate handover request");
8000                         return NULL;
8001                 }
8002                 ret = tmp;
8003         }
8004
8005         return ret;
8006 }
8007
8008
8009 static int wpas_p2p_cli_freq(struct wpa_supplicant *wpa_s,
8010                              struct wpa_ssid **ssid, u8 *go_dev_addr)
8011 {
8012         struct wpa_supplicant *iface;
8013
8014         if (go_dev_addr)
8015                 os_memset(go_dev_addr, 0, ETH_ALEN);
8016         if (ssid)
8017                 *ssid = NULL;
8018         for (iface = wpa_s->global->ifaces; iface; iface = iface->next) {
8019                 if (iface->wpa_state < WPA_ASSOCIATING ||
8020                     iface->current_ssid == NULL || iface->assoc_freq == 0 ||
8021                     !iface->current_ssid->p2p_group ||
8022                     iface->current_ssid->mode != WPAS_MODE_INFRA)
8023                         continue;
8024                 if (ssid)
8025                         *ssid = iface->current_ssid;
8026                 if (go_dev_addr)
8027                         os_memcpy(go_dev_addr, iface->go_dev_addr, ETH_ALEN);
8028                 return iface->assoc_freq;
8029         }
8030         return 0;
8031 }
8032
8033
8034 struct wpabuf * wpas_p2p_nfc_handover_req(struct wpa_supplicant *wpa_s,
8035                                           int ndef)
8036 {
8037         struct wpabuf *wsc, *p2p;
8038         struct wpa_ssid *ssid;
8039         u8 go_dev_addr[ETH_ALEN];
8040         int cli_freq = wpas_p2p_cli_freq(wpa_s, &ssid, go_dev_addr);
8041
8042         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL) {
8043                 wpa_printf(MSG_DEBUG, "P2P: P2P disabled - cannot build handover request");
8044                 return NULL;
8045         }
8046
8047         if (wpa_s->conf->wps_nfc_dh_pubkey == NULL &&
8048             wps_nfc_gen_dh(&wpa_s->conf->wps_nfc_dh_pubkey,
8049                            &wpa_s->conf->wps_nfc_dh_privkey) < 0) {
8050                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: No DH key available for handover request");
8051                 return NULL;
8052         }
8053
8054         if (cli_freq == 0) {
8055                 wsc = wps_build_nfc_handover_req_p2p(
8056                         wpa_s->parent->wps, wpa_s->conf->wps_nfc_dh_pubkey);
8057         } else
8058                 wsc = NULL;
8059         p2p = p2p_build_nfc_handover_req(wpa_s->global->p2p, cli_freq,
8060                                          go_dev_addr, ssid ? ssid->ssid : NULL,
8061                                          ssid ? ssid->ssid_len : 0);
8062
8063         return wpas_p2p_nfc_handover(ndef, wsc, p2p);
8064 }
8065
8066
8067 struct wpabuf * wpas_p2p_nfc_handover_sel(struct wpa_supplicant *wpa_s,
8068                                           int ndef, int tag)
8069 {
8070         struct wpabuf *wsc, *p2p;
8071         struct wpa_ssid *ssid;
8072         u8 go_dev_addr[ETH_ALEN];
8073         int cli_freq = wpas_p2p_cli_freq(wpa_s, &ssid, go_dev_addr);
8074
8075         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
8076                 return NULL;
8077
8078         if (!tag && wpa_s->conf->wps_nfc_dh_pubkey == NULL &&
8079             wps_nfc_gen_dh(&wpa_s->conf->wps_nfc_dh_pubkey,
8080                            &wpa_s->conf->wps_nfc_dh_privkey) < 0)
8081                 return NULL;
8082
8083         if (cli_freq == 0) {
8084                 wsc = wps_build_nfc_handover_sel_p2p(
8085                         wpa_s->parent->wps,
8086                         tag ? wpa_s->conf->wps_nfc_dev_pw_id :
8087                         DEV_PW_NFC_CONNECTION_HANDOVER,
8088                         wpa_s->conf->wps_nfc_dh_pubkey,
8089                         tag ? wpa_s->conf->wps_nfc_dev_pw : NULL);
8090         } else
8091                 wsc = NULL;
8092         p2p = p2p_build_nfc_handover_sel(wpa_s->global->p2p, cli_freq,
8093                                          go_dev_addr, ssid ? ssid->ssid : NULL,
8094                                          ssid ? ssid->ssid_len : 0);
8095
8096         return wpas_p2p_nfc_handover(ndef, wsc, p2p);
8097 }
8098
8099
8100 static int wpas_p2p_nfc_join_group(struct wpa_supplicant *wpa_s,
8101                                    struct p2p_nfc_params *params)
8102 {
8103         wpa_printf(MSG_DEBUG, "P2P: Initiate join-group based on NFC "
8104                    "connection handover (freq=%d)",
8105                    params->go_freq);
8106
8107         if (params->go_freq && params->go_ssid_len) {
8108                 wpa_s->p2p_wps_method = WPS_NFC;
8109                 wpa_s->pending_join_wps_method = WPS_NFC;
8110                 os_memset(wpa_s->pending_join_iface_addr, 0, ETH_ALEN);
8111                 os_memcpy(wpa_s->pending_join_dev_addr, params->go_dev_addr,
8112                           ETH_ALEN);
8113                 return wpas_p2p_join_start(wpa_s, params->go_freq,
8114                                            params->go_ssid,
8115                                            params->go_ssid_len);
8116         }
8117
8118         return wpas_p2p_connect(wpa_s, params->peer->p2p_device_addr, NULL,
8119                                 WPS_NFC, 0, 0, 1, 0, wpa_s->conf->p2p_go_intent,
8120                                 params->go_freq, -1, 0, 1, 1);
8121 }
8122
8123
8124 static int wpas_p2p_nfc_auth_join(struct wpa_supplicant *wpa_s,
8125                                   struct p2p_nfc_params *params, int tag)
8126 {
8127         int res, persistent;
8128         struct wpa_ssid *ssid;
8129
8130         wpa_printf(MSG_DEBUG, "P2P: Authorize join-group based on NFC "
8131                    "connection handover");
8132         for (wpa_s = wpa_s->global->ifaces; wpa_s; wpa_s = wpa_s->next) {
8133                 ssid = wpa_s->current_ssid;
8134                 if (ssid == NULL)
8135                         continue;
8136                 if (ssid->mode != WPAS_MODE_P2P_GO)
8137                         continue;
8138                 if (wpa_s->ap_iface == NULL)
8139                         continue;
8140                 break;
8141         }
8142         if (wpa_s == NULL) {
8143                 wpa_printf(MSG_DEBUG, "P2P: Could not find GO interface");
8144                 return -1;
8145         }
8146
8147         if (wpa_s->parent->p2p_oob_dev_pw_id !=
8148             DEV_PW_NFC_CONNECTION_HANDOVER &&
8149             !wpa_s->parent->p2p_oob_dev_pw) {
8150                 wpa_printf(MSG_DEBUG, "P2P: No NFC Dev Pw known");
8151                 return -1;
8152         }
8153         res = wpas_ap_wps_add_nfc_pw(
8154                 wpa_s, wpa_s->parent->p2p_oob_dev_pw_id,
8155                 wpa_s->parent->p2p_oob_dev_pw,
8156                 wpa_s->parent->p2p_peer_oob_pk_hash_known ?
8157                 wpa_s->parent->p2p_peer_oob_pubkey_hash : NULL);
8158         if (res)
8159                 return res;
8160
8161         if (!tag) {
8162                 wpa_printf(MSG_DEBUG, "P2P: Negotiated handover - wait for peer to join without invitation");
8163                 return 0;
8164         }
8165
8166         if (!params->peer ||
8167             !(params->peer->dev_capab & P2P_DEV_CAPAB_INVITATION_PROCEDURE))
8168                 return 0;
8169
8170         wpa_printf(MSG_DEBUG, "P2P: Static handover - invite peer " MACSTR
8171                    " to join", MAC2STR(params->peer->p2p_device_addr));
8172
8173         wpa_s->global->p2p_invite_group = wpa_s;
8174         persistent = ssid->p2p_persistent_group &&
8175                 wpas_p2p_get_persistent(wpa_s->parent,
8176                                         params->peer->p2p_device_addr,
8177                                         ssid->ssid, ssid->ssid_len);
8178         wpa_s->parent->pending_invite_ssid_id = -1;
8179
8180         return p2p_invite(wpa_s->global->p2p, params->peer->p2p_device_addr,
8181                           P2P_INVITE_ROLE_ACTIVE_GO, wpa_s->own_addr,
8182                           ssid->ssid, ssid->ssid_len, ssid->frequency,
8183                           wpa_s->global->p2p_dev_addr, persistent, 0,
8184                           wpa_s->parent->p2p_oob_dev_pw_id);
8185 }
8186
8187
8188 static int wpas_p2p_nfc_init_go_neg(struct wpa_supplicant *wpa_s,
8189                                     struct p2p_nfc_params *params,
8190                                     int forced_freq)
8191 {
8192         wpa_printf(MSG_DEBUG, "P2P: Initiate GO Negotiation based on NFC "
8193                    "connection handover");
8194         return wpas_p2p_connect(wpa_s, params->peer->p2p_device_addr, NULL,
8195                                 WPS_NFC, 0, 0, 0, 0, wpa_s->conf->p2p_go_intent,
8196                                 forced_freq, -1, 0, 1, 1);
8197 }
8198
8199
8200 static int wpas_p2p_nfc_resp_go_neg(struct wpa_supplicant *wpa_s,
8201                                     struct p2p_nfc_params *params,
8202                                     int forced_freq)
8203 {
8204         int res;
8205
8206         wpa_printf(MSG_DEBUG, "P2P: Authorize GO Negotiation based on NFC "
8207                    "connection handover");
8208         res = wpas_p2p_connect(wpa_s, params->peer->p2p_device_addr, NULL,
8209                                WPS_NFC, 0, 0, 0, 1, wpa_s->conf->p2p_go_intent,
8210                                forced_freq, -1, 0, 1, 1);
8211         if (res)
8212                 return res;
8213
8214         res = wpas_p2p_listen(wpa_s, 60);
8215         if (res) {
8216                 p2p_unauthorize(wpa_s->global->p2p,
8217                                 params->peer->p2p_device_addr);
8218         }
8219
8220         return res;
8221 }
8222
8223
8224 static int wpas_p2p_nfc_connection_handover(struct wpa_supplicant *wpa_s,
8225                                             const struct wpabuf *data,
8226                                             int sel, int tag, int forced_freq)
8227 {
8228         const u8 *pos, *end;
8229         u16 len, id;
8230         struct p2p_nfc_params params;
8231         int res;
8232
8233         os_memset(&params, 0, sizeof(params));
8234         params.sel = sel;
8235
8236         wpa_hexdump_buf(MSG_DEBUG, "P2P: Received NFC tag payload", data);
8237
8238         pos = wpabuf_head(data);
8239         end = pos + wpabuf_len(data);
8240
8241         if (end - pos < 2) {
8242                 wpa_printf(MSG_DEBUG, "P2P: Not enough data for Length of WSC "
8243                            "attributes");
8244                 return -1;
8245         }
8246         len = WPA_GET_BE16(pos);
8247         pos += 2;
8248         if (len > end - pos) {
8249                 wpa_printf(MSG_DEBUG, "P2P: Not enough data for WSC "
8250                            "attributes");
8251                 return -1;
8252         }
8253         params.wsc_attr = pos;
8254         params.wsc_len = len;
8255         pos += len;
8256
8257         if (end - pos < 2) {
8258                 wpa_printf(MSG_DEBUG, "P2P: Not enough data for Length of P2P "
8259                            "attributes");
8260                 return -1;
8261         }
8262         len = WPA_GET_BE16(pos);
8263         pos += 2;
8264         if (len > end - pos) {
8265                 wpa_printf(MSG_DEBUG, "P2P: Not enough data for P2P "
8266                            "attributes");
8267                 return -1;
8268         }
8269         params.p2p_attr = pos;
8270         params.p2p_len = len;
8271         pos += len;
8272
8273         wpa_hexdump(MSG_DEBUG, "P2P: WSC attributes",
8274                     params.wsc_attr, params.wsc_len);
8275         wpa_hexdump(MSG_DEBUG, "P2P: P2P attributes",
8276                     params.p2p_attr, params.p2p_len);
8277         if (pos < end) {
8278                 wpa_hexdump(MSG_DEBUG,
8279                             "P2P: Ignored extra data after P2P attributes",
8280                             pos, end - pos);
8281         }
8282
8283         res = p2p_process_nfc_connection_handover(wpa_s->global->p2p, &params);
8284         if (res)
8285                 return res;
8286
8287         if (params.next_step == NO_ACTION)
8288                 return 0;
8289
8290         if (params.next_step == BOTH_GO) {
8291                 wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_NFC_BOTH_GO "peer=" MACSTR,
8292                         MAC2STR(params.peer->p2p_device_addr));
8293                 return 0;
8294         }
8295
8296         if (params.next_step == PEER_CLIENT) {
8297                 if (!is_zero_ether_addr(params.go_dev_addr)) {
8298                         wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_NFC_PEER_CLIENT
8299                                 "peer=" MACSTR " freq=%d go_dev_addr=" MACSTR
8300                                 " ssid=\"%s\"",
8301                                 MAC2STR(params.peer->p2p_device_addr),
8302                                 params.go_freq,
8303                                 MAC2STR(params.go_dev_addr),
8304                                 wpa_ssid_txt(params.go_ssid,
8305                                              params.go_ssid_len));
8306                 } else {
8307                         wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_NFC_PEER_CLIENT
8308                                 "peer=" MACSTR " freq=%d",
8309                                 MAC2STR(params.peer->p2p_device_addr),
8310                                 params.go_freq);
8311                 }
8312                 return 0;
8313         }
8314
8315         if (wpas_p2p_cli_freq(wpa_s, NULL, NULL)) {
8316                 wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_NFC_WHILE_CLIENT "peer="
8317                         MACSTR, MAC2STR(params.peer->p2p_device_addr));
8318                 return 0;
8319         }
8320
8321         wpabuf_free(wpa_s->p2p_oob_dev_pw);
8322         wpa_s->p2p_oob_dev_pw = NULL;
8323
8324         if (params.oob_dev_pw_len < WPS_OOB_PUBKEY_HASH_LEN + 2) {
8325                 wpa_printf(MSG_DEBUG, "P2P: No peer OOB Dev Pw "
8326                            "received");
8327                 return -1;
8328         }
8329
8330         id = WPA_GET_BE16(params.oob_dev_pw + WPS_OOB_PUBKEY_HASH_LEN);
8331         wpa_printf(MSG_DEBUG, "P2P: Peer OOB Dev Pw %u", id);
8332         wpa_hexdump(MSG_DEBUG, "P2P: Peer OOB Public Key hash",
8333                     params.oob_dev_pw, WPS_OOB_PUBKEY_HASH_LEN);
8334         os_memcpy(wpa_s->p2p_peer_oob_pubkey_hash,
8335                   params.oob_dev_pw, WPS_OOB_PUBKEY_HASH_LEN);
8336         wpa_s->p2p_peer_oob_pk_hash_known = 1;
8337
8338         if (tag) {
8339                 if (id < 0x10) {
8340                         wpa_printf(MSG_DEBUG, "P2P: Static handover - invalid "
8341                                    "peer OOB Device Password Id %u", id);
8342                         return -1;
8343                 }
8344                 wpa_printf(MSG_DEBUG, "P2P: Static handover - use peer OOB "
8345                            "Device Password Id %u", id);
8346                 wpa_hexdump_key(MSG_DEBUG, "P2P: Peer OOB Device Password",
8347                                 params.oob_dev_pw + WPS_OOB_PUBKEY_HASH_LEN + 2,
8348                                 params.oob_dev_pw_len -
8349                                 WPS_OOB_PUBKEY_HASH_LEN - 2);
8350                 wpa_s->p2p_oob_dev_pw_id = id;
8351                 wpa_s->p2p_oob_dev_pw = wpabuf_alloc_copy(
8352                         params.oob_dev_pw + WPS_OOB_PUBKEY_HASH_LEN + 2,
8353                         params.oob_dev_pw_len -
8354                         WPS_OOB_PUBKEY_HASH_LEN - 2);
8355                 if (wpa_s->p2p_oob_dev_pw == NULL)
8356                         return -1;
8357
8358                 if (wpa_s->conf->wps_nfc_dh_pubkey == NULL &&
8359                     wps_nfc_gen_dh(&wpa_s->conf->wps_nfc_dh_pubkey,
8360                                    &wpa_s->conf->wps_nfc_dh_privkey) < 0)
8361                         return -1;
8362         } else {
8363                 wpa_printf(MSG_DEBUG, "P2P: Using abbreviated WPS handshake "
8364                            "without Device Password");
8365                 wpa_s->p2p_oob_dev_pw_id = DEV_PW_NFC_CONNECTION_HANDOVER;
8366         }
8367
8368         switch (params.next_step) {
8369         case NO_ACTION:
8370         case BOTH_GO:
8371         case PEER_CLIENT:
8372                 /* already covered above */
8373                 return 0;
8374         case JOIN_GROUP:
8375                 return wpas_p2p_nfc_join_group(wpa_s, &params);
8376         case AUTH_JOIN:
8377                 return wpas_p2p_nfc_auth_join(wpa_s, &params, tag);
8378         case INIT_GO_NEG:
8379                 return wpas_p2p_nfc_init_go_neg(wpa_s, &params, forced_freq);
8380         case RESP_GO_NEG:
8381                 /* TODO: use own OOB Dev Pw */
8382                 return wpas_p2p_nfc_resp_go_neg(wpa_s, &params, forced_freq);
8383         }
8384
8385         return -1;
8386 }
8387
8388
8389 int wpas_p2p_nfc_tag_process(struct wpa_supplicant *wpa_s,
8390                              const struct wpabuf *data, int forced_freq)
8391 {
8392         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
8393                 return -1;
8394
8395         return wpas_p2p_nfc_connection_handover(wpa_s, data, 1, 1, forced_freq);
8396 }
8397
8398
8399 int wpas_p2p_nfc_report_handover(struct wpa_supplicant *wpa_s, int init,
8400                                  const struct wpabuf *req,
8401                                  const struct wpabuf *sel, int forced_freq)
8402 {
8403         struct wpabuf *tmp;
8404         int ret;
8405
8406         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
8407                 return -1;
8408
8409         wpa_printf(MSG_DEBUG, "NFC: P2P connection handover reported");
8410
8411         wpa_hexdump_ascii(MSG_DEBUG, "NFC: Req",
8412                           wpabuf_head(req), wpabuf_len(req));
8413         wpa_hexdump_ascii(MSG_DEBUG, "NFC: Sel",
8414                           wpabuf_head(sel), wpabuf_len(sel));
8415         if (forced_freq)
8416                 wpa_printf(MSG_DEBUG, "NFC: Forced freq %d", forced_freq);
8417         tmp = ndef_parse_p2p(init ? sel : req);
8418         if (tmp == NULL) {
8419                 wpa_printf(MSG_DEBUG, "P2P: Could not parse NDEF");
8420                 return -1;
8421         }
8422
8423         ret = wpas_p2p_nfc_connection_handover(wpa_s, tmp, init, 0,
8424                                                forced_freq);
8425         wpabuf_free(tmp);
8426
8427         return ret;
8428 }
8429
8430
8431 int wpas_p2p_nfc_tag_enabled(struct wpa_supplicant *wpa_s, int enabled)
8432 {
8433         const u8 *if_addr;
8434         int go_intent = wpa_s->conf->p2p_go_intent;
8435         struct wpa_supplicant *iface;
8436
8437         if (wpa_s->global->p2p == NULL)
8438                 return -1;
8439
8440         if (!enabled) {
8441                 wpa_printf(MSG_DEBUG, "P2P: Disable use of own NFC Tag");
8442                 for (iface = wpa_s->global->ifaces; iface; iface = iface->next)
8443                 {
8444                         if (!iface->ap_iface)
8445                                 continue;
8446                         hostapd_wps_nfc_token_disable(iface->ap_iface->bss[0]);
8447                 }
8448                 p2p_set_authorized_oob_dev_pw_id(wpa_s->global->p2p, 0,
8449                                                  0, NULL);
8450                 if (wpa_s->p2p_nfc_tag_enabled)
8451                         wpas_p2p_remove_pending_group_interface(wpa_s);
8452                 wpa_s->p2p_nfc_tag_enabled = 0;
8453                 return 0;
8454         }
8455
8456         if (wpa_s->global->p2p_disabled)
8457                 return -1;
8458
8459         if (wpa_s->conf->wps_nfc_dh_pubkey == NULL ||
8460             wpa_s->conf->wps_nfc_dh_privkey == NULL ||
8461             wpa_s->conf->wps_nfc_dev_pw == NULL ||
8462             wpa_s->conf->wps_nfc_dev_pw_id < 0x10) {
8463                 wpa_printf(MSG_DEBUG, "P2P: NFC password token not configured "
8464                            "to allow static handover cases");
8465                 return -1;
8466         }
8467
8468         wpa_printf(MSG_DEBUG, "P2P: Enable use of own NFC Tag");
8469
8470         wpa_s->p2p_oob_dev_pw_id = wpa_s->conf->wps_nfc_dev_pw_id;
8471         wpabuf_free(wpa_s->p2p_oob_dev_pw);
8472         wpa_s->p2p_oob_dev_pw = wpabuf_dup(wpa_s->conf->wps_nfc_dev_pw);
8473         if (wpa_s->p2p_oob_dev_pw == NULL)
8474                 return -1;
8475         wpa_s->p2p_peer_oob_pk_hash_known = 0;
8476
8477         if (wpa_s->p2p_group_interface == P2P_GROUP_INTERFACE_GO ||
8478             wpa_s->p2p_group_interface == P2P_GROUP_INTERFACE_CLIENT) {
8479                 /*
8480                  * P2P Group Interface present and the command came on group
8481                  * interface, so enable the token for the current interface.
8482                  */
8483                 wpa_s->create_p2p_iface = 0;
8484         } else {
8485                 wpa_s->create_p2p_iface = wpas_p2p_create_iface(wpa_s);
8486         }
8487
8488         if (wpa_s->create_p2p_iface) {
8489                 enum wpa_driver_if_type iftype;
8490                 /* Prepare to add a new interface for the group */
8491                 iftype = WPA_IF_P2P_GROUP;
8492                 if (go_intent == 15)
8493                         iftype = WPA_IF_P2P_GO;
8494                 if (wpas_p2p_add_group_interface(wpa_s, iftype) < 0) {
8495                         wpa_printf(MSG_ERROR, "P2P: Failed to allocate a new "
8496                                    "interface for the group");
8497                         return -1;
8498                 }
8499
8500                 if_addr = wpa_s->pending_interface_addr;
8501         } else
8502                 if_addr = wpa_s->own_addr;
8503
8504         wpa_s->p2p_nfc_tag_enabled = enabled;
8505
8506         for (iface = wpa_s->global->ifaces; iface; iface = iface->next) {
8507                 struct hostapd_data *hapd;
8508                 if (iface->ap_iface == NULL)
8509                         continue;
8510                 hapd = iface->ap_iface->bss[0];
8511                 wpabuf_free(hapd->conf->wps_nfc_dh_pubkey);
8512                 hapd->conf->wps_nfc_dh_pubkey =
8513                         wpabuf_dup(wpa_s->conf->wps_nfc_dh_pubkey);
8514                 wpabuf_free(hapd->conf->wps_nfc_dh_privkey);
8515                 hapd->conf->wps_nfc_dh_privkey =
8516                         wpabuf_dup(wpa_s->conf->wps_nfc_dh_privkey);
8517                 wpabuf_free(hapd->conf->wps_nfc_dev_pw);
8518                 hapd->conf->wps_nfc_dev_pw =
8519                         wpabuf_dup(wpa_s->conf->wps_nfc_dev_pw);
8520                 hapd->conf->wps_nfc_dev_pw_id = wpa_s->conf->wps_nfc_dev_pw_id;
8521
8522                 if (hostapd_wps_nfc_token_enable(iface->ap_iface->bss[0]) < 0) {
8523                         wpa_dbg(iface, MSG_DEBUG,
8524                                 "P2P: Failed to enable NFC Tag for GO");
8525                 }
8526         }
8527         p2p_set_authorized_oob_dev_pw_id(
8528                 wpa_s->global->p2p, wpa_s->conf->wps_nfc_dev_pw_id, go_intent,
8529                 if_addr);
8530
8531         return 0;
8532 }
8533
8534 #endif /* CONFIG_WPS_NFC */
8535
8536
8537 static void wpas_p2p_optimize_listen_channel(struct wpa_supplicant *wpa_s,
8538                                              struct wpa_used_freq_data *freqs,
8539                                              unsigned int num)
8540 {
8541         u8 curr_chan, cand, chan;
8542         unsigned int i;
8543
8544         curr_chan = p2p_get_listen_channel(wpa_s->global->p2p);
8545         for (i = 0, cand = 0; i < num; i++) {
8546                 ieee80211_freq_to_chan(freqs[i].freq, &chan);
8547                 if (curr_chan == chan) {
8548                         cand = 0;
8549                         break;
8550                 }
8551
8552                 if (chan == 1 || chan == 6 || chan == 11)
8553                         cand = chan;
8554         }
8555
8556         if (cand) {
8557                 wpa_dbg(wpa_s, MSG_DEBUG,
8558                         "P2P: Update Listen channel to %u baased on operating channel",
8559                         cand);
8560                 p2p_set_listen_channel(wpa_s->global->p2p, 81, cand, 0);
8561         }
8562 }
8563
8564
8565 void wpas_p2p_indicate_state_change(struct wpa_supplicant *wpa_s)
8566 {
8567         struct wpa_used_freq_data *freqs;
8568         unsigned int num = wpa_s->num_multichan_concurrent;
8569
8570         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
8571                 return;
8572
8573         /*
8574          * If possible, optimize the Listen channel to be a channel that is
8575          * already used by one of the other interfaces.
8576          */
8577         if (!wpa_s->conf->p2p_optimize_listen_chan)
8578                 return;
8579
8580         if (!wpa_s->current_ssid || wpa_s->wpa_state != WPA_COMPLETED)
8581                 return;
8582
8583         freqs = os_calloc(num, sizeof(struct wpa_used_freq_data));
8584         if (!freqs)
8585                 return;
8586
8587         num = get_shared_radio_freqs_data(wpa_s, freqs, num);
8588
8589         wpas_p2p_optimize_listen_channel(wpa_s, freqs, num);
8590         os_free(freqs);
8591 }
8592
8593
8594 void wpas_p2p_deinit_iface(struct wpa_supplicant *wpa_s)
8595 {
8596         if (wpa_s == wpa_s->global->p2p_init_wpa_s && wpa_s->global->p2p) {
8597                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Disable P2P since removing "
8598                         "the management interface is being removed");
8599                 wpas_p2p_deinit_global(wpa_s->global);
8600         }
8601 }
8602
8603
8604 void wpas_p2p_ap_deinit(struct wpa_supplicant *wpa_s)
8605 {
8606         if (wpa_s->ap_iface->bss)
8607                 wpa_s->ap_iface->bss[0]->p2p_group = NULL;
8608         wpas_p2p_group_deinit(wpa_s);
8609 }