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