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