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