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