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