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