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