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