P2P: Collect and use extended data on used frequencies
[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         } else {
3876                 p2p.reg_class = 81;
3877                 /*
3878                  * Pick one of the social channels randomly as the listen
3879                  * channel.
3880                  */
3881                 os_get_random((u8 *) &r, sizeof(r));
3882                 p2p.channel = 1 + (r % 3) * 5;
3883         }
3884         wpa_printf(MSG_DEBUG, "P2P: Own listen channel: %d", p2p.channel);
3885
3886         if (wpa_s->conf->p2p_oper_reg_class &&
3887             wpa_s->conf->p2p_oper_channel) {
3888                 p2p.op_reg_class = wpa_s->conf->p2p_oper_reg_class;
3889                 p2p.op_channel = wpa_s->conf->p2p_oper_channel;
3890                 p2p.cfg_op_channel = 1;
3891                 wpa_printf(MSG_DEBUG, "P2P: Configured operating channel: "
3892                            "%d:%d", p2p.op_reg_class, p2p.op_channel);
3893
3894         } else {
3895                 p2p.op_reg_class = 81;
3896                 /*
3897                  * Use random operation channel from (1, 6, 11) if no other
3898                  * preference is indicated.
3899                  */
3900                 os_get_random((u8 *) &r, sizeof(r));
3901                 p2p.op_channel = 1 + (r % 3) * 5;
3902                 p2p.cfg_op_channel = 0;
3903                 wpa_printf(MSG_DEBUG, "P2P: Random operating channel: "
3904                            "%d:%d", p2p.op_reg_class, p2p.op_channel);
3905         }
3906
3907         if (wpa_s->conf->p2p_pref_chan && wpa_s->conf->num_p2p_pref_chan) {
3908                 p2p.pref_chan = wpa_s->conf->p2p_pref_chan;
3909                 p2p.num_pref_chan = wpa_s->conf->num_p2p_pref_chan;
3910         }
3911
3912         if (wpa_s->conf->country[0] && wpa_s->conf->country[1]) {
3913                 os_memcpy(p2p.country, wpa_s->conf->country, 2);
3914                 p2p.country[2] = 0x04;
3915         } else
3916                 os_memcpy(p2p.country, "XX\x04", 3);
3917
3918         if (wpas_p2p_setup_channels(wpa_s, &p2p.channels, &p2p.cli_channels)) {
3919                 wpa_printf(MSG_ERROR, "P2P: Failed to configure supported "
3920                            "channel list");
3921                 return -1;
3922         }
3923
3924         os_memcpy(p2p.pri_dev_type, wpa_s->conf->device_type,
3925                   WPS_DEV_TYPE_LEN);
3926
3927         p2p.num_sec_dev_types = wpa_s->conf->num_sec_device_types;
3928         os_memcpy(p2p.sec_dev_type, wpa_s->conf->sec_device_type,
3929                   p2p.num_sec_dev_types * WPS_DEV_TYPE_LEN);
3930
3931         p2p.concurrent_operations = !!(wpa_s->drv_flags &
3932                                        WPA_DRIVER_FLAGS_P2P_CONCURRENT);
3933
3934         p2p.max_peers = 100;
3935
3936         if (wpa_s->conf->p2p_ssid_postfix) {
3937                 p2p.ssid_postfix_len =
3938                         os_strlen(wpa_s->conf->p2p_ssid_postfix);
3939                 if (p2p.ssid_postfix_len > sizeof(p2p.ssid_postfix))
3940                         p2p.ssid_postfix_len = sizeof(p2p.ssid_postfix);
3941                 os_memcpy(p2p.ssid_postfix, wpa_s->conf->p2p_ssid_postfix,
3942                           p2p.ssid_postfix_len);
3943         }
3944
3945         p2p.p2p_intra_bss = wpa_s->conf->p2p_intra_bss;
3946
3947         p2p.max_listen = wpa_s->max_remain_on_chan;
3948
3949         global->p2p = p2p_init(&p2p);
3950         if (global->p2p == NULL)
3951                 return -1;
3952         global->p2p_init_wpa_s = wpa_s;
3953
3954         for (i = 0; i < MAX_WPS_VENDOR_EXT; i++) {
3955                 if (wpa_s->conf->wps_vendor_ext[i] == NULL)
3956                         continue;
3957                 p2p_add_wps_vendor_extension(
3958                         global->p2p, wpa_s->conf->wps_vendor_ext[i]);
3959         }
3960
3961         p2p_set_no_go_freq(global->p2p, &wpa_s->conf->p2p_no_go_freq);
3962
3963         return 0;
3964 }
3965
3966
3967 /**
3968  * wpas_p2p_deinit - Deinitialize per-interface P2P data
3969  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
3970  *
3971  * This function deinitialize per-interface P2P data.
3972  */
3973 void wpas_p2p_deinit(struct wpa_supplicant *wpa_s)
3974 {
3975         if (wpa_s->driver && wpa_s->drv_priv)
3976                 wpa_drv_probe_req_report(wpa_s, 0);
3977
3978         if (wpa_s->go_params) {
3979                 /* Clear any stored provisioning info */
3980                 p2p_clear_provisioning_info(
3981                         wpa_s->global->p2p,
3982                         wpa_s->go_params->peer_device_addr);
3983         }
3984
3985         os_free(wpa_s->go_params);
3986         wpa_s->go_params = NULL;
3987         eloop_cancel_timeout(wpas_p2p_psk_failure_removal, wpa_s, NULL);
3988         eloop_cancel_timeout(wpas_p2p_group_formation_timeout, wpa_s, NULL);
3989         eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
3990         wpa_s->p2p_long_listen = 0;
3991         eloop_cancel_timeout(wpas_p2p_long_listen_timeout, wpa_s, NULL);
3992         eloop_cancel_timeout(wpas_p2p_group_idle_timeout, wpa_s, NULL);
3993         wpas_p2p_remove_pending_group_interface(wpa_s);
3994         eloop_cancel_timeout(wpas_p2p_group_freq_conflict, wpa_s, NULL);
3995         wpas_p2p_listen_work_done(wpa_s);
3996         if (wpa_s->p2p_send_action_work) {
3997                 os_free(wpa_s->p2p_send_action_work->ctx);
3998                 radio_work_done(wpa_s->p2p_send_action_work);
3999                 wpa_s->p2p_send_action_work = NULL;
4000         }
4001         eloop_cancel_timeout(wpas_p2p_send_action_work_timeout, wpa_s, NULL);
4002
4003         wpabuf_free(wpa_s->p2p_oob_dev_pw);
4004         wpa_s->p2p_oob_dev_pw = NULL;
4005
4006         /* TODO: remove group interface from the driver if this wpa_s instance
4007          * is on top of a P2P group interface */
4008 }
4009
4010
4011 /**
4012  * wpas_p2p_deinit_global - Deinitialize global P2P module
4013  * @global: Pointer to global data from wpa_supplicant_init()
4014  *
4015  * This function deinitializes the global (per device) P2P module.
4016  */
4017 void wpas_p2p_deinit_global(struct wpa_global *global)
4018 {
4019         struct wpa_supplicant *wpa_s, *tmp;
4020
4021         wpa_s = global->ifaces;
4022         if (wpa_s)
4023                 wpas_p2p_service_flush(wpa_s);
4024
4025         if (global->p2p == NULL)
4026                 return;
4027
4028         /* Remove remaining P2P group interfaces */
4029         while (wpa_s && wpa_s->p2p_group_interface != NOT_P2P_GROUP_INTERFACE)
4030                 wpa_s = wpa_s->next;
4031         while (wpa_s) {
4032                 tmp = global->ifaces;
4033                 while (tmp &&
4034                        (tmp == wpa_s ||
4035                         tmp->p2p_group_interface == NOT_P2P_GROUP_INTERFACE)) {
4036                         tmp = tmp->next;
4037                 }
4038                 if (tmp == NULL)
4039                         break;
4040                 /* Disconnect from the P2P group and deinit the interface */
4041                 wpas_p2p_disconnect(tmp);
4042         }
4043
4044         /*
4045          * Deinit GO data on any possibly remaining interface (if main
4046          * interface is used as GO).
4047          */
4048         for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) {
4049                 if (wpa_s->ap_iface)
4050                         wpas_p2p_group_deinit(wpa_s);
4051         }
4052
4053         p2p_deinit(global->p2p);
4054         global->p2p = NULL;
4055         global->p2p_init_wpa_s = NULL;
4056 }
4057
4058
4059 static int wpas_p2p_create_iface(struct wpa_supplicant *wpa_s)
4060 {
4061         if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_DEDICATED_P2P_DEVICE) &&
4062             wpa_s->conf->p2p_no_group_iface)
4063                 return 0; /* separate interface disabled per configuration */
4064         if (wpa_s->drv_flags &
4065             (WPA_DRIVER_FLAGS_P2P_DEDICATED_INTERFACE |
4066              WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P))
4067                 return 1; /* P2P group requires a new interface in every case
4068                            */
4069         if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_CONCURRENT))
4070                 return 0; /* driver does not support concurrent operations */
4071         if (wpa_s->global->ifaces->next)
4072                 return 1; /* more that one interface already in use */
4073         if (wpa_s->wpa_state >= WPA_AUTHENTICATING)
4074                 return 1; /* this interface is already in use */
4075         return 0;
4076 }
4077
4078
4079 static int wpas_p2p_start_go_neg(struct wpa_supplicant *wpa_s,
4080                                  const u8 *peer_addr,
4081                                  enum p2p_wps_method wps_method,
4082                                  int go_intent, const u8 *own_interface_addr,
4083                                  unsigned int force_freq, int persistent_group,
4084                                  struct wpa_ssid *ssid, unsigned int pref_freq)
4085 {
4086         if (persistent_group && wpa_s->conf->persistent_reconnect)
4087                 persistent_group = 2;
4088
4089         /*
4090          * Increase GO config timeout if HT40 is used since it takes some time
4091          * to scan channels for coex purposes before the BSS can be started.
4092          */
4093         p2p_set_config_timeout(wpa_s->global->p2p,
4094                                wpa_s->p2p_go_ht40 ? 255 : 100, 20);
4095
4096         return p2p_connect(wpa_s->global->p2p, peer_addr, wps_method,
4097                            go_intent, own_interface_addr, force_freq,
4098                            persistent_group, ssid ? ssid->ssid : NULL,
4099                            ssid ? ssid->ssid_len : 0,
4100                            wpa_s->p2p_pd_before_go_neg, pref_freq,
4101                            wps_method == WPS_NFC ? wpa_s->p2p_oob_dev_pw_id :
4102                            0);
4103 }
4104
4105
4106 static int wpas_p2p_auth_go_neg(struct wpa_supplicant *wpa_s,
4107                                 const u8 *peer_addr,
4108                                 enum p2p_wps_method wps_method,
4109                                 int go_intent, const u8 *own_interface_addr,
4110                                 unsigned int force_freq, int persistent_group,
4111                                 struct wpa_ssid *ssid, unsigned int pref_freq)
4112 {
4113         if (persistent_group && wpa_s->conf->persistent_reconnect)
4114                 persistent_group = 2;
4115
4116         return p2p_authorize(wpa_s->global->p2p, peer_addr, wps_method,
4117                              go_intent, own_interface_addr, force_freq,
4118                              persistent_group, ssid ? ssid->ssid : NULL,
4119                              ssid ? ssid->ssid_len : 0, pref_freq,
4120                              wps_method == WPS_NFC ? wpa_s->p2p_oob_dev_pw_id :
4121                              0);
4122 }
4123
4124
4125 static void wpas_p2p_check_join_scan_limit(struct wpa_supplicant *wpa_s)
4126 {
4127         wpa_s->p2p_join_scan_count++;
4128         wpa_printf(MSG_DEBUG, "P2P: Join scan attempt %d",
4129                    wpa_s->p2p_join_scan_count);
4130         if (wpa_s->p2p_join_scan_count > P2P_MAX_JOIN_SCAN_ATTEMPTS) {
4131                 wpa_printf(MSG_DEBUG, "P2P: Failed to find GO " MACSTR
4132                            " for join operationg - stop join attempt",
4133                            MAC2STR(wpa_s->pending_join_iface_addr));
4134                 eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
4135                 if (wpa_s->p2p_auto_pd) {
4136                         wpa_s->p2p_auto_pd = 0;
4137                         wpa_msg_global(wpa_s, MSG_INFO,
4138                                        P2P_EVENT_PROV_DISC_FAILURE
4139                                        " p2p_dev_addr=" MACSTR " status=N/A",
4140                                        MAC2STR(wpa_s->pending_join_dev_addr));
4141                         return;
4142                 }
4143                 wpa_msg_global(wpa_s->parent, MSG_INFO,
4144                                P2P_EVENT_GROUP_FORMATION_FAILURE);
4145         }
4146 }
4147
4148
4149 static int wpas_check_freq_conflict(struct wpa_supplicant *wpa_s, int freq)
4150 {
4151         int res;
4152         unsigned int num, i;
4153         struct wpa_used_freq_data *freqs;
4154
4155         if (wpas_p2p_num_unused_channels(wpa_s) > 0) {
4156                 /* Multiple channels are supported and not all are in use */
4157                 return 0;
4158         }
4159
4160         freqs = os_calloc(wpa_s->num_multichan_concurrent,
4161                           sizeof(struct wpa_used_freq_data));
4162         if (!freqs)
4163                 return 1;
4164
4165         num = wpas_p2p_valid_oper_freqs(wpa_s, freqs,
4166                                         wpa_s->num_multichan_concurrent);
4167
4168         for (i = 0; i < num; i++) {
4169                 if (freqs[i].freq == freq) {
4170                         wpa_printf(MSG_DEBUG, "P2P: Frequency %d MHz in use by another virtual interface and can be used",
4171                                    freq);
4172                         res = 0;
4173                         goto exit_free;
4174                 }
4175         }
4176
4177         wpa_printf(MSG_DEBUG, "P2P: No valid operating frequencies");
4178         res = 1;
4179
4180 exit_free:
4181         os_free(freqs);
4182         return res;
4183 }
4184
4185
4186 static int wpas_p2p_peer_go(struct wpa_supplicant *wpa_s,
4187                             const u8 *peer_dev_addr)
4188 {
4189         struct wpa_bss *bss;
4190         int updated;
4191
4192         bss = wpa_bss_get_p2p_dev_addr(wpa_s, peer_dev_addr);
4193         if (bss == NULL)
4194                 return -1;
4195         if (bss->last_update_idx < wpa_s->bss_update_idx) {
4196                 wpa_printf(MSG_DEBUG, "P2P: Peer BSS entry not updated in the "
4197                            "last scan");
4198                 return 0;
4199         }
4200
4201         updated = os_reltime_before(&wpa_s->p2p_auto_started,
4202                                     &bss->last_update);
4203         wpa_printf(MSG_DEBUG, "P2P: Current BSS entry for peer updated at "
4204                    "%ld.%06ld (%supdated in last scan)",
4205                    bss->last_update.sec, bss->last_update.usec,
4206                    updated ? "": "not ");
4207
4208         return updated;
4209 }
4210
4211
4212 static void wpas_p2p_scan_res_join(struct wpa_supplicant *wpa_s,
4213                                    struct wpa_scan_results *scan_res)
4214 {
4215         struct wpa_bss *bss = NULL;
4216         int freq;
4217         u8 iface_addr[ETH_ALEN];
4218
4219         eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
4220
4221         if (wpa_s->global->p2p_disabled)
4222                 return;
4223
4224         wpa_printf(MSG_DEBUG, "P2P: Scan results received (%d BSS) for %sjoin",
4225                    scan_res ? (int) scan_res->num : -1,
4226                    wpa_s->p2p_auto_join ? "auto_" : "");
4227
4228         if (scan_res)
4229                 wpas_p2p_scan_res_handler(wpa_s, scan_res);
4230
4231         if (wpa_s->p2p_auto_pd) {
4232                 int join = wpas_p2p_peer_go(wpa_s,
4233                                             wpa_s->pending_join_dev_addr);
4234                 if (join == 0 &&
4235                     wpa_s->auto_pd_scan_retry < P2P_AUTO_PD_SCAN_ATTEMPTS) {
4236                         wpa_s->auto_pd_scan_retry++;
4237                         bss = wpa_bss_get_bssid_latest(
4238                                 wpa_s, wpa_s->pending_join_dev_addr);
4239                         if (bss) {
4240                                 freq = bss->freq;
4241                                 wpa_printf(MSG_DEBUG, "P2P: Scan retry %d for "
4242                                            "the peer " MACSTR " at %d MHz",
4243                                            wpa_s->auto_pd_scan_retry,
4244                                            MAC2STR(wpa_s->
4245                                                    pending_join_dev_addr),
4246                                            freq);
4247                                 wpas_p2p_join_scan_req(wpa_s, freq, NULL, 0);
4248                                 return;
4249                         }
4250                 }
4251
4252                 if (join < 0)
4253                         join = 0;
4254
4255                 wpa_s->p2p_auto_pd = 0;
4256                 wpa_s->pending_pd_use = join ? AUTO_PD_JOIN : AUTO_PD_GO_NEG;
4257                 wpa_printf(MSG_DEBUG, "P2P: Auto PD with " MACSTR " join=%d",
4258                            MAC2STR(wpa_s->pending_join_dev_addr), join);
4259                 if (p2p_prov_disc_req(wpa_s->global->p2p,
4260                                       wpa_s->pending_join_dev_addr,
4261                                       wpa_s->pending_pd_config_methods, join,
4262                                       0, wpa_s->user_initiated_pd) < 0) {
4263                         wpa_s->p2p_auto_pd = 0;
4264                         wpa_msg_global(wpa_s, MSG_INFO,
4265                                        P2P_EVENT_PROV_DISC_FAILURE
4266                                        " p2p_dev_addr=" MACSTR " status=N/A",
4267                                        MAC2STR(wpa_s->pending_join_dev_addr));
4268                 }
4269                 return;
4270         }
4271
4272         if (wpa_s->p2p_auto_join) {
4273                 int join = wpas_p2p_peer_go(wpa_s,
4274                                             wpa_s->pending_join_dev_addr);
4275                 if (join < 0) {
4276                         wpa_printf(MSG_DEBUG, "P2P: Peer was not found to be "
4277                                    "running a GO -> use GO Negotiation");
4278                         wpas_p2p_connect(wpa_s, wpa_s->pending_join_dev_addr,
4279                                          wpa_s->p2p_pin, wpa_s->p2p_wps_method,
4280                                          wpa_s->p2p_persistent_group, 0, 0, 0,
4281                                          wpa_s->p2p_go_intent,
4282                                          wpa_s->p2p_connect_freq,
4283                                          wpa_s->p2p_persistent_id,
4284                                          wpa_s->p2p_pd_before_go_neg,
4285                                          wpa_s->p2p_go_ht40,
4286                                          wpa_s->p2p_go_vht);
4287                         return;
4288                 }
4289
4290                 wpa_printf(MSG_DEBUG, "P2P: Peer was found running GO%s -> "
4291                            "try to join the group", join ? "" :
4292                            " in older scan");
4293                 if (!join)
4294                         wpa_s->p2p_fallback_to_go_neg = 1;
4295         }
4296
4297         freq = p2p_get_oper_freq(wpa_s->global->p2p,
4298                                  wpa_s->pending_join_iface_addr);
4299         if (freq < 0 &&
4300             p2p_get_interface_addr(wpa_s->global->p2p,
4301                                    wpa_s->pending_join_dev_addr,
4302                                    iface_addr) == 0 &&
4303             os_memcmp(iface_addr, wpa_s->pending_join_dev_addr, ETH_ALEN) != 0)
4304         {
4305                 wpa_printf(MSG_DEBUG, "P2P: Overwrite pending interface "
4306                            "address for join from " MACSTR " to " MACSTR
4307                            " based on newly discovered P2P peer entry",
4308                            MAC2STR(wpa_s->pending_join_iface_addr),
4309                            MAC2STR(iface_addr));
4310                 os_memcpy(wpa_s->pending_join_iface_addr, iface_addr,
4311                           ETH_ALEN);
4312
4313                 freq = p2p_get_oper_freq(wpa_s->global->p2p,
4314                                          wpa_s->pending_join_iface_addr);
4315         }
4316         if (freq >= 0) {
4317                 wpa_printf(MSG_DEBUG, "P2P: Target GO operating frequency "
4318                            "from P2P peer table: %d MHz", freq);
4319         }
4320         if (wpa_s->p2p_join_ssid_len) {
4321                 wpa_printf(MSG_DEBUG, "P2P: Trying to find target GO BSS entry based on BSSID "
4322                            MACSTR " and SSID %s",
4323                            MAC2STR(wpa_s->pending_join_iface_addr),
4324                            wpa_ssid_txt(wpa_s->p2p_join_ssid,
4325                                         wpa_s->p2p_join_ssid_len));
4326                 bss = wpa_bss_get(wpa_s, wpa_s->pending_join_iface_addr,
4327                                   wpa_s->p2p_join_ssid,
4328                                   wpa_s->p2p_join_ssid_len);
4329         }
4330         if (!bss) {
4331                 wpa_printf(MSG_DEBUG, "P2P: Trying to find target GO BSS entry based on BSSID "
4332                            MACSTR, MAC2STR(wpa_s->pending_join_iface_addr));
4333                 bss = wpa_bss_get_bssid_latest(wpa_s,
4334                                                wpa_s->pending_join_iface_addr);
4335         }
4336         if (bss) {
4337                 freq = bss->freq;
4338                 wpa_printf(MSG_DEBUG, "P2P: Target GO operating frequency "
4339                            "from BSS table: %d MHz (SSID %s)", freq,
4340                            wpa_ssid_txt(bss->ssid, bss->ssid_len));
4341         }
4342         if (freq > 0) {
4343                 u16 method;
4344
4345                 if (wpas_check_freq_conflict(wpa_s, freq) > 0) {
4346                         wpa_msg_global(wpa_s->parent, MSG_INFO,
4347                                        P2P_EVENT_GROUP_FORMATION_FAILURE
4348                                        "reason=FREQ_CONFLICT");
4349                         return;
4350                 }
4351
4352                 wpa_printf(MSG_DEBUG, "P2P: Send Provision Discovery Request "
4353                            "prior to joining an existing group (GO " MACSTR
4354                            " freq=%u MHz)",
4355                            MAC2STR(wpa_s->pending_join_dev_addr), freq);
4356                 wpa_s->pending_pd_before_join = 1;
4357
4358                 switch (wpa_s->pending_join_wps_method) {
4359                 case WPS_PIN_DISPLAY:
4360                         method = WPS_CONFIG_KEYPAD;
4361                         break;
4362                 case WPS_PIN_KEYPAD:
4363                         method = WPS_CONFIG_DISPLAY;
4364                         break;
4365                 case WPS_PBC:
4366                         method = WPS_CONFIG_PUSHBUTTON;
4367                         break;
4368                 default:
4369                         method = 0;
4370                         break;
4371                 }
4372
4373                 if ((p2p_get_provisioning_info(wpa_s->global->p2p,
4374                                                wpa_s->pending_join_dev_addr) ==
4375                      method)) {
4376                         /*
4377                          * We have already performed provision discovery for
4378                          * joining the group. Proceed directly to join
4379                          * operation without duplicated provision discovery. */
4380                         wpa_printf(MSG_DEBUG, "P2P: Provision discovery "
4381                                    "with " MACSTR " already done - proceed to "
4382                                    "join",
4383                                    MAC2STR(wpa_s->pending_join_dev_addr));
4384                         wpa_s->pending_pd_before_join = 0;
4385                         goto start;
4386                 }
4387
4388                 if (p2p_prov_disc_req(wpa_s->global->p2p,
4389                                       wpa_s->pending_join_dev_addr, method, 1,
4390                                       freq, wpa_s->user_initiated_pd) < 0) {
4391                         wpa_printf(MSG_DEBUG, "P2P: Failed to send Provision "
4392                                    "Discovery Request before joining an "
4393                                    "existing group");
4394                         wpa_s->pending_pd_before_join = 0;
4395                         goto start;
4396                 }
4397                 return;
4398         }
4399
4400         wpa_printf(MSG_DEBUG, "P2P: Failed to find BSS/GO - try again later");
4401         eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
4402         eloop_register_timeout(1, 0, wpas_p2p_join_scan, wpa_s, NULL);
4403         wpas_p2p_check_join_scan_limit(wpa_s);
4404         return;
4405
4406 start:
4407         /* Start join operation immediately */
4408         wpas_p2p_join_start(wpa_s, 0, NULL, 0);
4409 }
4410
4411
4412 static void wpas_p2p_join_scan_req(struct wpa_supplicant *wpa_s, int freq,
4413                                    const u8 *ssid, size_t ssid_len)
4414 {
4415         int ret;
4416         struct wpa_driver_scan_params params;
4417         struct wpabuf *wps_ie, *ies;
4418         size_t ielen;
4419         int freqs[2] = { 0, 0 };
4420
4421         os_memset(&params, 0, sizeof(params));
4422
4423         /* P2P Wildcard SSID */
4424         params.num_ssids = 1;
4425         if (ssid && ssid_len) {
4426                 params.ssids[0].ssid = ssid;
4427                 params.ssids[0].ssid_len = ssid_len;
4428                 os_memcpy(wpa_s->p2p_join_ssid, ssid, ssid_len);
4429                 wpa_s->p2p_join_ssid_len = ssid_len;
4430         } else {
4431                 params.ssids[0].ssid = (u8 *) P2P_WILDCARD_SSID;
4432                 params.ssids[0].ssid_len = P2P_WILDCARD_SSID_LEN;
4433                 wpa_s->p2p_join_ssid_len = 0;
4434         }
4435
4436         wpa_s->wps->dev.p2p = 1;
4437         wps_ie = wps_build_probe_req_ie(DEV_PW_DEFAULT, &wpa_s->wps->dev,
4438                                         wpa_s->wps->uuid, WPS_REQ_ENROLLEE, 0,
4439                                         NULL);
4440         if (wps_ie == NULL) {
4441                 wpas_p2p_scan_res_join(wpa_s, NULL);
4442                 return;
4443         }
4444
4445         ielen = p2p_scan_ie_buf_len(wpa_s->global->p2p);
4446         ies = wpabuf_alloc(wpabuf_len(wps_ie) + ielen);
4447         if (ies == NULL) {
4448                 wpabuf_free(wps_ie);
4449                 wpas_p2p_scan_res_join(wpa_s, NULL);
4450                 return;
4451         }
4452         wpabuf_put_buf(ies, wps_ie);
4453         wpabuf_free(wps_ie);
4454
4455         p2p_scan_ie(wpa_s->global->p2p, ies, NULL);
4456
4457         params.p2p_probe = 1;
4458         params.extra_ies = wpabuf_head(ies);
4459         params.extra_ies_len = wpabuf_len(ies);
4460
4461         if (!freq) {
4462                 int oper_freq;
4463                 /*
4464                  * If freq is not provided, check the operating freq of the GO
4465                  * and use a single channel scan on if possible.
4466                  */
4467                 oper_freq = p2p_get_oper_freq(wpa_s->global->p2p,
4468                                               wpa_s->pending_join_iface_addr);
4469                 if (oper_freq > 0)
4470                         freq = oper_freq;
4471         }
4472         if (freq > 0) {
4473                 freqs[0] = freq;
4474                 params.freqs = freqs;
4475         }
4476
4477         /*
4478          * Run a scan to update BSS table and start Provision Discovery once
4479          * the new scan results become available.
4480          */
4481         ret = wpa_drv_scan(wpa_s, &params);
4482         if (!ret) {
4483                 os_get_reltime(&wpa_s->scan_trigger_time);
4484                 wpa_s->scan_res_handler = wpas_p2p_scan_res_join;
4485                 wpa_s->own_scan_requested = 1;
4486         }
4487
4488         wpabuf_free(ies);
4489
4490         if (ret) {
4491                 wpa_printf(MSG_DEBUG, "P2P: Failed to start scan for join - "
4492                            "try again later");
4493                 eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
4494                 eloop_register_timeout(1, 0, wpas_p2p_join_scan, wpa_s, NULL);
4495                 wpas_p2p_check_join_scan_limit(wpa_s);
4496         }
4497 }
4498
4499
4500 static void wpas_p2p_join_scan(void *eloop_ctx, void *timeout_ctx)
4501 {
4502         struct wpa_supplicant *wpa_s = eloop_ctx;
4503         wpas_p2p_join_scan_req(wpa_s, 0, NULL, 0);
4504 }
4505
4506
4507 static int wpas_p2p_join(struct wpa_supplicant *wpa_s, const u8 *iface_addr,
4508                          const u8 *dev_addr, enum p2p_wps_method wps_method,
4509                          int auto_join, int op_freq,
4510                          const u8 *ssid, size_t ssid_len)
4511 {
4512         wpa_printf(MSG_DEBUG, "P2P: Request to join existing group (iface "
4513                    MACSTR " dev " MACSTR " op_freq=%d)%s",
4514                    MAC2STR(iface_addr), MAC2STR(dev_addr), op_freq,
4515                    auto_join ? " (auto_join)" : "");
4516         if (ssid && ssid_len) {
4517                 wpa_printf(MSG_DEBUG, "P2P: Group SSID specified: %s",
4518                            wpa_ssid_txt(ssid, ssid_len));
4519         }
4520
4521         wpa_s->p2p_auto_pd = 0;
4522         wpa_s->p2p_auto_join = !!auto_join;
4523         os_memcpy(wpa_s->pending_join_iface_addr, iface_addr, ETH_ALEN);
4524         os_memcpy(wpa_s->pending_join_dev_addr, dev_addr, ETH_ALEN);
4525         wpa_s->pending_join_wps_method = wps_method;
4526
4527         /* Make sure we are not running find during connection establishment */
4528         wpas_p2p_stop_find(wpa_s);
4529
4530         wpa_s->p2p_join_scan_count = 0;
4531         wpas_p2p_join_scan_req(wpa_s, op_freq, ssid, ssid_len);
4532         return 0;
4533 }
4534
4535
4536 static int wpas_p2p_join_start(struct wpa_supplicant *wpa_s, int freq,
4537                                const u8 *ssid, size_t ssid_len)
4538 {
4539         struct wpa_supplicant *group;
4540         struct p2p_go_neg_results res;
4541         struct wpa_bss *bss;
4542
4543         group = wpas_p2p_get_group_iface(wpa_s, 0, 0);
4544         if (group == NULL)
4545                 return -1;
4546         if (group != wpa_s) {
4547                 os_memcpy(group->p2p_pin, wpa_s->p2p_pin,
4548                           sizeof(group->p2p_pin));
4549                 group->p2p_wps_method = wpa_s->p2p_wps_method;
4550         } else {
4551                 /*
4552                  * Need to mark the current interface for p2p_group_formation
4553                  * when a separate group interface is not used. This is needed
4554                  * to allow p2p_cancel stop a pending p2p_connect-join.
4555                  * wpas_p2p_init_group_interface() addresses this for the case
4556                  * where a separate group interface is used.
4557                  */
4558                 wpa_s->global->p2p_group_formation = wpa_s;
4559         }
4560
4561         group->p2p_in_provisioning = 1;
4562         group->p2p_fallback_to_go_neg = wpa_s->p2p_fallback_to_go_neg;
4563
4564         os_memset(&res, 0, sizeof(res));
4565         os_memcpy(res.peer_device_addr, wpa_s->pending_join_dev_addr, ETH_ALEN);
4566         os_memcpy(res.peer_interface_addr, wpa_s->pending_join_iface_addr,
4567                   ETH_ALEN);
4568         res.wps_method = wpa_s->pending_join_wps_method;
4569         if (freq && ssid && ssid_len) {
4570                 res.freq = freq;
4571                 res.ssid_len = ssid_len;
4572                 os_memcpy(res.ssid, ssid, ssid_len);
4573         } else {
4574                 bss = wpa_bss_get_bssid_latest(wpa_s,
4575                                                wpa_s->pending_join_iface_addr);
4576                 if (bss) {
4577                         res.freq = bss->freq;
4578                         res.ssid_len = bss->ssid_len;
4579                         os_memcpy(res.ssid, bss->ssid, bss->ssid_len);
4580                         wpa_printf(MSG_DEBUG, "P2P: Join target GO operating frequency from BSS table: %d MHz (SSID %s)",
4581                                    bss->freq,
4582                                    wpa_ssid_txt(bss->ssid, bss->ssid_len));
4583                 }
4584         }
4585
4586         if (wpa_s->off_channel_freq || wpa_s->roc_waiting_drv_freq) {
4587                 wpa_printf(MSG_DEBUG, "P2P: Cancel remain-on-channel prior to "
4588                            "starting client");
4589                 wpa_drv_cancel_remain_on_channel(wpa_s);
4590                 wpa_s->off_channel_freq = 0;
4591                 wpa_s->roc_waiting_drv_freq = 0;
4592         }
4593         wpas_start_wps_enrollee(group, &res);
4594
4595         /*
4596          * Allow a longer timeout for join-a-running-group than normal 15
4597          * second group formation timeout since the GO may not have authorized
4598          * our connection yet.
4599          */
4600         eloop_cancel_timeout(wpas_p2p_group_formation_timeout, wpa_s, NULL);
4601         eloop_register_timeout(60, 0, wpas_p2p_group_formation_timeout,
4602                                wpa_s, NULL);
4603
4604         return 0;
4605 }
4606
4607
4608 static int wpas_p2p_setup_freqs(struct wpa_supplicant *wpa_s, int freq,
4609                                 int *force_freq, int *pref_freq, int go)
4610 {
4611         struct wpa_used_freq_data *freqs;
4612         int res, best_freq, num_unused;
4613         unsigned int freq_in_use = 0, num, i;
4614
4615         freqs = os_calloc(wpa_s->num_multichan_concurrent,
4616                           sizeof(struct wpa_used_freq_data));
4617         if (!freqs)
4618                 return -1;
4619
4620         num = wpas_p2p_valid_oper_freqs(wpa_s, freqs,
4621                                         wpa_s->num_multichan_concurrent);
4622
4623         /*
4624          * It is possible that the total number of used frequencies is bigger
4625          * than the number of frequencies used for P2P, so get the system wide
4626          * number of unused frequencies.
4627          */
4628         num_unused = wpas_p2p_num_unused_channels(wpa_s);
4629
4630         wpa_printf(MSG_DEBUG,
4631                    "P2P: Setup freqs: freq=%d num_MCC=%d shared_freqs=%u num_unused=%d",
4632                    freq, wpa_s->num_multichan_concurrent, num, num_unused);
4633
4634         if (freq > 0) {
4635                 int ret;
4636                 if (go)
4637                         ret = p2p_supported_freq(wpa_s->global->p2p, freq);
4638                 else
4639                         ret = p2p_supported_freq_cli(wpa_s->global->p2p, freq);
4640                 if (!ret) {
4641                         wpa_printf(MSG_DEBUG, "P2P: The forced channel "
4642                                    "(%u MHz) is not supported for P2P uses",
4643                                    freq);
4644                         res = -3;
4645                         goto exit_free;
4646                 }
4647
4648                 for (i = 0; i < num; i++) {
4649                         if (freqs[i].freq == freq)
4650                                 freq_in_use = 1;
4651                 }
4652
4653                 if (num_unused <= 0 && !freq_in_use) {
4654                         wpa_printf(MSG_DEBUG, "P2P: Cannot start P2P group on %u MHz as there are no available channels",
4655                                    freq);
4656                         res = -2;
4657                         goto exit_free;
4658                 }
4659                 wpa_printf(MSG_DEBUG, "P2P: Trying to force us to use the "
4660                            "requested channel (%u MHz)", freq);
4661                 *force_freq = freq;
4662                 goto exit_ok;
4663         }
4664
4665         best_freq = wpas_p2p_pick_best_used_freq(wpa_s, freqs, num);
4666
4667         /* We have a candidate frequency to use */
4668         if (best_freq > 0) {
4669                 if (*pref_freq == 0 && num_unused > 0) {
4670                         wpa_printf(MSG_DEBUG, "P2P: Try to prefer a frequency (%u MHz) we are already using",
4671                                    best_freq);
4672                         *pref_freq = best_freq;
4673                 } else {
4674                         wpa_printf(MSG_DEBUG, "P2P: Try to force us to use frequency (%u MHz) which is already in use",
4675                                    best_freq);
4676                         *force_freq = best_freq;
4677                 }
4678         } else if (num_unused > 0) {
4679                 wpa_printf(MSG_DEBUG,
4680                            "P2P: Current operating channels are not available for P2P. Try to use another channel");
4681                 *force_freq = 0;
4682         } else {
4683                 wpa_printf(MSG_DEBUG,
4684                            "P2P: All channels are in use and none of them are P2P enabled. Cannot start P2P group");
4685                 res = -2;
4686                 goto exit_free;
4687         }
4688
4689 exit_ok:
4690         res = 0;
4691 exit_free:
4692         os_free(freqs);
4693         return res;
4694 }
4695
4696
4697 /**
4698  * wpas_p2p_connect - Request P2P Group Formation to be started
4699  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
4700  * @peer_addr: Address of the peer P2P Device
4701  * @pin: PIN to use during provisioning or %NULL to indicate PBC mode
4702  * @persistent_group: Whether to create a persistent group
4703  * @auto_join: Whether to select join vs. GO Negotiation automatically
4704  * @join: Whether to join an existing group (as a client) instead of starting
4705  *      Group Owner negotiation; @peer_addr is BSSID in that case
4706  * @auth: Whether to only authorize the connection instead of doing that and
4707  *      initiating Group Owner negotiation
4708  * @go_intent: GO Intent or -1 to use default
4709  * @freq: Frequency for the group or 0 for auto-selection
4710  * @persistent_id: Persistent group credentials to use for forcing GO
4711  *      parameters or -1 to generate new values (SSID/passphrase)
4712  * @pd: Whether to send Provision Discovery prior to GO Negotiation as an
4713  *      interoperability workaround when initiating group formation
4714  * @ht40: Start GO with 40 MHz channel width
4715  * @vht:  Start GO with VHT support
4716  * Returns: 0 or new PIN (if pin was %NULL) on success, -1 on unspecified
4717  *      failure, -2 on failure due to channel not currently available,
4718  *      -3 if forced channel is not supported
4719  */
4720 int wpas_p2p_connect(struct wpa_supplicant *wpa_s, const u8 *peer_addr,
4721                      const char *pin, enum p2p_wps_method wps_method,
4722                      int persistent_group, int auto_join, int join, int auth,
4723                      int go_intent, int freq, int persistent_id, int pd,
4724                      int ht40, int vht)
4725 {
4726         int force_freq = 0, pref_freq = 0;
4727         int ret = 0, res;
4728         enum wpa_driver_if_type iftype;
4729         const u8 *if_addr;
4730         struct wpa_ssid *ssid = NULL;
4731
4732         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
4733                 return -1;
4734
4735         if (persistent_id >= 0) {
4736                 ssid = wpa_config_get_network(wpa_s->conf, persistent_id);
4737                 if (ssid == NULL || ssid->disabled != 2 ||
4738                     ssid->mode != WPAS_MODE_P2P_GO)
4739                         return -1;
4740         }
4741
4742         os_free(wpa_s->global->add_psk);
4743         wpa_s->global->add_psk = NULL;
4744
4745         wpa_s->global->p2p_fail_on_wps_complete = 0;
4746
4747         if (go_intent < 0)
4748                 go_intent = wpa_s->conf->p2p_go_intent;
4749
4750         if (!auth)
4751                 wpa_s->p2p_long_listen = 0;
4752
4753         wpa_s->p2p_wps_method = wps_method;
4754         wpa_s->p2p_persistent_group = !!persistent_group;
4755         wpa_s->p2p_persistent_id = persistent_id;
4756         wpa_s->p2p_go_intent = go_intent;
4757         wpa_s->p2p_connect_freq = freq;
4758         wpa_s->p2p_fallback_to_go_neg = 0;
4759         wpa_s->p2p_pd_before_go_neg = !!pd;
4760         wpa_s->p2p_go_ht40 = !!ht40;
4761         wpa_s->p2p_go_vht = !!vht;
4762
4763         if (pin)
4764                 os_strlcpy(wpa_s->p2p_pin, pin, sizeof(wpa_s->p2p_pin));
4765         else if (wps_method == WPS_PIN_DISPLAY) {
4766                 ret = wps_generate_pin();
4767                 os_snprintf(wpa_s->p2p_pin, sizeof(wpa_s->p2p_pin), "%08d",
4768                             ret);
4769                 wpa_printf(MSG_DEBUG, "P2P: Randomly generated PIN: %s",
4770                            wpa_s->p2p_pin);
4771         } else
4772                 wpa_s->p2p_pin[0] = '\0';
4773
4774         if (join || auto_join) {
4775                 u8 iface_addr[ETH_ALEN], dev_addr[ETH_ALEN];
4776                 if (auth) {
4777                         wpa_printf(MSG_DEBUG, "P2P: Authorize invitation to "
4778                                    "connect a running group from " MACSTR,
4779                                    MAC2STR(peer_addr));
4780                         os_memcpy(wpa_s->p2p_auth_invite, peer_addr, ETH_ALEN);
4781                         return ret;
4782                 }
4783                 os_memcpy(dev_addr, peer_addr, ETH_ALEN);
4784                 if (p2p_get_interface_addr(wpa_s->global->p2p, peer_addr,
4785                                            iface_addr) < 0) {
4786                         os_memcpy(iface_addr, peer_addr, ETH_ALEN);
4787                         p2p_get_dev_addr(wpa_s->global->p2p, peer_addr,
4788                                          dev_addr);
4789                 }
4790                 if (auto_join) {
4791                         os_get_reltime(&wpa_s->p2p_auto_started);
4792                         wpa_printf(MSG_DEBUG, "P2P: Auto join started at "
4793                                    "%ld.%06ld",
4794                                    wpa_s->p2p_auto_started.sec,
4795                                    wpa_s->p2p_auto_started.usec);
4796                 }
4797                 wpa_s->user_initiated_pd = 1;
4798                 if (wpas_p2p_join(wpa_s, iface_addr, dev_addr, wps_method,
4799                                   auto_join, freq, NULL, 0) < 0)
4800                         return -1;
4801                 return ret;
4802         }
4803
4804         res = wpas_p2p_setup_freqs(wpa_s, freq, &force_freq, &pref_freq,
4805                                    go_intent == 15);
4806         if (res)
4807                 return res;
4808         wpas_p2p_set_own_freq_preference(wpa_s,
4809                                          force_freq ? force_freq : pref_freq);
4810
4811         wpa_s->create_p2p_iface = wpas_p2p_create_iface(wpa_s);
4812
4813         if (wpa_s->create_p2p_iface) {
4814                 /* Prepare to add a new interface for the group */
4815                 iftype = WPA_IF_P2P_GROUP;
4816                 if (go_intent == 15)
4817                         iftype = WPA_IF_P2P_GO;
4818                 if (wpas_p2p_add_group_interface(wpa_s, iftype) < 0) {
4819                         wpa_printf(MSG_ERROR, "P2P: Failed to allocate a new "
4820                                    "interface for the group");
4821                         return -1;
4822                 }
4823
4824                 if_addr = wpa_s->pending_interface_addr;
4825         } else
4826                 if_addr = wpa_s->own_addr;
4827
4828         if (auth) {
4829                 if (wpas_p2p_auth_go_neg(wpa_s, peer_addr, wps_method,
4830                                          go_intent, if_addr,
4831                                          force_freq, persistent_group, ssid,
4832                                          pref_freq) < 0)
4833                         return -1;
4834                 return ret;
4835         }
4836
4837         if (wpas_p2p_start_go_neg(wpa_s, peer_addr, wps_method,
4838                                   go_intent, if_addr, force_freq,
4839                                   persistent_group, ssid, pref_freq) < 0) {
4840                 if (wpa_s->create_p2p_iface)
4841                         wpas_p2p_remove_pending_group_interface(wpa_s);
4842                 return -1;
4843         }
4844         return ret;
4845 }
4846
4847
4848 /**
4849  * wpas_p2p_remain_on_channel_cb - Indication of remain-on-channel start
4850  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
4851  * @freq: Frequency of the channel in MHz
4852  * @duration: Duration of the stay on the channel in milliseconds
4853  *
4854  * This callback is called when the driver indicates that it has started the
4855  * requested remain-on-channel duration.
4856  */
4857 void wpas_p2p_remain_on_channel_cb(struct wpa_supplicant *wpa_s,
4858                                    unsigned int freq, unsigned int duration)
4859 {
4860         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
4861                 return;
4862         if (wpa_s->off_channel_freq == wpa_s->pending_listen_freq) {
4863                 p2p_listen_cb(wpa_s->global->p2p, wpa_s->pending_listen_freq,
4864                               wpa_s->pending_listen_duration);
4865                 wpa_s->pending_listen_freq = 0;
4866         } else {
4867                 wpa_printf(MSG_DEBUG, "P2P: Ignore remain-on-channel callback (off_channel_freq=%u pending_listen_freq=%d freq=%u duration=%u)",
4868                            wpa_s->off_channel_freq, wpa_s->pending_listen_freq,
4869                            freq, duration);
4870         }
4871 }
4872
4873
4874 static int wpas_p2p_listen_start(struct wpa_supplicant *wpa_s,
4875                                  unsigned int timeout)
4876 {
4877         /* Limit maximum Listen state time based on driver limitation. */
4878         if (timeout > wpa_s->max_remain_on_chan)
4879                 timeout = wpa_s->max_remain_on_chan;
4880
4881         return p2p_listen(wpa_s->global->p2p, timeout);
4882 }
4883
4884
4885 /**
4886  * wpas_p2p_cancel_remain_on_channel_cb - Remain-on-channel timeout
4887  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
4888  * @freq: Frequency of the channel in MHz
4889  *
4890  * This callback is called when the driver indicates that a remain-on-channel
4891  * operation has been completed, i.e., the duration on the requested channel
4892  * has timed out.
4893  */
4894 void wpas_p2p_cancel_remain_on_channel_cb(struct wpa_supplicant *wpa_s,
4895                                           unsigned int freq)
4896 {
4897         wpa_printf(MSG_DEBUG, "P2P: Cancel remain-on-channel callback "
4898                    "(p2p_long_listen=%d ms pending_action_tx=%p)",
4899                    wpa_s->p2p_long_listen, offchannel_pending_action_tx(wpa_s));
4900         wpas_p2p_listen_work_done(wpa_s);
4901         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
4902                 return;
4903         if (p2p_listen_end(wpa_s->global->p2p, freq) > 0)
4904                 return; /* P2P module started a new operation */
4905         if (offchannel_pending_action_tx(wpa_s))
4906                 return;
4907         if (wpa_s->p2p_long_listen > 0)
4908                 wpa_s->p2p_long_listen -= wpa_s->max_remain_on_chan;
4909         if (wpa_s->p2p_long_listen > 0) {
4910                 wpa_printf(MSG_DEBUG, "P2P: Continuing long Listen state");
4911                 wpas_p2p_listen_start(wpa_s, wpa_s->p2p_long_listen);
4912         } else {
4913                 /*
4914                  * When listen duration is over, stop listen & update p2p_state
4915                  * to IDLE.
4916                  */
4917                 p2p_stop_listen(wpa_s->global->p2p);
4918         }
4919 }
4920
4921
4922 /**
4923  * wpas_p2p_group_remove - Remove a P2P group
4924  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
4925  * @ifname: Network interface name of the group interface or "*" to remove all
4926  *      groups
4927  * Returns: 0 on success, -1 on failure
4928  *
4929  * This function is used to remove a P2P group. This can be used to disconnect
4930  * from a group in which the local end is a P2P Client or to end a P2P Group in
4931  * case the local end is the Group Owner. If a virtual network interface was
4932  * created for this group, that interface will be removed. Otherwise, only the
4933  * configured P2P group network will be removed from the interface.
4934  */
4935 int wpas_p2p_group_remove(struct wpa_supplicant *wpa_s, const char *ifname)
4936 {
4937         struct wpa_global *global = wpa_s->global;
4938
4939         if (os_strcmp(ifname, "*") == 0) {
4940                 struct wpa_supplicant *prev;
4941                 wpa_s = global->ifaces;
4942                 while (wpa_s) {
4943                         prev = wpa_s;
4944                         wpa_s = wpa_s->next;
4945                         if (prev->p2p_group_interface !=
4946                             NOT_P2P_GROUP_INTERFACE ||
4947                             (prev->current_ssid &&
4948                              prev->current_ssid->p2p_group))
4949                                 wpas_p2p_disconnect(prev);
4950                 }
4951                 return 0;
4952         }
4953
4954         for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) {
4955                 if (os_strcmp(wpa_s->ifname, ifname) == 0)
4956                         break;
4957         }
4958
4959         return wpas_p2p_disconnect(wpa_s);
4960 }
4961
4962
4963 static int wpas_p2p_select_go_freq(struct wpa_supplicant *wpa_s, int freq)
4964 {
4965         unsigned int r;
4966
4967         if (freq == 2) {
4968                 wpa_printf(MSG_DEBUG, "P2P: Request to start GO on 2.4 GHz "
4969                            "band");
4970                 if (wpa_s->best_24_freq > 0 &&
4971                     p2p_supported_freq_go(wpa_s->global->p2p,
4972                                           wpa_s->best_24_freq)) {
4973                         freq = wpa_s->best_24_freq;
4974                         wpa_printf(MSG_DEBUG, "P2P: Use best 2.4 GHz band "
4975                                    "channel: %d MHz", freq);
4976                 } else {
4977                         os_get_random((u8 *) &r, sizeof(r));
4978                         freq = 2412 + (r % 3) * 25;
4979                         wpa_printf(MSG_DEBUG, "P2P: Use random 2.4 GHz band "
4980                                    "channel: %d MHz", freq);
4981                 }
4982         }
4983
4984         if (freq == 5) {
4985                 wpa_printf(MSG_DEBUG, "P2P: Request to start GO on 5 GHz "
4986                            "band");
4987                 if (wpa_s->best_5_freq > 0 &&
4988                     p2p_supported_freq_go(wpa_s->global->p2p,
4989                                        wpa_s->best_5_freq)) {
4990                         freq = wpa_s->best_5_freq;
4991                         wpa_printf(MSG_DEBUG, "P2P: Use best 5 GHz band "
4992                                    "channel: %d MHz", freq);
4993                 } else {
4994                         os_get_random((u8 *) &r, sizeof(r));
4995                         freq = 5180 + (r % 4) * 20;
4996                         if (!p2p_supported_freq_go(wpa_s->global->p2p, freq)) {
4997                                 wpa_printf(MSG_DEBUG, "P2P: Could not select "
4998                                            "5 GHz channel for P2P group");
4999                                 return -1;
5000                         }
5001                         wpa_printf(MSG_DEBUG, "P2P: Use random 5 GHz band "
5002                                    "channel: %d MHz", freq);
5003                 }
5004         }
5005
5006         if (freq > 0 && !p2p_supported_freq_go(wpa_s->global->p2p, freq)) {
5007                 wpa_printf(MSG_DEBUG, "P2P: The forced channel for GO "
5008                            "(%u MHz) is not supported for P2P uses",
5009                            freq);
5010                 return -1;
5011         }
5012
5013         return freq;
5014 }
5015
5016
5017 static int wpas_p2p_init_go_params(struct wpa_supplicant *wpa_s,
5018                                    struct p2p_go_neg_results *params,
5019                                    int freq, int ht40, int vht,
5020                                    const struct p2p_channels *channels)
5021 {
5022         struct wpa_used_freq_data *freqs;
5023         unsigned int pref_freq, cand_freq;
5024         unsigned int num, i;
5025
5026         os_memset(params, 0, sizeof(*params));
5027         params->role_go = 1;
5028         params->ht40 = ht40;
5029         params->vht = vht;
5030         if (freq) {
5031                 if (!freq_included(channels, freq)) {
5032                         wpa_printf(MSG_DEBUG, "P2P: Forced GO freq %d MHz not "
5033                                    "accepted", freq);
5034                         return -1;
5035                 }
5036                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on forced "
5037                            "frequency %d MHz", freq);
5038                 params->freq = freq;
5039         } else if (wpa_s->conf->p2p_oper_reg_class == 81 &&
5040                    wpa_s->conf->p2p_oper_channel >= 1 &&
5041                    wpa_s->conf->p2p_oper_channel <= 11 &&
5042                    freq_included(channels,
5043                                  2407 + 5 * wpa_s->conf->p2p_oper_channel)) {
5044                 params->freq = 2407 + 5 * wpa_s->conf->p2p_oper_channel;
5045                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on configured "
5046                            "frequency %d MHz", params->freq);
5047         } else if ((wpa_s->conf->p2p_oper_reg_class == 115 ||
5048                     wpa_s->conf->p2p_oper_reg_class == 116 ||
5049                     wpa_s->conf->p2p_oper_reg_class == 117 ||
5050                     wpa_s->conf->p2p_oper_reg_class == 124 ||
5051                     wpa_s->conf->p2p_oper_reg_class == 126 ||
5052                     wpa_s->conf->p2p_oper_reg_class == 127) &&
5053                    freq_included(channels,
5054                                  5000 + 5 * wpa_s->conf->p2p_oper_channel)) {
5055                 params->freq = 5000 + 5 * wpa_s->conf->p2p_oper_channel;
5056                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on configured "
5057                            "frequency %d MHz", params->freq);
5058         } else if (wpa_s->conf->p2p_oper_channel == 0 &&
5059                    wpa_s->best_overall_freq > 0 &&
5060                    p2p_supported_freq_go(wpa_s->global->p2p,
5061                                          wpa_s->best_overall_freq) &&
5062                    freq_included(channels, wpa_s->best_overall_freq)) {
5063                 params->freq = wpa_s->best_overall_freq;
5064                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on best overall "
5065                            "channel %d MHz", params->freq);
5066         } else if (wpa_s->conf->p2p_oper_channel == 0 &&
5067                    wpa_s->best_24_freq > 0 &&
5068                    p2p_supported_freq_go(wpa_s->global->p2p,
5069                                          wpa_s->best_24_freq) &&
5070                    freq_included(channels, wpa_s->best_24_freq)) {
5071                 params->freq = wpa_s->best_24_freq;
5072                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on best 2.4 GHz "
5073                            "channel %d MHz", params->freq);
5074         } else if (wpa_s->conf->p2p_oper_channel == 0 &&
5075                    wpa_s->best_5_freq > 0 &&
5076                    p2p_supported_freq_go(wpa_s->global->p2p,
5077                                          wpa_s->best_5_freq) &&
5078                    freq_included(channels, wpa_s->best_5_freq)) {
5079                 params->freq = wpa_s->best_5_freq;
5080                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq based on best 5 GHz "
5081                            "channel %d MHz", params->freq);
5082         } else if ((pref_freq = p2p_get_pref_freq(wpa_s->global->p2p,
5083                                                   channels))) {
5084                 params->freq = pref_freq;
5085                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq %d MHz from preferred "
5086                            "channels", params->freq);
5087         } else {
5088                 int chan;
5089                 for (chan = 0; chan < 11; chan++) {
5090                         params->freq = 2412 + chan * 5;
5091                         if (!wpas_p2p_disallowed_freq(wpa_s->global,
5092                                                       params->freq) &&
5093                             freq_included(channels, params->freq))
5094                                 break;
5095                 }
5096                 if (chan == 11) {
5097                         wpa_printf(MSG_DEBUG, "P2P: No 2.4 GHz channel "
5098                                    "allowed");
5099                         return -1;
5100                 }
5101                 wpa_printf(MSG_DEBUG, "P2P: Set GO freq %d MHz (no preference "
5102                            "known)", params->freq);
5103         }
5104
5105         freqs = os_calloc(wpa_s->num_multichan_concurrent,
5106                           sizeof(struct wpa_used_freq_data));
5107         if (!freqs)
5108                 return -1;
5109
5110         num = wpas_p2p_valid_oper_freqs(wpa_s, freqs,
5111                                         wpa_s->num_multichan_concurrent);
5112
5113         cand_freq = wpas_p2p_pick_best_used_freq(wpa_s, freqs, num);
5114
5115         /* First try the best used frequency if possible */
5116         if (!freq && cand_freq > 0 && freq_included(channels, cand_freq)) {
5117                 params->freq = cand_freq;
5118         } else if (!freq) {
5119                 /* Try any of the used frequencies */
5120                 for (i = 0; i < num; i++) {
5121                         if (freq_included(channels, freqs[i].freq)) {
5122                                 wpa_printf(MSG_DEBUG, "P2P: Force GO on a channel we are already using (%u MHz)",
5123                                            freqs[i].freq);
5124                                 params->freq = freqs[i].freq;
5125                                 break;
5126                         }
5127                 }
5128
5129                 if (i == num) {
5130                         if (wpas_p2p_num_unused_channels(wpa_s) <= 0) {
5131                                 wpa_printf(MSG_DEBUG, "P2P: Cannot force GO on any of the channels we are already using");
5132                                 os_free(freqs);
5133                                 return -1;
5134                         } else {
5135                                 wpa_printf(MSG_DEBUG, "P2P: Cannot force GO on any of the channels we are already using. Use one of the free channels");
5136                         }
5137                 }
5138         } else {
5139                 for (i = 0; i < num; i++) {
5140                         if (freqs[i].freq == freq)
5141                                 break;
5142                 }
5143
5144                 if (i == num) {
5145                         if (wpas_p2p_num_unused_channels(wpa_s) <= 0) {
5146                                 if (freq)
5147                                         wpa_printf(MSG_DEBUG, "P2P: Cannot force GO on freq (%u MHz) as all the channels are in use", freq);
5148                                 os_free(freqs);
5149                                 return -1;
5150                         } else {
5151                                 wpa_printf(MSG_DEBUG, "P2P: Use one of the free channels");
5152                         }
5153                 }
5154         }
5155
5156         os_free(freqs);
5157         return 0;
5158 }
5159
5160
5161 static struct wpa_supplicant *
5162 wpas_p2p_get_group_iface(struct wpa_supplicant *wpa_s, int addr_allocated,
5163                          int go)
5164 {
5165         struct wpa_supplicant *group_wpa_s;
5166
5167         if (!wpas_p2p_create_iface(wpa_s)) {
5168                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Use same interface for group "
5169                         "operations");
5170                 wpa_s->p2p_first_connection_timeout = 0;
5171                 return wpa_s;
5172         }
5173
5174         if (wpas_p2p_add_group_interface(wpa_s, go ? WPA_IF_P2P_GO :
5175                                          WPA_IF_P2P_CLIENT) < 0) {
5176                 wpa_msg_global(wpa_s, MSG_ERROR,
5177                                "P2P: Failed to add group interface");
5178                 return NULL;
5179         }
5180         group_wpa_s = wpas_p2p_init_group_interface(wpa_s, go);
5181         if (group_wpa_s == NULL) {
5182                 wpa_msg_global(wpa_s, MSG_ERROR,
5183                                "P2P: Failed to initialize group interface");
5184                 wpas_p2p_remove_pending_group_interface(wpa_s);
5185                 return NULL;
5186         }
5187
5188         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Use separate group interface %s",
5189                 group_wpa_s->ifname);
5190         group_wpa_s->p2p_first_connection_timeout = 0;
5191         return group_wpa_s;
5192 }
5193
5194
5195 /**
5196  * wpas_p2p_group_add - Add a new P2P group with local end as Group Owner
5197  * @wpa_s: Pointer to wpa_supplicant data from wpa_supplicant_add_iface()
5198  * @persistent_group: Whether to create a persistent group
5199  * @freq: Frequency for the group or 0 to indicate no hardcoding
5200  * @ht40: Start GO with 40 MHz channel width
5201  * @vht:  Start GO with VHT support
5202  * Returns: 0 on success, -1 on failure
5203  *
5204  * This function creates a new P2P group with the local end as the Group Owner,
5205  * i.e., without using Group Owner Negotiation.
5206  */
5207 int wpas_p2p_group_add(struct wpa_supplicant *wpa_s, int persistent_group,
5208                        int freq, int ht40, int vht)
5209 {
5210         struct p2p_go_neg_results params;
5211
5212         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5213                 return -1;
5214
5215         os_free(wpa_s->global->add_psk);
5216         wpa_s->global->add_psk = NULL;
5217
5218         /* Make sure we are not running find during connection establishment */
5219         wpa_printf(MSG_DEBUG, "P2P: Stop any on-going P2P FIND");
5220         wpas_p2p_stop_find_oper(wpa_s);
5221
5222         freq = wpas_p2p_select_go_freq(wpa_s, freq);
5223         if (freq < 0)
5224                 return -1;
5225
5226         if (wpas_p2p_init_go_params(wpa_s, &params, freq, ht40, vht, NULL))
5227                 return -1;
5228         if (params.freq &&
5229             !p2p_supported_freq_go(wpa_s->global->p2p, params.freq)) {
5230                 wpa_printf(MSG_DEBUG, "P2P: The selected channel for GO "
5231                            "(%u MHz) is not supported for P2P uses",
5232                            params.freq);
5233                 return -1;
5234         }
5235         p2p_go_params(wpa_s->global->p2p, &params);
5236         params.persistent_group = persistent_group;
5237
5238         wpa_s = wpas_p2p_get_group_iface(wpa_s, 0, 1);
5239         if (wpa_s == NULL)
5240                 return -1;
5241         wpas_start_wps_go(wpa_s, &params, 0);
5242
5243         return 0;
5244 }
5245
5246
5247 static int wpas_start_p2p_client(struct wpa_supplicant *wpa_s,
5248                                  struct wpa_ssid *params, int addr_allocated,
5249                                  int freq)
5250 {
5251         struct wpa_ssid *ssid;
5252
5253         wpa_s = wpas_p2p_get_group_iface(wpa_s, addr_allocated, 0);
5254         if (wpa_s == NULL)
5255                 return -1;
5256         wpa_s->p2p_last_4way_hs_fail = NULL;
5257
5258         wpa_supplicant_ap_deinit(wpa_s);
5259
5260         ssid = wpa_config_add_network(wpa_s->conf);
5261         if (ssid == NULL)
5262                 return -1;
5263         wpa_config_set_network_defaults(ssid);
5264         ssid->temporary = 1;
5265         ssid->proto = WPA_PROTO_RSN;
5266         ssid->pairwise_cipher = WPA_CIPHER_CCMP;
5267         ssid->group_cipher = WPA_CIPHER_CCMP;
5268         ssid->key_mgmt = WPA_KEY_MGMT_PSK;
5269         ssid->ssid = os_malloc(params->ssid_len);
5270         if (ssid->ssid == NULL) {
5271                 wpa_config_remove_network(wpa_s->conf, ssid->id);
5272                 return -1;
5273         }
5274         os_memcpy(ssid->ssid, params->ssid, params->ssid_len);
5275         ssid->ssid_len = params->ssid_len;
5276         ssid->p2p_group = 1;
5277         ssid->export_keys = 1;
5278         if (params->psk_set) {
5279                 os_memcpy(ssid->psk, params->psk, 32);
5280                 ssid->psk_set = 1;
5281         }
5282         if (params->passphrase)
5283                 ssid->passphrase = os_strdup(params->passphrase);
5284
5285         wpa_s->show_group_started = 1;
5286         wpa_s->p2p_in_invitation = 1;
5287         wpa_s->p2p_invite_go_freq = freq;
5288
5289         eloop_cancel_timeout(wpas_p2p_group_formation_timeout, wpa_s->parent,
5290                              NULL);
5291         eloop_register_timeout(P2P_MAX_INITIAL_CONN_WAIT, 0,
5292                                wpas_p2p_group_formation_timeout,
5293                                wpa_s->parent, NULL);
5294         wpa_supplicant_select_network(wpa_s, ssid);
5295
5296         return 0;
5297 }
5298
5299
5300 int wpas_p2p_group_add_persistent(struct wpa_supplicant *wpa_s,
5301                                   struct wpa_ssid *ssid, int addr_allocated,
5302                                   int force_freq, int neg_freq, int ht40,
5303                                   int vht, const struct p2p_channels *channels,
5304                                   int connection_timeout)
5305 {
5306         struct p2p_go_neg_results params;
5307         int go = 0, freq;
5308
5309         if (ssid->disabled != 2 || ssid->ssid == NULL)
5310                 return -1;
5311
5312         if (wpas_get_p2p_group(wpa_s, ssid->ssid, ssid->ssid_len, &go) &&
5313             go == (ssid->mode == WPAS_MODE_P2P_GO)) {
5314                 wpa_printf(MSG_DEBUG, "P2P: Requested persistent group is "
5315                            "already running");
5316                 return 0;
5317         }
5318
5319         os_free(wpa_s->global->add_psk);
5320         wpa_s->global->add_psk = NULL;
5321
5322         /* Make sure we are not running find during connection establishment */
5323         wpas_p2p_stop_find_oper(wpa_s);
5324
5325         wpa_s->p2p_fallback_to_go_neg = 0;
5326
5327         if (force_freq > 0) {
5328                 freq = wpas_p2p_select_go_freq(wpa_s, force_freq);
5329                 if (freq < 0)
5330                         return -1;
5331         } else {
5332                 freq = wpas_p2p_select_go_freq(wpa_s, neg_freq);
5333                 if (freq < 0 || (freq > 0 && !freq_included(channels, freq)))
5334                         freq = 0;
5335         }
5336
5337         if (ssid->mode == WPAS_MODE_INFRA)
5338                 return wpas_start_p2p_client(wpa_s, ssid, addr_allocated, freq);
5339
5340         if (ssid->mode != WPAS_MODE_P2P_GO)
5341                 return -1;
5342
5343         if (wpas_p2p_init_go_params(wpa_s, &params, freq, ht40, vht, channels))
5344                 return -1;
5345
5346         params.role_go = 1;
5347         params.psk_set = ssid->psk_set;
5348         if (params.psk_set)
5349                 os_memcpy(params.psk, ssid->psk, sizeof(params.psk));
5350         if (ssid->passphrase) {
5351                 if (os_strlen(ssid->passphrase) >= sizeof(params.passphrase)) {
5352                         wpa_printf(MSG_ERROR, "P2P: Invalid passphrase in "
5353                                    "persistent group");
5354                         return -1;
5355                 }
5356                 os_strlcpy(params.passphrase, ssid->passphrase,
5357                            sizeof(params.passphrase));
5358         }
5359         os_memcpy(params.ssid, ssid->ssid, ssid->ssid_len);
5360         params.ssid_len = ssid->ssid_len;
5361         params.persistent_group = 1;
5362
5363         wpa_s = wpas_p2p_get_group_iface(wpa_s, addr_allocated, 1);
5364         if (wpa_s == NULL)
5365                 return -1;
5366
5367         wpa_s->p2p_first_connection_timeout = connection_timeout;
5368         wpas_start_wps_go(wpa_s, &params, 0);
5369
5370         return 0;
5371 }
5372
5373
5374 static void wpas_p2p_ie_update(void *ctx, struct wpabuf *beacon_ies,
5375                                struct wpabuf *proberesp_ies)
5376 {
5377         struct wpa_supplicant *wpa_s = ctx;
5378         if (wpa_s->ap_iface) {
5379                 struct hostapd_data *hapd = wpa_s->ap_iface->bss[0];
5380                 if (!(hapd->conf->p2p & P2P_GROUP_OWNER)) {
5381                         wpabuf_free(beacon_ies);
5382                         wpabuf_free(proberesp_ies);
5383                         return;
5384                 }
5385                 if (beacon_ies) {
5386                         wpabuf_free(hapd->p2p_beacon_ie);
5387                         hapd->p2p_beacon_ie = beacon_ies;
5388                 }
5389                 wpabuf_free(hapd->p2p_probe_resp_ie);
5390                 hapd->p2p_probe_resp_ie = proberesp_ies;
5391         } else {
5392                 wpabuf_free(beacon_ies);
5393                 wpabuf_free(proberesp_ies);
5394         }
5395         wpa_supplicant_ap_update_beacon(wpa_s);
5396 }
5397
5398
5399 static void wpas_p2p_idle_update(void *ctx, int idle)
5400 {
5401         struct wpa_supplicant *wpa_s = ctx;
5402         if (!wpa_s->ap_iface)
5403                 return;
5404         wpa_printf(MSG_DEBUG, "P2P: GO - group %sidle", idle ? "" : "not ");
5405         if (idle) {
5406                 if (wpa_s->global->p2p_fail_on_wps_complete &&
5407                     wpa_s->p2p_in_provisioning) {
5408                         wpas_p2p_grpform_fail_after_wps(wpa_s);
5409                         return;
5410                 }
5411                 wpas_p2p_set_group_idle_timeout(wpa_s);
5412         } else
5413                 eloop_cancel_timeout(wpas_p2p_group_idle_timeout, wpa_s, NULL);
5414 }
5415
5416
5417 struct p2p_group * wpas_p2p_group_init(struct wpa_supplicant *wpa_s,
5418                                        struct wpa_ssid *ssid)
5419 {
5420         struct p2p_group *group;
5421         struct p2p_group_config *cfg;
5422
5423         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5424                 return NULL;
5425
5426         cfg = os_zalloc(sizeof(*cfg));
5427         if (cfg == NULL)
5428                 return NULL;
5429
5430         if (ssid->p2p_persistent_group && wpa_s->conf->persistent_reconnect)
5431                 cfg->persistent_group = 2;
5432         else if (ssid->p2p_persistent_group)
5433                 cfg->persistent_group = 1;
5434         os_memcpy(cfg->interface_addr, wpa_s->own_addr, ETH_ALEN);
5435         if (wpa_s->max_stations &&
5436             wpa_s->max_stations < wpa_s->conf->max_num_sta)
5437                 cfg->max_clients = wpa_s->max_stations;
5438         else
5439                 cfg->max_clients = wpa_s->conf->max_num_sta;
5440         os_memcpy(cfg->ssid, ssid->ssid, ssid->ssid_len);
5441         cfg->ssid_len = ssid->ssid_len;
5442         cfg->freq = ssid->frequency;
5443         cfg->cb_ctx = wpa_s;
5444         cfg->ie_update = wpas_p2p_ie_update;
5445         cfg->idle_update = wpas_p2p_idle_update;
5446
5447         group = p2p_group_init(wpa_s->global->p2p, cfg);
5448         if (group == NULL)
5449                 os_free(cfg);
5450         if (ssid->mode != WPAS_MODE_P2P_GROUP_FORMATION)
5451                 p2p_group_notif_formation_done(group);
5452         wpa_s->p2p_group = group;
5453         return group;
5454 }
5455
5456
5457 void wpas_p2p_wps_success(struct wpa_supplicant *wpa_s, const u8 *peer_addr,
5458                           int registrar)
5459 {
5460         struct wpa_ssid *ssid = wpa_s->current_ssid;
5461
5462         if (!wpa_s->p2p_in_provisioning) {
5463                 wpa_printf(MSG_DEBUG, "P2P: Ignore WPS success event - P2P "
5464                            "provisioning not in progress");
5465                 return;
5466         }
5467
5468         if (ssid && ssid->mode == WPAS_MODE_INFRA) {
5469                 u8 go_dev_addr[ETH_ALEN];
5470                 os_memcpy(go_dev_addr, wpa_s->bssid, ETH_ALEN);
5471                 wpas_p2p_persistent_group(wpa_s, go_dev_addr, ssid->ssid,
5472                                           ssid->ssid_len);
5473                 /* Clear any stored provisioning info */
5474                 p2p_clear_provisioning_info(wpa_s->global->p2p, go_dev_addr);
5475         }
5476
5477         eloop_cancel_timeout(wpas_p2p_group_formation_timeout, wpa_s->parent,
5478                              NULL);
5479         wpa_s->p2p_go_group_formation_completed = 1;
5480         if (ssid && ssid->mode == WPAS_MODE_INFRA) {
5481                 /*
5482                  * Use a separate timeout for initial data connection to
5483                  * complete to allow the group to be removed automatically if
5484                  * something goes wrong in this step before the P2P group idle
5485                  * timeout mechanism is taken into use.
5486                  */
5487                 wpa_dbg(wpa_s, MSG_DEBUG,
5488                         "P2P: Re-start group formation timeout (%d seconds) as client for initial connection",
5489                         P2P_MAX_INITIAL_CONN_WAIT);
5490                 eloop_register_timeout(P2P_MAX_INITIAL_CONN_WAIT, 0,
5491                                        wpas_p2p_group_formation_timeout,
5492                                        wpa_s->parent, NULL);
5493         } else if (ssid) {
5494                 /*
5495                  * Use a separate timeout for initial data connection to
5496                  * complete to allow the group to be removed automatically if
5497                  * the client does not complete data connection successfully.
5498                  */
5499                 wpa_dbg(wpa_s, MSG_DEBUG,
5500                         "P2P: Re-start group formation timeout (%d seconds) as GO for initial connection",
5501                         P2P_MAX_INITIAL_CONN_WAIT_GO);
5502                 eloop_register_timeout(P2P_MAX_INITIAL_CONN_WAIT_GO, 0,
5503                                        wpas_p2p_group_formation_timeout,
5504                                        wpa_s->parent, NULL);
5505                 /*
5506                  * Complete group formation on first successful data connection
5507                  */
5508                 wpa_s->p2p_go_group_formation_completed = 0;
5509         }
5510         if (wpa_s->global->p2p)
5511                 p2p_wps_success_cb(wpa_s->global->p2p, peer_addr);
5512         wpas_group_formation_completed(wpa_s, 1);
5513 }
5514
5515
5516 void wpas_p2p_wps_failed(struct wpa_supplicant *wpa_s,
5517                          struct wps_event_fail *fail)
5518 {
5519         if (!wpa_s->p2p_in_provisioning) {
5520                 wpa_printf(MSG_DEBUG, "P2P: Ignore WPS fail event - P2P "
5521                            "provisioning not in progress");
5522                 return;
5523         }
5524
5525         if (wpa_s->go_params) {
5526                 p2p_clear_provisioning_info(
5527                         wpa_s->global->p2p,
5528                         wpa_s->go_params->peer_device_addr);
5529         }
5530
5531         wpas_notify_p2p_wps_failed(wpa_s, fail);
5532
5533         if (wpa_s == wpa_s->global->p2p_group_formation) {
5534                 /*
5535                  * Allow some time for the failed WPS negotiation exchange to
5536                  * complete, but remove the group since group formation cannot
5537                  * succeed after provisioning failure.
5538                  */
5539                 wpa_printf(MSG_DEBUG, "P2P: WPS step failed during group formation - reject connection from timeout");
5540                 wpa_s->global->p2p_fail_on_wps_complete = 1;
5541                 eloop_deplete_timeout(0, 50000,
5542                                       wpas_p2p_group_formation_timeout,
5543                                       wpa_s->parent, NULL);
5544         }
5545 }
5546
5547
5548 int wpas_p2p_wps_eapol_cb(struct wpa_supplicant *wpa_s)
5549 {
5550         if (!wpa_s->global->p2p_fail_on_wps_complete ||
5551             !wpa_s->p2p_in_provisioning)
5552                 return 0;
5553
5554         wpas_p2p_grpform_fail_after_wps(wpa_s);
5555
5556         return 1;
5557 }
5558
5559
5560 int wpas_p2p_prov_disc(struct wpa_supplicant *wpa_s, const u8 *peer_addr,
5561                        const char *config_method,
5562                        enum wpas_p2p_prov_disc_use use)
5563 {
5564         u16 config_methods;
5565
5566         wpa_s->p2p_fallback_to_go_neg = 0;
5567         wpa_s->pending_pd_use = NORMAL_PD;
5568         if (os_strncmp(config_method, "display", 7) == 0)
5569                 config_methods = WPS_CONFIG_DISPLAY;
5570         else if (os_strncmp(config_method, "keypad", 6) == 0)
5571                 config_methods = WPS_CONFIG_KEYPAD;
5572         else if (os_strncmp(config_method, "pbc", 3) == 0 ||
5573                  os_strncmp(config_method, "pushbutton", 10) == 0)
5574                 config_methods = WPS_CONFIG_PUSHBUTTON;
5575         else {
5576                 wpa_printf(MSG_DEBUG, "P2P: Unknown config method");
5577                 return -1;
5578         }
5579
5580         if (use == WPAS_P2P_PD_AUTO) {
5581                 os_memcpy(wpa_s->pending_join_dev_addr, peer_addr, ETH_ALEN);
5582                 wpa_s->pending_pd_config_methods = config_methods;
5583                 wpa_s->p2p_auto_pd = 1;
5584                 wpa_s->p2p_auto_join = 0;
5585                 wpa_s->pending_pd_before_join = 0;
5586                 wpa_s->auto_pd_scan_retry = 0;
5587                 wpas_p2p_stop_find(wpa_s);
5588                 wpa_s->p2p_join_scan_count = 0;
5589                 os_get_reltime(&wpa_s->p2p_auto_started);
5590                 wpa_printf(MSG_DEBUG, "P2P: Auto PD started at %ld.%06ld",
5591                            wpa_s->p2p_auto_started.sec,
5592                            wpa_s->p2p_auto_started.usec);
5593                 wpas_p2p_join_scan(wpa_s, NULL);
5594                 return 0;
5595         }
5596
5597         if (wpa_s->global->p2p == NULL || wpa_s->global->p2p_disabled)
5598                 return -1;
5599
5600         return p2p_prov_disc_req(wpa_s->global->p2p, peer_addr,
5601                                  config_methods, use == WPAS_P2P_PD_FOR_JOIN,
5602                                  0, 1);
5603 }
5604
5605
5606 int wpas_p2p_scan_result_text(const u8 *ies, size_t ies_len, char *buf,
5607                               char *end)
5608 {
5609         return p2p_scan_result_text(ies, ies_len, buf, end);
5610 }
5611
5612
5613 static void wpas_p2p_clear_pending_action_tx(struct wpa_supplicant *wpa_s)
5614 {
5615         if (!offchannel_pending_action_tx(wpa_s))
5616                 return;
5617
5618         wpa_printf(MSG_DEBUG, "P2P: Drop pending Action TX due to new "
5619                    "operation request");
5620         offchannel_clear_pending_action_tx(wpa_s);
5621 }
5622
5623
5624 int wpas_p2p_find(struct wpa_supplicant *wpa_s, unsigned int timeout,
5625                   enum p2p_discovery_type type,
5626                   unsigned int num_req_dev_types, const u8 *req_dev_types,
5627                   const u8 *dev_id, unsigned int search_delay)
5628 {
5629         wpas_p2p_clear_pending_action_tx(wpa_s);
5630         wpa_s->p2p_long_listen = 0;
5631
5632         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL ||
5633             wpa_s->p2p_in_provisioning)
5634                 return -1;
5635
5636         wpa_supplicant_cancel_sched_scan(wpa_s);
5637
5638         return p2p_find(wpa_s->global->p2p, timeout, type,
5639                         num_req_dev_types, req_dev_types, dev_id,
5640                         search_delay);
5641 }
5642
5643
5644 static int wpas_p2p_stop_find_oper(struct wpa_supplicant *wpa_s)
5645 {
5646         wpas_p2p_clear_pending_action_tx(wpa_s);
5647         wpa_s->p2p_long_listen = 0;
5648         eloop_cancel_timeout(wpas_p2p_long_listen_timeout, wpa_s, NULL);
5649         eloop_cancel_timeout(wpas_p2p_join_scan, wpa_s, NULL);
5650
5651         if (wpa_s->global->p2p)
5652                 p2p_stop_find(wpa_s->global->p2p);
5653
5654         return 0;
5655 }
5656
5657
5658 void wpas_p2p_stop_find(struct wpa_supplicant *wpa_s)
5659 {
5660         if (wpas_p2p_stop_find_oper(wpa_s) > 0)
5661                 return;
5662         wpas_p2p_remove_pending_group_interface(wpa_s);
5663 }
5664
5665
5666 static void wpas_p2p_long_listen_timeout(void *eloop_ctx, void *timeout_ctx)
5667 {
5668         struct wpa_supplicant *wpa_s = eloop_ctx;
5669         wpa_s->p2p_long_listen = 0;
5670 }
5671
5672
5673 int wpas_p2p_listen(struct wpa_supplicant *wpa_s, unsigned int timeout)
5674 {
5675         int res;
5676
5677         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5678                 return -1;
5679
5680         wpa_supplicant_cancel_sched_scan(wpa_s);
5681         wpas_p2p_clear_pending_action_tx(wpa_s);
5682
5683         if (timeout == 0) {
5684                 /*
5685                  * This is a request for unlimited Listen state. However, at
5686                  * least for now, this is mapped to a Listen state for one
5687                  * hour.
5688                  */
5689                 timeout = 3600;
5690         }
5691         eloop_cancel_timeout(wpas_p2p_long_listen_timeout, wpa_s, NULL);
5692         wpa_s->p2p_long_listen = 0;
5693
5694         /*
5695          * Stop previous find/listen operation to avoid trying to request a new
5696          * remain-on-channel operation while the driver is still running the
5697          * previous one.
5698          */
5699         if (wpa_s->global->p2p)
5700                 p2p_stop_find(wpa_s->global->p2p);
5701
5702         res = wpas_p2p_listen_start(wpa_s, timeout * 1000);
5703         if (res == 0 && timeout * 1000 > wpa_s->max_remain_on_chan) {
5704                 wpa_s->p2p_long_listen = timeout * 1000;
5705                 eloop_register_timeout(timeout, 0,
5706                                        wpas_p2p_long_listen_timeout,
5707                                        wpa_s, NULL);
5708         }
5709
5710         return res;
5711 }
5712
5713
5714 int wpas_p2p_assoc_req_ie(struct wpa_supplicant *wpa_s, struct wpa_bss *bss,
5715                           u8 *buf, size_t len, int p2p_group)
5716 {
5717         struct wpabuf *p2p_ie;
5718         int ret;
5719
5720         if (wpa_s->global->p2p_disabled)
5721                 return -1;
5722         if (wpa_s->global->p2p == NULL)
5723                 return -1;
5724         if (bss == NULL)
5725                 return -1;
5726
5727         p2p_ie = wpa_bss_get_vendor_ie_multi(bss, P2P_IE_VENDOR_TYPE);
5728         ret = p2p_assoc_req_ie(wpa_s->global->p2p, bss->bssid, buf, len,
5729                                p2p_group, p2p_ie);
5730         wpabuf_free(p2p_ie);
5731
5732         return ret;
5733 }
5734
5735
5736 int wpas_p2p_probe_req_rx(struct wpa_supplicant *wpa_s, const u8 *addr,
5737                           const u8 *dst, const u8 *bssid,
5738                           const u8 *ie, size_t ie_len, int ssi_signal)
5739 {
5740         if (wpa_s->global->p2p_disabled)
5741                 return 0;
5742         if (wpa_s->global->p2p == NULL)
5743                 return 0;
5744
5745         switch (p2p_probe_req_rx(wpa_s->global->p2p, addr, dst, bssid,
5746                                  ie, ie_len)) {
5747         case P2P_PREQ_NOT_P2P:
5748                 wpas_notify_preq(wpa_s, addr, dst, bssid, ie, ie_len,
5749                                  ssi_signal);
5750                 /* fall through */
5751         case P2P_PREQ_MALFORMED:
5752         case P2P_PREQ_NOT_LISTEN:
5753         case P2P_PREQ_NOT_PROCESSED:
5754         default: /* make gcc happy */
5755                 return 0;
5756         case P2P_PREQ_PROCESSED:
5757                 return 1;
5758         }
5759 }
5760
5761
5762 void wpas_p2p_rx_action(struct wpa_supplicant *wpa_s, const u8 *da,
5763                         const u8 *sa, const u8 *bssid,
5764                         u8 category, const u8 *data, size_t len, int freq)
5765 {
5766         if (wpa_s->global->p2p_disabled)
5767                 return;
5768         if (wpa_s->global->p2p == NULL)
5769                 return;
5770
5771         p2p_rx_action(wpa_s->global->p2p, da, sa, bssid, category, data, len,
5772                       freq);
5773 }
5774
5775
5776 void wpas_p2p_scan_ie(struct wpa_supplicant *wpa_s, struct wpabuf *ies)
5777 {
5778         if (wpa_s->global->p2p_disabled)
5779                 return;
5780         if (wpa_s->global->p2p == NULL)
5781                 return;
5782
5783         p2p_scan_ie(wpa_s->global->p2p, ies, NULL);
5784 }
5785
5786
5787 void wpas_p2p_group_deinit(struct wpa_supplicant *wpa_s)
5788 {
5789         p2p_group_deinit(wpa_s->p2p_group);
5790         wpa_s->p2p_group = NULL;
5791
5792         wpa_s->ap_configured_cb = NULL;
5793         wpa_s->ap_configured_cb_ctx = NULL;
5794         wpa_s->ap_configured_cb_data = NULL;
5795         wpa_s->connect_without_scan = NULL;
5796 }
5797
5798
5799 int wpas_p2p_reject(struct wpa_supplicant *wpa_s, const u8 *addr)
5800 {
5801         wpa_s->p2p_long_listen = 0;
5802
5803         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5804                 return -1;
5805
5806         return p2p_reject(wpa_s->global->p2p, addr);
5807 }
5808
5809
5810 /* Invite to reinvoke a persistent group */
5811 int wpas_p2p_invite(struct wpa_supplicant *wpa_s, const u8 *peer_addr,
5812                     struct wpa_ssid *ssid, const u8 *go_dev_addr, int freq,
5813                     int ht40, int vht, int pref_freq)
5814 {
5815         enum p2p_invite_role role;
5816         u8 *bssid = NULL;
5817         int force_freq = 0;
5818         int res;
5819         int no_pref_freq_given = pref_freq == 0;
5820
5821         wpa_s->global->p2p_invite_group = NULL;
5822         if (peer_addr)
5823                 os_memcpy(wpa_s->p2p_auth_invite, peer_addr, ETH_ALEN);
5824         else
5825                 os_memset(wpa_s->p2p_auth_invite, 0, ETH_ALEN);
5826
5827         wpa_s->p2p_persistent_go_freq = freq;
5828         wpa_s->p2p_go_ht40 = !!ht40;
5829         if (ssid->mode == WPAS_MODE_P2P_GO) {
5830                 role = P2P_INVITE_ROLE_GO;
5831                 if (peer_addr == NULL) {
5832                         wpa_printf(MSG_DEBUG, "P2P: Missing peer "
5833                                    "address in invitation command");
5834                         return -1;
5835                 }
5836                 if (wpas_p2p_create_iface(wpa_s)) {
5837                         if (wpas_p2p_add_group_interface(wpa_s,
5838                                                          WPA_IF_P2P_GO) < 0) {
5839                                 wpa_printf(MSG_ERROR, "P2P: Failed to "
5840                                            "allocate a new interface for the "
5841                                            "group");
5842                                 return -1;
5843                         }
5844                         bssid = wpa_s->pending_interface_addr;
5845                 } else
5846                         bssid = wpa_s->own_addr;
5847         } else {
5848                 role = P2P_INVITE_ROLE_CLIENT;
5849                 peer_addr = ssid->bssid;
5850         }
5851         wpa_s->pending_invite_ssid_id = ssid->id;
5852
5853         res = wpas_p2p_setup_freqs(wpa_s, freq, &force_freq, &pref_freq,
5854                                    role == P2P_INVITE_ROLE_GO);
5855         if (res)
5856                 return res;
5857
5858         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5859                 return -1;
5860
5861         if (wpa_s->parent->conf->p2p_ignore_shared_freq &&
5862             no_pref_freq_given && pref_freq > 0 &&
5863             wpa_s->num_multichan_concurrent > 1 &&
5864             wpas_p2p_num_unused_channels(wpa_s) > 0) {
5865                 wpa_printf(MSG_DEBUG, "P2P: Ignore own channel preference %d MHz for invitation due to p2p_ignore_shared_freq=1 configuration",
5866                            pref_freq);
5867                 pref_freq = 0;
5868         }
5869
5870         return p2p_invite(wpa_s->global->p2p, peer_addr, role, bssid,
5871                           ssid->ssid, ssid->ssid_len, force_freq, go_dev_addr,
5872                           1, pref_freq, -1);
5873 }
5874
5875
5876 /* Invite to join an active group */
5877 int wpas_p2p_invite_group(struct wpa_supplicant *wpa_s, const char *ifname,
5878                           const u8 *peer_addr, const u8 *go_dev_addr)
5879 {
5880         struct wpa_global *global = wpa_s->global;
5881         enum p2p_invite_role role;
5882         u8 *bssid = NULL;
5883         struct wpa_ssid *ssid;
5884         int persistent;
5885         int freq = 0, force_freq = 0, pref_freq = 0;
5886         int res;
5887
5888         wpa_s->p2p_persistent_go_freq = 0;
5889         wpa_s->p2p_go_ht40 = 0;
5890         wpa_s->p2p_go_vht = 0;
5891
5892         for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) {
5893                 if (os_strcmp(wpa_s->ifname, ifname) == 0)
5894                         break;
5895         }
5896         if (wpa_s == NULL) {
5897                 wpa_printf(MSG_DEBUG, "P2P: Interface '%s' not found", ifname);
5898                 return -1;
5899         }
5900
5901         ssid = wpa_s->current_ssid;
5902         if (ssid == NULL) {
5903                 wpa_printf(MSG_DEBUG, "P2P: No current SSID to use for "
5904                            "invitation");
5905                 return -1;
5906         }
5907
5908         wpa_s->global->p2p_invite_group = wpa_s;
5909         persistent = ssid->p2p_persistent_group &&
5910                 wpas_p2p_get_persistent(wpa_s->parent, peer_addr,
5911                                         ssid->ssid, ssid->ssid_len);
5912
5913         if (ssid->mode == WPAS_MODE_P2P_GO) {
5914                 role = P2P_INVITE_ROLE_ACTIVE_GO;
5915                 bssid = wpa_s->own_addr;
5916                 if (go_dev_addr == NULL)
5917                         go_dev_addr = wpa_s->global->p2p_dev_addr;
5918                 freq = ssid->frequency;
5919         } else {
5920                 role = P2P_INVITE_ROLE_CLIENT;
5921                 if (wpa_s->wpa_state < WPA_ASSOCIATED) {
5922                         wpa_printf(MSG_DEBUG, "P2P: Not associated - cannot "
5923                                    "invite to current group");
5924                         return -1;
5925                 }
5926                 bssid = wpa_s->bssid;
5927                 if (go_dev_addr == NULL &&
5928                     !is_zero_ether_addr(wpa_s->go_dev_addr))
5929                         go_dev_addr = wpa_s->go_dev_addr;
5930                 freq = wpa_s->current_bss ? wpa_s->current_bss->freq :
5931                         (int) wpa_s->assoc_freq;
5932         }
5933         wpa_s->parent->pending_invite_ssid_id = -1;
5934
5935         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
5936                 return -1;
5937
5938         res = wpas_p2p_setup_freqs(wpa_s, freq, &force_freq, &pref_freq,
5939                                    role == P2P_INVITE_ROLE_ACTIVE_GO);
5940         if (res)
5941                 return res;
5942         wpas_p2p_set_own_freq_preference(wpa_s, force_freq);
5943
5944         return p2p_invite(wpa_s->global->p2p, peer_addr, role, bssid,
5945                           ssid->ssid, ssid->ssid_len, force_freq,
5946                           go_dev_addr, persistent, pref_freq, -1);
5947 }
5948
5949
5950 void wpas_p2p_completed(struct wpa_supplicant *wpa_s)
5951 {
5952         struct wpa_ssid *ssid = wpa_s->current_ssid;
5953         const char *ssid_txt;
5954         u8 go_dev_addr[ETH_ALEN];
5955         int network_id = -1;
5956         int persistent;
5957         int freq;
5958         u8 ip[3 * 4];
5959         char ip_addr[100];
5960
5961         if (ssid == NULL || ssid->mode != WPAS_MODE_P2P_GROUP_FORMATION) {
5962                 eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
5963                                      wpa_s->parent, NULL);
5964         }
5965
5966         if (!wpa_s->show_group_started || !ssid)
5967                 return;
5968
5969         wpa_s->show_group_started = 0;
5970
5971         ssid_txt = wpa_ssid_txt(ssid->ssid, ssid->ssid_len);
5972         os_memset(go_dev_addr, 0, ETH_ALEN);
5973         if (ssid->bssid_set)
5974                 os_memcpy(go_dev_addr, ssid->bssid, ETH_ALEN);
5975         persistent = wpas_p2p_persistent_group(wpa_s, go_dev_addr, ssid->ssid,
5976                                                ssid->ssid_len);
5977         os_memcpy(wpa_s->go_dev_addr, go_dev_addr, ETH_ALEN);
5978
5979         if (wpa_s->global->p2p_group_formation == wpa_s)
5980                 wpa_s->global->p2p_group_formation = NULL;
5981
5982         freq = wpa_s->current_bss ? wpa_s->current_bss->freq :
5983                 (int) wpa_s->assoc_freq;
5984
5985         ip_addr[0] = '\0';
5986         if (wpa_sm_get_p2p_ip_addr(wpa_s->wpa, ip) == 0) {
5987                 os_snprintf(ip_addr, sizeof(ip_addr), " ip_addr=%u.%u.%u.%u "
5988                             "ip_mask=%u.%u.%u.%u go_ip_addr=%u.%u.%u.%u",
5989                             ip[0], ip[1], ip[2], ip[3],
5990                             ip[4], ip[5], ip[6], ip[7],
5991                             ip[8], ip[9], ip[10], ip[11]);
5992         }
5993
5994         if (ssid->passphrase == NULL && ssid->psk_set) {
5995                 char psk[65];
5996                 wpa_snprintf_hex(psk, sizeof(psk), ssid->psk, 32);
5997                 wpa_msg_global(wpa_s->parent, MSG_INFO, P2P_EVENT_GROUP_STARTED
5998                                "%s client ssid=\"%s\" freq=%d psk=%s "
5999                                "go_dev_addr=" MACSTR "%s%s",
6000                                wpa_s->ifname, ssid_txt, freq, psk,
6001                                MAC2STR(go_dev_addr),
6002                                persistent ? " [PERSISTENT]" : "", ip_addr);
6003         } else {
6004                 wpa_msg_global(wpa_s->parent, MSG_INFO, P2P_EVENT_GROUP_STARTED
6005                                "%s client ssid=\"%s\" freq=%d "
6006                                "passphrase=\"%s\" go_dev_addr=" MACSTR "%s%s",
6007                                wpa_s->ifname, ssid_txt, freq,
6008                                ssid->passphrase ? ssid->passphrase : "",
6009                                MAC2STR(go_dev_addr),
6010                                persistent ? " [PERSISTENT]" : "", ip_addr);
6011         }
6012
6013         if (persistent)
6014                 network_id = wpas_p2p_store_persistent_group(wpa_s->parent,
6015                                                              ssid, go_dev_addr);
6016         if (network_id < 0)
6017                 network_id = ssid->id;
6018         wpas_notify_p2p_group_started(wpa_s, ssid, network_id, 1);
6019 }
6020
6021
6022 int wpas_p2p_presence_req(struct wpa_supplicant *wpa_s, u32 duration1,
6023                           u32 interval1, u32 duration2, u32 interval2)
6024 {
6025         int ret;
6026
6027         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6028                 return -1;
6029
6030         if (wpa_s->wpa_state < WPA_ASSOCIATED ||
6031             wpa_s->current_ssid == NULL ||
6032             wpa_s->current_ssid->mode != WPAS_MODE_INFRA)
6033                 return -1;
6034
6035         ret = p2p_presence_req(wpa_s->global->p2p, wpa_s->bssid,
6036                                wpa_s->own_addr, wpa_s->assoc_freq,
6037                                duration1, interval1, duration2, interval2);
6038         if (ret == 0)
6039                 wpa_s->waiting_presence_resp = 1;
6040
6041         return ret;
6042 }
6043
6044
6045 int wpas_p2p_ext_listen(struct wpa_supplicant *wpa_s, unsigned int period,
6046                         unsigned int interval)
6047 {
6048         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6049                 return -1;
6050
6051         return p2p_ext_listen(wpa_s->global->p2p, period, interval);
6052 }
6053
6054
6055 static int wpas_p2p_is_client(struct wpa_supplicant *wpa_s)
6056 {
6057         if (wpa_s->current_ssid == NULL) {
6058                 /*
6059                  * current_ssid can be cleared when P2P client interface gets
6060                  * disconnected, so assume this interface was used as P2P
6061                  * client.
6062                  */
6063                 return 1;
6064         }
6065         return wpa_s->current_ssid->p2p_group &&
6066                 wpa_s->current_ssid->mode == WPAS_MODE_INFRA;
6067 }
6068
6069
6070 static void wpas_p2p_group_idle_timeout(void *eloop_ctx, void *timeout_ctx)
6071 {
6072         struct wpa_supplicant *wpa_s = eloop_ctx;
6073
6074         if (wpa_s->conf->p2p_group_idle == 0 && !wpas_p2p_is_client(wpa_s)) {
6075                 wpa_printf(MSG_DEBUG, "P2P: Ignore group idle timeout - "
6076                            "disabled");
6077                 return;
6078         }
6079
6080         wpa_printf(MSG_DEBUG, "P2P: Group idle timeout reached - terminate "
6081                    "group");
6082         wpas_p2p_group_delete(wpa_s, P2P_GROUP_REMOVAL_IDLE_TIMEOUT);
6083 }
6084
6085
6086 static void wpas_p2p_set_group_idle_timeout(struct wpa_supplicant *wpa_s)
6087 {
6088         int timeout;
6089
6090         if (eloop_cancel_timeout(wpas_p2p_group_idle_timeout, wpa_s, NULL) > 0)
6091                 wpa_printf(MSG_DEBUG, "P2P: Cancelled P2P group idle timeout");
6092
6093         if (wpa_s->current_ssid == NULL || !wpa_s->current_ssid->p2p_group)
6094                 return;
6095
6096         timeout = wpa_s->conf->p2p_group_idle;
6097         if (wpa_s->current_ssid->mode == WPAS_MODE_INFRA &&
6098             (timeout == 0 || timeout > P2P_MAX_CLIENT_IDLE))
6099             timeout = P2P_MAX_CLIENT_IDLE;
6100
6101         if (timeout == 0)
6102                 return;
6103
6104         if (timeout < 0) {
6105                 if (wpa_s->current_ssid->mode == WPAS_MODE_INFRA)
6106                         timeout = 0; /* special client mode no-timeout */
6107                 else
6108                         return;
6109         }
6110
6111         if (wpa_s->p2p_in_provisioning) {
6112                 /*
6113                  * Use the normal group formation timeout during the
6114                  * provisioning phase to avoid terminating this process too
6115                  * early due to group idle timeout.
6116                  */
6117                 wpa_printf(MSG_DEBUG, "P2P: Do not use P2P group idle timeout "
6118                            "during provisioning");
6119                 return;
6120         }
6121
6122         if (wpa_s->show_group_started) {
6123                 /*
6124                  * Use the normal group formation timeout between the end of
6125                  * the provisioning phase and completion of 4-way handshake to
6126                  * avoid terminating this process too early due to group idle
6127                  * timeout.
6128                  */
6129                 wpa_printf(MSG_DEBUG, "P2P: Do not use P2P group idle timeout "
6130                            "while waiting for initial 4-way handshake to "
6131                            "complete");
6132                 return;
6133         }
6134
6135         wpa_printf(MSG_DEBUG, "P2P: Set P2P group idle timeout to %u seconds",
6136                    timeout);
6137         eloop_register_timeout(timeout, 0, wpas_p2p_group_idle_timeout,
6138                                wpa_s, NULL);
6139 }
6140
6141
6142 /* Returns 1 if the interface was removed */
6143 int wpas_p2p_deauth_notif(struct wpa_supplicant *wpa_s, const u8 *bssid,
6144                           u16 reason_code, const u8 *ie, size_t ie_len,
6145                           int locally_generated)
6146 {
6147         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6148                 return 0;
6149
6150         if (!locally_generated)
6151                 p2p_deauth_notif(wpa_s->global->p2p, bssid, reason_code, ie,
6152                                  ie_len);
6153
6154         if (reason_code == WLAN_REASON_DEAUTH_LEAVING && !locally_generated &&
6155             wpa_s->current_ssid &&
6156             wpa_s->current_ssid->p2p_group &&
6157             wpa_s->current_ssid->mode == WPAS_MODE_INFRA) {
6158                 wpa_printf(MSG_DEBUG, "P2P: GO indicated that the P2P Group "
6159                            "session is ending");
6160                 if (wpas_p2p_group_delete(wpa_s,
6161                                           P2P_GROUP_REMOVAL_GO_ENDING_SESSION)
6162                     > 0)
6163                         return 1;
6164         }
6165
6166         return 0;
6167 }
6168
6169
6170 void wpas_p2p_disassoc_notif(struct wpa_supplicant *wpa_s, const u8 *bssid,
6171                              u16 reason_code, const u8 *ie, size_t ie_len,
6172                              int locally_generated)
6173 {
6174         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6175                 return;
6176
6177         if (!locally_generated)
6178                 p2p_disassoc_notif(wpa_s->global->p2p, bssid, reason_code, ie,
6179                                    ie_len);
6180 }
6181
6182
6183 void wpas_p2p_update_config(struct wpa_supplicant *wpa_s)
6184 {
6185         struct p2p_data *p2p = wpa_s->global->p2p;
6186
6187         if (p2p == NULL)
6188                 return;
6189
6190         if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_CAPABLE))
6191                 return;
6192
6193         if (wpa_s->conf->changed_parameters & CFG_CHANGED_DEVICE_NAME)
6194                 p2p_set_dev_name(p2p, wpa_s->conf->device_name);
6195
6196         if (wpa_s->conf->changed_parameters & CFG_CHANGED_DEVICE_TYPE)
6197                 p2p_set_pri_dev_type(p2p, wpa_s->conf->device_type);
6198
6199         if (wpa_s->wps &&
6200             (wpa_s->conf->changed_parameters & CFG_CHANGED_CONFIG_METHODS))
6201                 p2p_set_config_methods(p2p, wpa_s->wps->config_methods);
6202
6203         if (wpa_s->wps && (wpa_s->conf->changed_parameters & CFG_CHANGED_UUID))
6204                 p2p_set_uuid(p2p, wpa_s->wps->uuid);
6205
6206         if (wpa_s->conf->changed_parameters & CFG_CHANGED_WPS_STRING) {
6207                 p2p_set_manufacturer(p2p, wpa_s->conf->manufacturer);
6208                 p2p_set_model_name(p2p, wpa_s->conf->model_name);
6209                 p2p_set_model_number(p2p, wpa_s->conf->model_number);
6210                 p2p_set_serial_number(p2p, wpa_s->conf->serial_number);
6211         }
6212
6213         if (wpa_s->conf->changed_parameters & CFG_CHANGED_SEC_DEVICE_TYPE)
6214                 p2p_set_sec_dev_types(p2p,
6215                                       (void *) wpa_s->conf->sec_device_type,
6216                                       wpa_s->conf->num_sec_device_types);
6217
6218         if (wpa_s->conf->changed_parameters & CFG_CHANGED_VENDOR_EXTENSION) {
6219                 int i;
6220                 p2p_remove_wps_vendor_extensions(p2p);
6221                 for (i = 0; i < MAX_WPS_VENDOR_EXT; i++) {
6222                         if (wpa_s->conf->wps_vendor_ext[i] == NULL)
6223                                 continue;
6224                         p2p_add_wps_vendor_extension(
6225                                 p2p, wpa_s->conf->wps_vendor_ext[i]);
6226                 }
6227         }
6228
6229         if ((wpa_s->conf->changed_parameters & CFG_CHANGED_COUNTRY) &&
6230             wpa_s->conf->country[0] && wpa_s->conf->country[1]) {
6231                 char country[3];
6232                 country[0] = wpa_s->conf->country[0];
6233                 country[1] = wpa_s->conf->country[1];
6234                 country[2] = 0x04;
6235                 p2p_set_country(p2p, country);
6236         }
6237
6238         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_SSID_POSTFIX) {
6239                 p2p_set_ssid_postfix(p2p, (u8 *) wpa_s->conf->p2p_ssid_postfix,
6240                                      wpa_s->conf->p2p_ssid_postfix ?
6241                                      os_strlen(wpa_s->conf->p2p_ssid_postfix) :
6242                                      0);
6243         }
6244
6245         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_INTRA_BSS)
6246                 p2p_set_intra_bss_dist(p2p, wpa_s->conf->p2p_intra_bss);
6247
6248         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_LISTEN_CHANNEL) {
6249                 u8 reg_class, channel;
6250                 int ret;
6251                 unsigned int r;
6252                 if (wpa_s->conf->p2p_listen_reg_class &&
6253                     wpa_s->conf->p2p_listen_channel) {
6254                         reg_class = wpa_s->conf->p2p_listen_reg_class;
6255                         channel = wpa_s->conf->p2p_listen_channel;
6256                 } else {
6257                         reg_class = 81;
6258                         /*
6259                          * Pick one of the social channels randomly as the
6260                          * listen channel.
6261                          */
6262                         os_get_random((u8 *) &r, sizeof(r));
6263                         channel = 1 + (r % 3) * 5;
6264                 }
6265                 ret = p2p_set_listen_channel(p2p, reg_class, channel);
6266                 if (ret)
6267                         wpa_printf(MSG_ERROR, "P2P: Own listen channel update "
6268                                    "failed: %d", ret);
6269         }
6270         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_OPER_CHANNEL) {
6271                 u8 op_reg_class, op_channel, cfg_op_channel;
6272                 int ret = 0;
6273                 unsigned int r;
6274                 if (wpa_s->conf->p2p_oper_reg_class &&
6275                     wpa_s->conf->p2p_oper_channel) {
6276                         op_reg_class = wpa_s->conf->p2p_oper_reg_class;
6277                         op_channel = wpa_s->conf->p2p_oper_channel;
6278                         cfg_op_channel = 1;
6279                 } else {
6280                         op_reg_class = 81;
6281                         /*
6282                          * Use random operation channel from (1, 6, 11)
6283                          *if no other preference is indicated.
6284                          */
6285                         os_get_random((u8 *) &r, sizeof(r));
6286                         op_channel = 1 + (r % 3) * 5;
6287                         cfg_op_channel = 0;
6288                 }
6289                 ret = p2p_set_oper_channel(p2p, op_reg_class, op_channel,
6290                                            cfg_op_channel);
6291                 if (ret)
6292                         wpa_printf(MSG_ERROR, "P2P: Own oper channel update "
6293                                    "failed: %d", ret);
6294         }
6295
6296         if (wpa_s->conf->changed_parameters & CFG_CHANGED_P2P_PREF_CHAN) {
6297                 if (p2p_set_pref_chan(p2p, wpa_s->conf->num_p2p_pref_chan,
6298                                       wpa_s->conf->p2p_pref_chan) < 0) {
6299                         wpa_printf(MSG_ERROR, "P2P: Preferred channel list "
6300                                    "update failed");
6301                 }
6302
6303                 if (p2p_set_no_go_freq(p2p, &wpa_s->conf->p2p_no_go_freq) < 0) {
6304                         wpa_printf(MSG_ERROR, "P2P: No GO channel list "
6305                                    "update failed");
6306                 }
6307         }
6308 }
6309
6310
6311 int wpas_p2p_set_noa(struct wpa_supplicant *wpa_s, u8 count, int start,
6312                      int duration)
6313 {
6314         if (!wpa_s->ap_iface)
6315                 return -1;
6316         return hostapd_p2p_set_noa(wpa_s->ap_iface->bss[0], count, start,
6317                                    duration);
6318 }
6319
6320
6321 int wpas_p2p_set_cross_connect(struct wpa_supplicant *wpa_s, int enabled)
6322 {
6323         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6324                 return -1;
6325
6326         wpa_s->global->cross_connection = enabled;
6327         p2p_set_cross_connect(wpa_s->global->p2p, enabled);
6328
6329         if (!enabled) {
6330                 struct wpa_supplicant *iface;
6331
6332                 for (iface = wpa_s->global->ifaces; iface; iface = iface->next)
6333                 {
6334                         if (iface->cross_connect_enabled == 0)
6335                                 continue;
6336
6337                         iface->cross_connect_enabled = 0;
6338                         iface->cross_connect_in_use = 0;
6339                         wpa_msg_global(iface->parent, MSG_INFO,
6340                                        P2P_EVENT_CROSS_CONNECT_DISABLE "%s %s",
6341                                        iface->ifname,
6342                                        iface->cross_connect_uplink);
6343                 }
6344         }
6345
6346         return 0;
6347 }
6348
6349
6350 static void wpas_p2p_enable_cross_connect(struct wpa_supplicant *uplink)
6351 {
6352         struct wpa_supplicant *iface;
6353
6354         if (!uplink->global->cross_connection)
6355                 return;
6356
6357         for (iface = uplink->global->ifaces; iface; iface = iface->next) {
6358                 if (!iface->cross_connect_enabled)
6359                         continue;
6360                 if (os_strcmp(uplink->ifname, iface->cross_connect_uplink) !=
6361                     0)
6362                         continue;
6363                 if (iface->ap_iface == NULL)
6364                         continue;
6365                 if (iface->cross_connect_in_use)
6366                         continue;
6367
6368                 iface->cross_connect_in_use = 1;
6369                 wpa_msg_global(iface->parent, MSG_INFO,
6370                                P2P_EVENT_CROSS_CONNECT_ENABLE "%s %s",
6371                                iface->ifname, iface->cross_connect_uplink);
6372         }
6373 }
6374
6375
6376 static void wpas_p2p_disable_cross_connect(struct wpa_supplicant *uplink)
6377 {
6378         struct wpa_supplicant *iface;
6379
6380         for (iface = uplink->global->ifaces; iface; iface = iface->next) {
6381                 if (!iface->cross_connect_enabled)
6382                         continue;
6383                 if (os_strcmp(uplink->ifname, iface->cross_connect_uplink) !=
6384                     0)
6385                         continue;
6386                 if (!iface->cross_connect_in_use)
6387                         continue;
6388
6389                 wpa_msg_global(iface->parent, MSG_INFO,
6390                                P2P_EVENT_CROSS_CONNECT_DISABLE "%s %s",
6391                                iface->ifname, iface->cross_connect_uplink);
6392                 iface->cross_connect_in_use = 0;
6393         }
6394 }
6395
6396
6397 void wpas_p2p_notif_connected(struct wpa_supplicant *wpa_s)
6398 {
6399         if (wpa_s->ap_iface || wpa_s->current_ssid == NULL ||
6400             wpa_s->current_ssid->mode != WPAS_MODE_INFRA ||
6401             wpa_s->cross_connect_disallowed)
6402                 wpas_p2p_disable_cross_connect(wpa_s);
6403         else
6404                 wpas_p2p_enable_cross_connect(wpa_s);
6405         if (!wpa_s->ap_iface &&
6406             eloop_cancel_timeout(wpas_p2p_group_idle_timeout, wpa_s, NULL) > 0)
6407                 wpa_printf(MSG_DEBUG, "P2P: Cancelled P2P group idle timeout");
6408 }
6409
6410
6411 void wpas_p2p_notif_disconnected(struct wpa_supplicant *wpa_s)
6412 {
6413         wpas_p2p_disable_cross_connect(wpa_s);
6414         if (!wpa_s->ap_iface &&
6415             !eloop_is_timeout_registered(wpas_p2p_group_idle_timeout,
6416                                          wpa_s, NULL))
6417                 wpas_p2p_set_group_idle_timeout(wpa_s);
6418 }
6419
6420
6421 static void wpas_p2p_cross_connect_setup(struct wpa_supplicant *wpa_s)
6422 {
6423         struct wpa_supplicant *iface;
6424
6425         if (!wpa_s->global->cross_connection)
6426                 return;
6427
6428         for (iface = wpa_s->global->ifaces; iface; iface = iface->next) {
6429                 if (iface == wpa_s)
6430                         continue;
6431                 if (iface->drv_flags &
6432                     WPA_DRIVER_FLAGS_P2P_DEDICATED_INTERFACE)
6433                         continue;
6434                 if (iface->drv_flags & WPA_DRIVER_FLAGS_P2P_CAPABLE)
6435                         continue;
6436
6437                 wpa_s->cross_connect_enabled = 1;
6438                 os_strlcpy(wpa_s->cross_connect_uplink, iface->ifname,
6439                            sizeof(wpa_s->cross_connect_uplink));
6440                 wpa_printf(MSG_DEBUG, "P2P: Enable cross connection from "
6441                            "%s to %s whenever uplink is available",
6442                            wpa_s->ifname, wpa_s->cross_connect_uplink);
6443
6444                 if (iface->ap_iface || iface->current_ssid == NULL ||
6445                     iface->current_ssid->mode != WPAS_MODE_INFRA ||
6446                     iface->cross_connect_disallowed ||
6447                     iface->wpa_state != WPA_COMPLETED)
6448                         break;
6449
6450                 wpa_s->cross_connect_in_use = 1;
6451                 wpa_msg_global(wpa_s->parent, MSG_INFO,
6452                                P2P_EVENT_CROSS_CONNECT_ENABLE "%s %s",
6453                                wpa_s->ifname, wpa_s->cross_connect_uplink);
6454                 break;
6455         }
6456 }
6457
6458
6459 int wpas_p2p_notif_pbc_overlap(struct wpa_supplicant *wpa_s)
6460 {
6461         if (wpa_s->p2p_group_interface != P2P_GROUP_INTERFACE_CLIENT &&
6462             !wpa_s->p2p_in_provisioning)
6463                 return 0; /* not P2P client operation */
6464
6465         wpa_printf(MSG_DEBUG, "P2P: Terminate connection due to WPS PBC "
6466                    "session overlap");
6467         if (wpa_s != wpa_s->parent)
6468                 wpa_msg_ctrl(wpa_s->parent, MSG_INFO, WPS_EVENT_OVERLAP);
6469         wpas_p2p_group_formation_failed(wpa_s);
6470         return 1;
6471 }
6472
6473
6474 void wpas_p2p_pbc_overlap_cb(void *eloop_ctx, void *timeout_ctx)
6475 {
6476         struct wpa_supplicant *wpa_s = eloop_ctx;
6477         wpas_p2p_notif_pbc_overlap(wpa_s);
6478 }
6479
6480
6481 void wpas_p2p_update_channel_list(struct wpa_supplicant *wpa_s)
6482 {
6483         struct p2p_channels chan, cli_chan;
6484         struct wpa_supplicant *ifs;
6485
6486         if (wpa_s->global == NULL || wpa_s->global->p2p == NULL)
6487                 return;
6488
6489         os_memset(&chan, 0, sizeof(chan));
6490         os_memset(&cli_chan, 0, sizeof(cli_chan));
6491         if (wpas_p2p_setup_channels(wpa_s, &chan, &cli_chan)) {
6492                 wpa_printf(MSG_ERROR, "P2P: Failed to update supported "
6493                            "channel list");
6494                 return;
6495         }
6496
6497         p2p_update_channel_list(wpa_s->global->p2p, &chan, &cli_chan);
6498
6499         for (ifs = wpa_s->global->ifaces; ifs; ifs = ifs->next) {
6500                 int freq;
6501                 if (!ifs->current_ssid ||
6502                     !ifs->current_ssid->p2p_group ||
6503                     (ifs->current_ssid->mode != WPAS_MODE_P2P_GO &&
6504                      ifs->current_ssid->mode != WPAS_MODE_P2P_GROUP_FORMATION))
6505                                 continue;
6506                 freq = ifs->current_ssid->frequency;
6507                 if (freq_included(&chan, freq)) {
6508                         wpa_dbg(ifs, MSG_DEBUG,
6509                                 "P2P GO operating frequency %d MHz in valid range",
6510                                 freq);
6511                         continue;
6512                 }
6513
6514                 wpa_dbg(ifs, MSG_DEBUG,
6515                         "P2P GO operating in invalid frequency %d MHz", freq);
6516                 /* TODO: Consider using CSA or removing the group within
6517                  * wpa_supplicant */
6518                 wpa_msg(ifs, MSG_INFO, P2P_EVENT_REMOVE_AND_REFORM_GROUP);
6519         }
6520 }
6521
6522
6523 static void wpas_p2p_scan_res_ignore(struct wpa_supplicant *wpa_s,
6524                                      struct wpa_scan_results *scan_res)
6525 {
6526         wpa_printf(MSG_DEBUG, "P2P: Ignore scan results");
6527 }
6528
6529
6530 int wpas_p2p_cancel(struct wpa_supplicant *wpa_s)
6531 {
6532         struct wpa_global *global = wpa_s->global;
6533         int found = 0;
6534         const u8 *peer;
6535
6536         if (global->p2p == NULL)
6537                 return -1;
6538
6539         wpa_printf(MSG_DEBUG, "P2P: Request to cancel group formation");
6540
6541         if (wpa_s->pending_interface_name[0] &&
6542             !is_zero_ether_addr(wpa_s->pending_interface_addr))
6543                 found = 1;
6544
6545         peer = p2p_get_go_neg_peer(global->p2p);
6546         if (peer) {
6547                 wpa_printf(MSG_DEBUG, "P2P: Unauthorize pending GO Neg peer "
6548                            MACSTR, MAC2STR(peer));
6549                 p2p_unauthorize(global->p2p, peer);
6550                 found = 1;
6551         }
6552
6553         if (wpa_s->scan_res_handler == wpas_p2p_scan_res_join) {
6554                 wpa_printf(MSG_DEBUG, "P2P: Stop pending scan for join");
6555                 wpa_s->scan_res_handler = wpas_p2p_scan_res_ignore;
6556                 found = 1;
6557         }
6558
6559         if (wpa_s->pending_pd_before_join) {
6560                 wpa_printf(MSG_DEBUG, "P2P: Stop pending PD before join");
6561                 wpa_s->pending_pd_before_join = 0;
6562                 found = 1;
6563         }
6564
6565         wpas_p2p_stop_find(wpa_s);
6566
6567         for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) {
6568                 if (wpa_s == global->p2p_group_formation &&
6569                     (wpa_s->p2p_in_provisioning ||
6570                      wpa_s->parent->pending_interface_type ==
6571                      WPA_IF_P2P_CLIENT)) {
6572                         wpa_printf(MSG_DEBUG, "P2P: Interface %s in group "
6573                                    "formation found - cancelling",
6574                                    wpa_s->ifname);
6575                         found = 1;
6576                         eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
6577                                              wpa_s->parent, NULL);
6578                         if (wpa_s->p2p_in_provisioning) {
6579                                 wpas_group_formation_completed(wpa_s, 0);
6580                                 break;
6581                         }
6582                         wpas_p2p_group_delete(wpa_s,
6583                                               P2P_GROUP_REMOVAL_REQUESTED);
6584                         break;
6585                 } else if (wpa_s->p2p_in_invitation) {
6586                         wpa_printf(MSG_DEBUG, "P2P: Interface %s in invitation found - cancelling",
6587                                    wpa_s->ifname);
6588                         found = 1;
6589                         wpas_p2p_group_formation_failed(wpa_s);
6590                 }
6591         }
6592
6593         if (!found) {
6594                 wpa_printf(MSG_DEBUG, "P2P: No ongoing group formation found");
6595                 return -1;
6596         }
6597
6598         return 0;
6599 }
6600
6601
6602 void wpas_p2p_interface_unavailable(struct wpa_supplicant *wpa_s)
6603 {
6604         if (wpa_s->current_ssid == NULL || !wpa_s->current_ssid->p2p_group)
6605                 return;
6606
6607         wpa_printf(MSG_DEBUG, "P2P: Remove group due to driver resource not "
6608                    "being available anymore");
6609         wpas_p2p_group_delete(wpa_s, P2P_GROUP_REMOVAL_UNAVAILABLE);
6610 }
6611
6612
6613 void wpas_p2p_update_best_channels(struct wpa_supplicant *wpa_s,
6614                                    int freq_24, int freq_5, int freq_overall)
6615 {
6616         struct p2p_data *p2p = wpa_s->global->p2p;
6617         if (p2p == NULL)
6618                 return;
6619         p2p_set_best_channels(p2p, freq_24, freq_5, freq_overall);
6620 }
6621
6622
6623 int wpas_p2p_unauthorize(struct wpa_supplicant *wpa_s, const char *addr)
6624 {
6625         u8 peer[ETH_ALEN];
6626         struct p2p_data *p2p = wpa_s->global->p2p;
6627
6628         if (p2p == NULL)
6629                 return -1;
6630
6631         if (hwaddr_aton(addr, peer))
6632                 return -1;
6633
6634         return p2p_unauthorize(p2p, peer);
6635 }
6636
6637
6638 /**
6639  * wpas_p2p_disconnect - Disconnect from a P2P Group
6640  * @wpa_s: Pointer to wpa_supplicant data
6641  * Returns: 0 on success, -1 on failure
6642  *
6643  * This can be used to disconnect from a group in which the local end is a P2P
6644  * Client or to end a P2P Group in case the local end is the Group Owner. If a
6645  * virtual network interface was created for this group, that interface will be
6646  * removed. Otherwise, only the configured P2P group network will be removed
6647  * from the interface.
6648  */
6649 int wpas_p2p_disconnect(struct wpa_supplicant *wpa_s)
6650 {
6651
6652         if (wpa_s == NULL)
6653                 return -1;
6654
6655         return wpas_p2p_group_delete(wpa_s, P2P_GROUP_REMOVAL_REQUESTED) < 0 ?
6656                 -1 : 0;
6657 }
6658
6659
6660 int wpas_p2p_in_progress(struct wpa_supplicant *wpa_s)
6661 {
6662         int ret;
6663
6664         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
6665                 return 0;
6666
6667         ret = p2p_in_progress(wpa_s->global->p2p);
6668         if (ret == 0) {
6669                 /*
6670                  * Check whether there is an ongoing WPS provisioning step (or
6671                  * other parts of group formation) on another interface since
6672                  * p2p_in_progress() does not report this to avoid issues for
6673                  * scans during such provisioning step.
6674                  */
6675                 if (wpa_s->global->p2p_group_formation &&
6676                     wpa_s->global->p2p_group_formation != wpa_s) {
6677                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Another interface (%s) "
6678                                 "in group formation",
6679                                 wpa_s->global->p2p_group_formation->ifname);
6680                         ret = 1;
6681                 }
6682         }
6683
6684         if (!ret && wpa_s->global->p2p_go_wait_client.sec) {
6685                 struct os_reltime now;
6686                 os_get_reltime(&now);
6687                 if (os_reltime_expired(&now, &wpa_s->global->p2p_go_wait_client,
6688                                        P2P_MAX_INITIAL_CONN_WAIT_GO)) {
6689                         /* Wait for the first client has expired */
6690                         wpa_s->global->p2p_go_wait_client.sec = 0;
6691                 } else {
6692                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Waiting for initial client connection during group formation");
6693                         ret = 1;
6694                 }
6695         }
6696
6697         return ret;
6698 }
6699
6700
6701 void wpas_p2p_network_removed(struct wpa_supplicant *wpa_s,
6702                               struct wpa_ssid *ssid)
6703 {
6704         if (wpa_s->p2p_in_provisioning && ssid->p2p_group &&
6705             eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
6706                                  wpa_s->parent, NULL) > 0) {
6707                 /**
6708                  * Remove the network by scheduling the group formation
6709                  * timeout to happen immediately. The teardown code
6710                  * needs to be scheduled to run asynch later so that we
6711                  * don't delete data from under ourselves unexpectedly.
6712                  * Calling wpas_p2p_group_formation_timeout directly
6713                  * causes a series of crashes in WPS failure scenarios.
6714                  */
6715                 wpa_printf(MSG_DEBUG, "P2P: Canceled group formation due to "
6716                            "P2P group network getting removed");
6717                 eloop_register_timeout(0, 0, wpas_p2p_group_formation_timeout,
6718                                        wpa_s->parent, NULL);
6719         }
6720 }
6721
6722
6723 struct wpa_ssid * wpas_p2p_get_persistent(struct wpa_supplicant *wpa_s,
6724                                           const u8 *addr, const u8 *ssid,
6725                                           size_t ssid_len)
6726 {
6727         struct wpa_ssid *s;
6728         size_t i;
6729
6730         for (s = wpa_s->conf->ssid; s; s = s->next) {
6731                 if (s->disabled != 2)
6732                         continue;
6733                 if (ssid &&
6734                     (ssid_len != s->ssid_len ||
6735                      os_memcmp(ssid, s->ssid, ssid_len) != 0))
6736                         continue;
6737                 if (addr == NULL) {
6738                         if (s->mode == WPAS_MODE_P2P_GO)
6739                                 return s;
6740                         continue;
6741                 }
6742                 if (os_memcmp(s->bssid, addr, ETH_ALEN) == 0)
6743                         return s; /* peer is GO in the persistent group */
6744                 if (s->mode != WPAS_MODE_P2P_GO || s->p2p_client_list == NULL)
6745                         continue;
6746                 for (i = 0; i < s->num_p2p_clients; i++) {
6747                         if (os_memcmp(s->p2p_client_list + i * ETH_ALEN,
6748                                       addr, ETH_ALEN) == 0)
6749                                 return s; /* peer is P2P client in persistent
6750                                            * group */
6751                 }
6752         }
6753
6754         return NULL;
6755 }
6756
6757
6758 void wpas_p2p_notify_ap_sta_authorized(struct wpa_supplicant *wpa_s,
6759                                        const u8 *addr)
6760 {
6761         if (eloop_cancel_timeout(wpas_p2p_group_formation_timeout,
6762                                  wpa_s->parent, NULL) > 0) {
6763                 /*
6764                  * This can happen if WPS provisioning step is not terminated
6765                  * cleanly (e.g., P2P Client does not send WSC_Done). Since the
6766                  * peer was able to connect, there is no need to time out group
6767                  * formation after this, though. In addition, this is used with
6768                  * the initial connection wait on the GO as a separate formation
6769                  * timeout and as such, expected to be hit after the initial WPS
6770                  * provisioning step.
6771                  */
6772                 wpa_printf(MSG_DEBUG, "P2P: Canceled P2P group formation timeout on data connection");
6773         }
6774         if (!wpa_s->p2p_go_group_formation_completed) {
6775                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Marking group formation completed on GO on first data connection");
6776                 wpa_s->p2p_go_group_formation_completed = 1;
6777                 wpa_s->global->p2p_group_formation = NULL;
6778                 wpa_s->p2p_in_provisioning = 0;
6779                 wpa_s->p2p_in_invitation = 0;
6780         }
6781         wpa_s->global->p2p_go_wait_client.sec = 0;
6782         if (addr == NULL)
6783                 return;
6784         wpas_p2p_add_persistent_group_client(wpa_s, addr);
6785 }
6786
6787
6788 static void wpas_p2p_fallback_to_go_neg(struct wpa_supplicant *wpa_s,
6789                                         int group_added)
6790 {
6791         struct wpa_supplicant *group = wpa_s;
6792         if (wpa_s->global->p2p_group_formation)
6793                 group = wpa_s->global->p2p_group_formation;
6794         wpa_s = wpa_s->parent;
6795         offchannel_send_action_done(wpa_s);
6796         if (group_added)
6797                 wpas_p2p_group_delete(group, P2P_GROUP_REMOVAL_SILENT);
6798         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Fall back to GO Negotiation");
6799         wpas_p2p_connect(wpa_s, wpa_s->pending_join_dev_addr, wpa_s->p2p_pin,
6800                          wpa_s->p2p_wps_method, wpa_s->p2p_persistent_group, 0,
6801                          0, 0, wpa_s->p2p_go_intent, wpa_s->p2p_connect_freq,
6802                          wpa_s->p2p_persistent_id,
6803                          wpa_s->p2p_pd_before_go_neg,
6804                          wpa_s->p2p_go_ht40,
6805                          wpa_s->p2p_go_vht);
6806 }
6807
6808
6809 int wpas_p2p_scan_no_go_seen(struct wpa_supplicant *wpa_s)
6810 {
6811         if (!wpa_s->p2p_fallback_to_go_neg ||
6812             wpa_s->p2p_in_provisioning <= 5)
6813                 return 0;
6814
6815         if (wpas_p2p_peer_go(wpa_s, wpa_s->pending_join_dev_addr) > 0)
6816                 return 0; /* peer operating as a GO */
6817
6818         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: GO not found for p2p_connect-auto - "
6819                 "fallback to GO Negotiation");
6820         wpas_p2p_fallback_to_go_neg(wpa_s, 1);
6821
6822         return 1;
6823 }
6824
6825
6826 unsigned int wpas_p2p_search_delay(struct wpa_supplicant *wpa_s)
6827 {
6828         struct wpa_supplicant *ifs;
6829
6830         if (wpa_s->wpa_state > WPA_SCANNING) {
6831                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Use %u ms search delay due to "
6832                         "concurrent operation",
6833                         wpa_s->conf->p2p_search_delay);
6834                 return wpa_s->conf->p2p_search_delay;
6835         }
6836
6837         dl_list_for_each(ifs, &wpa_s->radio->ifaces, struct wpa_supplicant,
6838                          radio_list) {
6839                 if (ifs != wpa_s && ifs->wpa_state > WPA_SCANNING) {
6840                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Use %u ms search "
6841                                 "delay due to concurrent operation on "
6842                                 "interface %s",
6843                                 wpa_s->conf->p2p_search_delay,
6844                                 ifs->ifname);
6845                         return wpa_s->conf->p2p_search_delay;
6846                 }
6847         }
6848
6849         return 0;
6850 }
6851
6852
6853 static int wpas_p2p_remove_psk_entry(struct wpa_supplicant *wpa_s,
6854                                      struct wpa_ssid *s, const u8 *addr,
6855                                      int iface_addr)
6856 {
6857         struct psk_list_entry *psk, *tmp;
6858         int changed = 0;
6859
6860         dl_list_for_each_safe(psk, tmp, &s->psk_list, struct psk_list_entry,
6861                               list) {
6862                 if ((iface_addr && !psk->p2p &&
6863                      os_memcmp(addr, psk->addr, ETH_ALEN) == 0) ||
6864                     (!iface_addr && psk->p2p &&
6865                      os_memcmp(addr, psk->addr, ETH_ALEN) == 0)) {
6866                         wpa_dbg(wpa_s, MSG_DEBUG,
6867                                 "P2P: Remove persistent group PSK list entry for "
6868                                 MACSTR " p2p=%u",
6869                                 MAC2STR(psk->addr), psk->p2p);
6870                         dl_list_del(&psk->list);
6871                         os_free(psk);
6872                         changed++;
6873                 }
6874         }
6875
6876         return changed;
6877 }
6878
6879
6880 void wpas_p2p_new_psk_cb(struct wpa_supplicant *wpa_s, const u8 *mac_addr,
6881                          const u8 *p2p_dev_addr,
6882                          const u8 *psk, size_t psk_len)
6883 {
6884         struct wpa_ssid *ssid = wpa_s->current_ssid;
6885         struct wpa_ssid *persistent;
6886         struct psk_list_entry *p, *last;
6887
6888         if (psk_len != sizeof(p->psk))
6889                 return;
6890
6891         if (p2p_dev_addr) {
6892                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: New PSK for addr=" MACSTR
6893                         " p2p_dev_addr=" MACSTR,
6894                         MAC2STR(mac_addr), MAC2STR(p2p_dev_addr));
6895                 if (is_zero_ether_addr(p2p_dev_addr))
6896                         p2p_dev_addr = NULL;
6897         } else {
6898                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: New PSK for addr=" MACSTR,
6899                         MAC2STR(mac_addr));
6900         }
6901
6902         if (ssid->mode == WPAS_MODE_P2P_GROUP_FORMATION) {
6903                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: new_psk_cb during group formation");
6904                 /* To be added to persistent group once created */
6905                 if (wpa_s->global->add_psk == NULL) {
6906                         wpa_s->global->add_psk = os_zalloc(sizeof(*p));
6907                         if (wpa_s->global->add_psk == NULL)
6908                                 return;
6909                 }
6910                 p = wpa_s->global->add_psk;
6911                 if (p2p_dev_addr) {
6912                         p->p2p = 1;
6913                         os_memcpy(p->addr, p2p_dev_addr, ETH_ALEN);
6914                 } else {
6915                         p->p2p = 0;
6916                         os_memcpy(p->addr, mac_addr, ETH_ALEN);
6917                 }
6918                 os_memcpy(p->psk, psk, psk_len);
6919                 return;
6920         }
6921
6922         if (ssid->mode != WPAS_MODE_P2P_GO || !ssid->p2p_persistent_group) {
6923                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Ignore new_psk_cb on not-persistent GO");
6924                 return;
6925         }
6926
6927         persistent = wpas_p2p_get_persistent(wpa_s->parent, NULL, ssid->ssid,
6928                                              ssid->ssid_len);
6929         if (!persistent) {
6930                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Could not find persistent group information to store the new PSK");
6931                 return;
6932         }
6933
6934         p = os_zalloc(sizeof(*p));
6935         if (p == NULL)
6936                 return;
6937         if (p2p_dev_addr) {
6938                 p->p2p = 1;
6939                 os_memcpy(p->addr, p2p_dev_addr, ETH_ALEN);
6940         } else {
6941                 p->p2p = 0;
6942                 os_memcpy(p->addr, mac_addr, ETH_ALEN);
6943         }
6944         os_memcpy(p->psk, psk, psk_len);
6945
6946         if (dl_list_len(&persistent->psk_list) > P2P_MAX_STORED_CLIENTS &&
6947             (last = dl_list_last(&persistent->psk_list,
6948                                  struct psk_list_entry, list))) {
6949                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Remove oldest PSK entry for "
6950                         MACSTR " (p2p=%u) to make room for a new one",
6951                         MAC2STR(last->addr), last->p2p);
6952                 dl_list_del(&last->list);
6953                 os_free(last);
6954         }
6955
6956         wpas_p2p_remove_psk_entry(wpa_s->parent, persistent,
6957                                   p2p_dev_addr ? p2p_dev_addr : mac_addr,
6958                                   p2p_dev_addr == NULL);
6959         if (p2p_dev_addr) {
6960                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Add new PSK for p2p_dev_addr="
6961                         MACSTR, MAC2STR(p2p_dev_addr));
6962         } else {
6963                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Add new PSK for addr=" MACSTR,
6964                         MAC2STR(mac_addr));
6965         }
6966         dl_list_add(&persistent->psk_list, &p->list);
6967
6968         if (wpa_s->parent->conf->update_config &&
6969             wpa_config_write(wpa_s->parent->confname, wpa_s->parent->conf))
6970                 wpa_printf(MSG_DEBUG, "P2P: Failed to update configuration");
6971 }
6972
6973
6974 static void wpas_p2p_remove_psk(struct wpa_supplicant *wpa_s,
6975                                 struct wpa_ssid *s, const u8 *addr,
6976                                 int iface_addr)
6977 {
6978         int res;
6979
6980         res = wpas_p2p_remove_psk_entry(wpa_s, s, addr, iface_addr);
6981         if (res > 0 && wpa_s->conf->update_config &&
6982             wpa_config_write(wpa_s->confname, wpa_s->conf))
6983                 wpa_dbg(wpa_s, MSG_DEBUG,
6984                         "P2P: Failed to update configuration");
6985 }
6986
6987
6988 static void wpas_p2p_remove_client_go(struct wpa_supplicant *wpa_s,
6989                                       const u8 *peer, int iface_addr)
6990 {
6991         struct hostapd_data *hapd;
6992         struct hostapd_wpa_psk *psk, *prev, *rem;
6993         struct sta_info *sta;
6994
6995         if (wpa_s->ap_iface == NULL || wpa_s->current_ssid == NULL ||
6996             wpa_s->current_ssid->mode != WPAS_MODE_P2P_GO)
6997                 return;
6998
6999         /* Remove per-station PSK entry */
7000         hapd = wpa_s->ap_iface->bss[0];
7001         prev = NULL;
7002         psk = hapd->conf->ssid.wpa_psk;
7003         while (psk) {
7004                 if ((iface_addr && os_memcmp(peer, psk->addr, ETH_ALEN) == 0) ||
7005                     (!iface_addr &&
7006                      os_memcmp(peer, psk->p2p_dev_addr, ETH_ALEN) == 0)) {
7007                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Remove operating group PSK entry for "
7008                                 MACSTR " iface_addr=%d",
7009                                 MAC2STR(peer), iface_addr);
7010                         if (prev)
7011                                 prev->next = psk->next;
7012                         else
7013                                 hapd->conf->ssid.wpa_psk = psk->next;
7014                         rem = psk;
7015                         psk = psk->next;
7016                         os_free(rem);
7017                 } else {
7018                         prev = psk;
7019                         psk = psk->next;
7020                 }
7021         }
7022
7023         /* Disconnect from group */
7024         if (iface_addr)
7025                 sta = ap_get_sta(hapd, peer);
7026         else
7027                 sta = ap_get_sta_p2p(hapd, peer);
7028         if (sta) {
7029                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Disconnect peer " MACSTR
7030                         " (iface_addr=%d) from group",
7031                         MAC2STR(peer), iface_addr);
7032                 hostapd_drv_sta_deauth(hapd, sta->addr,
7033                                        WLAN_REASON_DEAUTH_LEAVING);
7034                 ap_sta_deauthenticate(hapd, sta, WLAN_REASON_DEAUTH_LEAVING);
7035         }
7036 }
7037
7038
7039 void wpas_p2p_remove_client(struct wpa_supplicant *wpa_s, const u8 *peer,
7040                             int iface_addr)
7041 {
7042         struct wpa_ssid *s;
7043         struct wpa_supplicant *w;
7044
7045         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Remove client " MACSTR, MAC2STR(peer));
7046
7047         /* Remove from any persistent group */
7048         for (s = wpa_s->parent->conf->ssid; s; s = s->next) {
7049                 if (s->disabled != 2 || s->mode != WPAS_MODE_P2P_GO)
7050                         continue;
7051                 if (!iface_addr)
7052                         wpas_remove_persistent_peer(wpa_s, s, peer, 0);
7053                 wpas_p2p_remove_psk(wpa_s->parent, s, peer, iface_addr);
7054         }
7055
7056         /* Remove from any operating group */
7057         for (w = wpa_s->global->ifaces; w; w = w->next)
7058                 wpas_p2p_remove_client_go(w, peer, iface_addr);
7059 }
7060
7061
7062 static void wpas_p2p_psk_failure_removal(void *eloop_ctx, void *timeout_ctx)
7063 {
7064         struct wpa_supplicant *wpa_s = eloop_ctx;
7065         wpas_p2p_group_delete(wpa_s, P2P_GROUP_REMOVAL_PSK_FAILURE);
7066 }
7067
7068
7069 static void wpas_p2p_group_freq_conflict(void *eloop_ctx, void *timeout_ctx)
7070 {
7071         struct wpa_supplicant *wpa_s = eloop_ctx;
7072
7073         wpa_printf(MSG_DEBUG, "P2P: Frequency conflict - terminate group");
7074         wpas_p2p_group_delete(wpa_s, P2P_GROUP_REMOVAL_FREQ_CONFLICT);
7075 }
7076
7077
7078 int wpas_p2p_handle_frequency_conflicts(struct wpa_supplicant *wpa_s, int freq,
7079                                         struct wpa_ssid *ssid)
7080 {
7081         struct wpa_supplicant *iface;
7082
7083         for (iface = wpa_s->global->ifaces; iface; iface = iface->next) {
7084                 if (!iface->current_ssid ||
7085                     iface->current_ssid->frequency == freq ||
7086                     (iface->p2p_group_interface == NOT_P2P_GROUP_INTERFACE &&
7087                      !iface->current_ssid->p2p_group))
7088                         continue;
7089
7090                 /* Remove the connection with least priority */
7091                 if (!wpas_is_p2p_prioritized(iface)) {
7092                         /* STA connection has priority over existing
7093                          * P2P connection, so remove the interface. */
7094                         wpa_printf(MSG_DEBUG, "P2P: Removing P2P connection due to single channel concurrent mode frequency conflict");
7095                         eloop_register_timeout(0, 0,
7096                                                wpas_p2p_group_freq_conflict,
7097                                                iface, NULL);
7098                         /* If connection in progress is P2P connection, do not
7099                          * proceed for the connection. */
7100                         if (wpa_s == iface)
7101                                 return -1;
7102                         else
7103                                 return 0;
7104                 } else {
7105                         /* P2P connection has priority, disable the STA network
7106                          */
7107                         wpa_supplicant_disable_network(wpa_s->global->ifaces,
7108                                                        ssid);
7109                         wpa_msg(wpa_s->global->ifaces, MSG_INFO,
7110                                 WPA_EVENT_FREQ_CONFLICT " id=%d", ssid->id);
7111                         os_memset(wpa_s->global->ifaces->pending_bssid, 0,
7112                                   ETH_ALEN);
7113                         /* If P2P connection is in progress, continue
7114                          * connecting...*/
7115                         if (wpa_s == iface)
7116                                 return 0;
7117                         else
7118                                 return -1;
7119                 }
7120         }
7121
7122         return 0;
7123 }
7124
7125
7126 int wpas_p2p_4way_hs_failed(struct wpa_supplicant *wpa_s)
7127 {
7128         struct wpa_ssid *ssid = wpa_s->current_ssid;
7129
7130         if (ssid == NULL || !ssid->p2p_group)
7131                 return 0;
7132
7133         if (wpa_s->p2p_last_4way_hs_fail &&
7134             wpa_s->p2p_last_4way_hs_fail == ssid) {
7135                 u8 go_dev_addr[ETH_ALEN];
7136                 struct wpa_ssid *persistent;
7137
7138                 if (wpas_p2p_persistent_group(wpa_s, go_dev_addr,
7139                                               ssid->ssid,
7140                                               ssid->ssid_len) <= 0) {
7141                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Could not determine whether 4-way handshake failures were for a persistent group");
7142                         goto disconnect;
7143                 }
7144
7145                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: Two 4-way handshake failures for a P2P group - go_dev_addr="
7146                         MACSTR, MAC2STR(go_dev_addr));
7147                 persistent = wpas_p2p_get_persistent(wpa_s->parent, go_dev_addr,
7148                                                      ssid->ssid,
7149                                                      ssid->ssid_len);
7150                 if (persistent == NULL || persistent->mode != WPAS_MODE_INFRA) {
7151                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: No matching persistent group stored");
7152                         goto disconnect;
7153                 }
7154                 wpa_msg_global(wpa_s->parent, MSG_INFO,
7155                                P2P_EVENT_PERSISTENT_PSK_FAIL "%d",
7156                                persistent->id);
7157         disconnect:
7158                 wpa_s->p2p_last_4way_hs_fail = NULL;
7159                 /*
7160                  * Remove the group from a timeout to avoid issues with caller
7161                  * continuing to use the interface if this is on a P2P group
7162                  * interface.
7163                  */
7164                 eloop_register_timeout(0, 0, wpas_p2p_psk_failure_removal,
7165                                        wpa_s, NULL);
7166                 return 1;
7167         }
7168
7169         wpa_s->p2p_last_4way_hs_fail = ssid;
7170         return 0;
7171 }
7172
7173
7174 #ifdef CONFIG_WPS_NFC
7175
7176 static struct wpabuf * wpas_p2p_nfc_handover(int ndef, struct wpabuf *wsc,
7177                                              struct wpabuf *p2p)
7178 {
7179         struct wpabuf *ret;
7180         size_t wsc_len;
7181
7182         if (p2p == NULL) {
7183                 wpabuf_free(wsc);
7184                 wpa_printf(MSG_DEBUG, "P2P: No p2p buffer for handover");
7185                 return NULL;
7186         }
7187
7188         wsc_len = wsc ? wpabuf_len(wsc) : 0;
7189         ret = wpabuf_alloc(2 + wsc_len + 2 + wpabuf_len(p2p));
7190         if (ret == NULL) {
7191                 wpabuf_free(wsc);
7192                 wpabuf_free(p2p);
7193                 return NULL;
7194         }
7195
7196         wpabuf_put_be16(ret, wsc_len);
7197         if (wsc)
7198                 wpabuf_put_buf(ret, wsc);
7199         wpabuf_put_be16(ret, wpabuf_len(p2p));
7200         wpabuf_put_buf(ret, p2p);
7201
7202         wpabuf_free(wsc);
7203         wpabuf_free(p2p);
7204         wpa_hexdump_buf(MSG_DEBUG,
7205                         "P2P: Generated NFC connection handover message", ret);
7206
7207         if (ndef && ret) {
7208                 struct wpabuf *tmp;
7209                 tmp = ndef_build_p2p(ret);
7210                 wpabuf_free(ret);
7211                 if (tmp == NULL) {
7212                         wpa_printf(MSG_DEBUG, "P2P: Failed to NDEF encapsulate handover request");
7213                         return NULL;
7214                 }
7215                 ret = tmp;
7216         }
7217
7218         return ret;
7219 }
7220
7221
7222 static int wpas_p2p_cli_freq(struct wpa_supplicant *wpa_s,
7223                              struct wpa_ssid **ssid, u8 *go_dev_addr)
7224 {
7225         struct wpa_supplicant *iface;
7226
7227         if (go_dev_addr)
7228                 os_memset(go_dev_addr, 0, ETH_ALEN);
7229         if (ssid)
7230                 *ssid = NULL;
7231         for (iface = wpa_s->global->ifaces; iface; iface = iface->next) {
7232                 if (iface->wpa_state < WPA_ASSOCIATING ||
7233                     iface->current_ssid == NULL || iface->assoc_freq == 0 ||
7234                     !iface->current_ssid->p2p_group ||
7235                     iface->current_ssid->mode != WPAS_MODE_INFRA)
7236                         continue;
7237                 if (ssid)
7238                         *ssid = iface->current_ssid;
7239                 if (go_dev_addr)
7240                         os_memcpy(go_dev_addr, iface->go_dev_addr, ETH_ALEN);
7241                 return iface->assoc_freq;
7242         }
7243         return 0;
7244 }
7245
7246
7247 struct wpabuf * wpas_p2p_nfc_handover_req(struct wpa_supplicant *wpa_s,
7248                                           int ndef)
7249 {
7250         struct wpabuf *wsc, *p2p;
7251         struct wpa_ssid *ssid;
7252         u8 go_dev_addr[ETH_ALEN];
7253         int cli_freq = wpas_p2p_cli_freq(wpa_s, &ssid, go_dev_addr);
7254
7255         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL) {
7256                 wpa_printf(MSG_DEBUG, "P2P: P2P disabled - cannot build handover request");
7257                 return NULL;
7258         }
7259
7260         if (wpa_s->conf->wps_nfc_dh_pubkey == NULL &&
7261             wps_nfc_gen_dh(&wpa_s->conf->wps_nfc_dh_pubkey,
7262                            &wpa_s->conf->wps_nfc_dh_privkey) < 0) {
7263                 wpa_dbg(wpa_s, MSG_DEBUG, "P2P: No DH key available for handover request");
7264                 return NULL;
7265         }
7266
7267         if (cli_freq == 0) {
7268                 wsc = wps_build_nfc_handover_req_p2p(
7269                         wpa_s->parent->wps, wpa_s->conf->wps_nfc_dh_pubkey);
7270         } else
7271                 wsc = NULL;
7272         p2p = p2p_build_nfc_handover_req(wpa_s->global->p2p, cli_freq,
7273                                          go_dev_addr, ssid ? ssid->ssid : NULL,
7274                                          ssid ? ssid->ssid_len : 0);
7275
7276         return wpas_p2p_nfc_handover(ndef, wsc, p2p);
7277 }
7278
7279
7280 struct wpabuf * wpas_p2p_nfc_handover_sel(struct wpa_supplicant *wpa_s,
7281                                           int ndef, int tag)
7282 {
7283         struct wpabuf *wsc, *p2p;
7284         struct wpa_ssid *ssid;
7285         u8 go_dev_addr[ETH_ALEN];
7286         int cli_freq = wpas_p2p_cli_freq(wpa_s, &ssid, go_dev_addr);
7287
7288         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
7289                 return NULL;
7290
7291         if (!tag && wpa_s->conf->wps_nfc_dh_pubkey == NULL &&
7292             wps_nfc_gen_dh(&wpa_s->conf->wps_nfc_dh_pubkey,
7293                            &wpa_s->conf->wps_nfc_dh_privkey) < 0)
7294                 return NULL;
7295
7296         if (cli_freq == 0) {
7297                 wsc = wps_build_nfc_handover_sel_p2p(
7298                         wpa_s->parent->wps,
7299                         tag ? wpa_s->conf->wps_nfc_dev_pw_id :
7300                         DEV_PW_NFC_CONNECTION_HANDOVER,
7301                         wpa_s->conf->wps_nfc_dh_pubkey,
7302                         tag ? wpa_s->conf->wps_nfc_dev_pw : NULL);
7303         } else
7304                 wsc = NULL;
7305         p2p = p2p_build_nfc_handover_sel(wpa_s->global->p2p, cli_freq,
7306                                          go_dev_addr, ssid ? ssid->ssid : NULL,
7307                                          ssid ? ssid->ssid_len : 0);
7308
7309         return wpas_p2p_nfc_handover(ndef, wsc, p2p);
7310 }
7311
7312
7313 static int wpas_p2p_nfc_join_group(struct wpa_supplicant *wpa_s,
7314                                    struct p2p_nfc_params *params)
7315 {
7316         wpa_printf(MSG_DEBUG, "P2P: Initiate join-group based on NFC "
7317                    "connection handover (freq=%d)",
7318                    params->go_freq);
7319
7320         if (params->go_freq && params->go_ssid_len) {
7321                 wpa_s->p2p_wps_method = WPS_NFC;
7322                 wpa_s->pending_join_wps_method = WPS_NFC;
7323                 os_memset(wpa_s->pending_join_iface_addr, 0, ETH_ALEN);
7324                 os_memcpy(wpa_s->pending_join_dev_addr, params->go_dev_addr,
7325                           ETH_ALEN);
7326                 return wpas_p2p_join_start(wpa_s, params->go_freq,
7327                                            params->go_ssid,
7328                                            params->go_ssid_len);
7329         }
7330
7331         return wpas_p2p_connect(wpa_s, params->peer->p2p_device_addr, NULL,
7332                                 WPS_NFC, 0, 0, 1, 0, wpa_s->conf->p2p_go_intent,
7333                                 params->go_freq, -1, 0, 1, 1);
7334 }
7335
7336
7337 static int wpas_p2p_nfc_auth_join(struct wpa_supplicant *wpa_s,
7338                                   struct p2p_nfc_params *params, int tag)
7339 {
7340         int res, persistent;
7341         struct wpa_ssid *ssid;
7342
7343         wpa_printf(MSG_DEBUG, "P2P: Authorize join-group based on NFC "
7344                    "connection handover");
7345         for (wpa_s = wpa_s->global->ifaces; wpa_s; wpa_s = wpa_s->next) {
7346                 ssid = wpa_s->current_ssid;
7347                 if (ssid == NULL)
7348                         continue;
7349                 if (ssid->mode != WPAS_MODE_P2P_GO)
7350                         continue;
7351                 if (wpa_s->ap_iface == NULL)
7352                         continue;
7353                 break;
7354         }
7355         if (wpa_s == NULL) {
7356                 wpa_printf(MSG_DEBUG, "P2P: Could not find GO interface");
7357                 return -1;
7358         }
7359
7360         if (wpa_s->parent->p2p_oob_dev_pw_id !=
7361             DEV_PW_NFC_CONNECTION_HANDOVER &&
7362             !wpa_s->parent->p2p_oob_dev_pw) {
7363                 wpa_printf(MSG_DEBUG, "P2P: No NFC Dev Pw known");
7364                 return -1;
7365         }
7366         res = wpas_ap_wps_add_nfc_pw(
7367                 wpa_s, wpa_s->parent->p2p_oob_dev_pw_id,
7368                 wpa_s->parent->p2p_oob_dev_pw,
7369                 wpa_s->parent->p2p_peer_oob_pk_hash_known ?
7370                 wpa_s->parent->p2p_peer_oob_pubkey_hash : NULL);
7371         if (res)
7372                 return res;
7373
7374         if (!tag) {
7375                 wpa_printf(MSG_DEBUG, "P2P: Negotiated handover - wait for peer to join without invitation");
7376                 return 0;
7377         }
7378
7379         if (!params->peer ||
7380             !(params->peer->dev_capab & P2P_DEV_CAPAB_INVITATION_PROCEDURE))
7381                 return 0;
7382
7383         wpa_printf(MSG_DEBUG, "P2P: Static handover - invite peer " MACSTR
7384                    " to join", MAC2STR(params->peer->p2p_device_addr));
7385
7386         wpa_s->global->p2p_invite_group = wpa_s;
7387         persistent = ssid->p2p_persistent_group &&
7388                 wpas_p2p_get_persistent(wpa_s->parent,
7389                                         params->peer->p2p_device_addr,
7390                                         ssid->ssid, ssid->ssid_len);
7391         wpa_s->parent->pending_invite_ssid_id = -1;
7392
7393         return p2p_invite(wpa_s->global->p2p, params->peer->p2p_device_addr,
7394                           P2P_INVITE_ROLE_ACTIVE_GO, wpa_s->own_addr,
7395                           ssid->ssid, ssid->ssid_len, ssid->frequency,
7396                           wpa_s->global->p2p_dev_addr, persistent, 0,
7397                           wpa_s->parent->p2p_oob_dev_pw_id);
7398 }
7399
7400
7401 static int wpas_p2p_nfc_init_go_neg(struct wpa_supplicant *wpa_s,
7402                                     struct p2p_nfc_params *params,
7403                                     int forced_freq)
7404 {
7405         wpa_printf(MSG_DEBUG, "P2P: Initiate GO Negotiation based on NFC "
7406                    "connection handover");
7407         return wpas_p2p_connect(wpa_s, params->peer->p2p_device_addr, NULL,
7408                                 WPS_NFC, 0, 0, 0, 0, wpa_s->conf->p2p_go_intent,
7409                                 forced_freq, -1, 0, 1, 1);
7410 }
7411
7412
7413 static int wpas_p2p_nfc_resp_go_neg(struct wpa_supplicant *wpa_s,
7414                                     struct p2p_nfc_params *params,
7415                                     int forced_freq)
7416 {
7417         int res;
7418
7419         wpa_printf(MSG_DEBUG, "P2P: Authorize GO Negotiation based on NFC "
7420                    "connection handover");
7421         res = wpas_p2p_connect(wpa_s, params->peer->p2p_device_addr, NULL,
7422                                WPS_NFC, 0, 0, 0, 1, wpa_s->conf->p2p_go_intent,
7423                                forced_freq, -1, 0, 1, 1);
7424         if (res)
7425                 return res;
7426
7427         res = wpas_p2p_listen(wpa_s, 60);
7428         if (res) {
7429                 p2p_unauthorize(wpa_s->global->p2p,
7430                                 params->peer->p2p_device_addr);
7431         }
7432
7433         return res;
7434 }
7435
7436
7437 static int wpas_p2p_nfc_connection_handover(struct wpa_supplicant *wpa_s,
7438                                             const struct wpabuf *data,
7439                                             int sel, int tag, int forced_freq)
7440 {
7441         const u8 *pos, *end;
7442         u16 len, id;
7443         struct p2p_nfc_params params;
7444         int res;
7445
7446         os_memset(&params, 0, sizeof(params));
7447         params.sel = sel;
7448
7449         wpa_hexdump_buf(MSG_DEBUG, "P2P: Received NFC tag payload", data);
7450
7451         pos = wpabuf_head(data);
7452         end = pos + wpabuf_len(data);
7453
7454         if (end - pos < 2) {
7455                 wpa_printf(MSG_DEBUG, "P2P: Not enough data for Length of WSC "
7456                            "attributes");
7457                 return -1;
7458         }
7459         len = WPA_GET_BE16(pos);
7460         pos += 2;
7461         if (pos + len > end) {
7462                 wpa_printf(MSG_DEBUG, "P2P: Not enough data for WSC "
7463                            "attributes");
7464                 return -1;
7465         }
7466         params.wsc_attr = pos;
7467         params.wsc_len = len;
7468         pos += len;
7469
7470         if (end - pos < 2) {
7471                 wpa_printf(MSG_DEBUG, "P2P: Not enough data for Length of P2P "
7472                            "attributes");
7473                 return -1;
7474         }
7475         len = WPA_GET_BE16(pos);
7476         pos += 2;
7477         if (pos + len > end) {
7478                 wpa_printf(MSG_DEBUG, "P2P: Not enough data for P2P "
7479                            "attributes");
7480                 return -1;
7481         }
7482         params.p2p_attr = pos;
7483         params.p2p_len = len;
7484         pos += len;
7485
7486         wpa_hexdump(MSG_DEBUG, "P2P: WSC attributes",
7487                     params.wsc_attr, params.wsc_len);
7488         wpa_hexdump(MSG_DEBUG, "P2P: P2P attributes",
7489                     params.p2p_attr, params.p2p_len);
7490         if (pos < end) {
7491                 wpa_hexdump(MSG_DEBUG,
7492                             "P2P: Ignored extra data after P2P attributes",
7493                             pos, end - pos);
7494         }
7495
7496         res = p2p_process_nfc_connection_handover(wpa_s->global->p2p, &params);
7497         if (res)
7498                 return res;
7499
7500         if (params.next_step == NO_ACTION)
7501                 return 0;
7502
7503         if (params.next_step == BOTH_GO) {
7504                 wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_NFC_BOTH_GO "peer=" MACSTR,
7505                         MAC2STR(params.peer->p2p_device_addr));
7506                 return 0;
7507         }
7508
7509         if (params.next_step == PEER_CLIENT) {
7510                 if (!is_zero_ether_addr(params.go_dev_addr)) {
7511                         wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_NFC_PEER_CLIENT
7512                                 "peer=" MACSTR " freq=%d go_dev_addr=" MACSTR
7513                                 " ssid=\"%s\"",
7514                                 MAC2STR(params.peer->p2p_device_addr),
7515                                 params.go_freq,
7516                                 MAC2STR(params.go_dev_addr),
7517                                 wpa_ssid_txt(params.go_ssid,
7518                                              params.go_ssid_len));
7519                 } else {
7520                         wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_NFC_PEER_CLIENT
7521                                 "peer=" MACSTR " freq=%d",
7522                                 MAC2STR(params.peer->p2p_device_addr),
7523                                 params.go_freq);
7524                 }
7525                 return 0;
7526         }
7527
7528         if (wpas_p2p_cli_freq(wpa_s, NULL, NULL)) {
7529                 wpa_msg(wpa_s, MSG_INFO, P2P_EVENT_NFC_WHILE_CLIENT "peer="
7530                         MACSTR, MAC2STR(params.peer->p2p_device_addr));
7531                 return 0;
7532         }
7533
7534         wpabuf_free(wpa_s->p2p_oob_dev_pw);
7535         wpa_s->p2p_oob_dev_pw = NULL;
7536
7537         if (params.oob_dev_pw_len < WPS_OOB_PUBKEY_HASH_LEN + 2) {
7538                 wpa_printf(MSG_DEBUG, "P2P: No peer OOB Dev Pw "
7539                            "received");
7540                 return -1;
7541         }
7542
7543         id = WPA_GET_BE16(params.oob_dev_pw + WPS_OOB_PUBKEY_HASH_LEN);
7544         wpa_printf(MSG_DEBUG, "P2P: Peer OOB Dev Pw %u", id);
7545         wpa_hexdump(MSG_DEBUG, "P2P: Peer OOB Public Key hash",
7546                     params.oob_dev_pw, WPS_OOB_PUBKEY_HASH_LEN);
7547         os_memcpy(wpa_s->p2p_peer_oob_pubkey_hash,
7548                   params.oob_dev_pw, WPS_OOB_PUBKEY_HASH_LEN);
7549         wpa_s->p2p_peer_oob_pk_hash_known = 1;
7550
7551         if (tag) {
7552                 if (id < 0x10) {
7553                         wpa_printf(MSG_DEBUG, "P2P: Static handover - invalid "
7554                                    "peer OOB Device Password Id %u", id);
7555                         return -1;
7556                 }
7557                 wpa_printf(MSG_DEBUG, "P2P: Static handover - use peer OOB "
7558                            "Device Password Id %u", id);
7559                 wpa_hexdump_key(MSG_DEBUG, "P2P: Peer OOB Device Password",
7560                                 params.oob_dev_pw + WPS_OOB_PUBKEY_HASH_LEN + 2,
7561                                 params.oob_dev_pw_len -
7562                                 WPS_OOB_PUBKEY_HASH_LEN - 2);
7563                 wpa_s->p2p_oob_dev_pw_id = id;
7564                 wpa_s->p2p_oob_dev_pw = wpabuf_alloc_copy(
7565                         params.oob_dev_pw + WPS_OOB_PUBKEY_HASH_LEN + 2,
7566                         params.oob_dev_pw_len -
7567                         WPS_OOB_PUBKEY_HASH_LEN - 2);
7568                 if (wpa_s->p2p_oob_dev_pw == NULL)
7569                         return -1;
7570
7571                 if (wpa_s->conf->wps_nfc_dh_pubkey == NULL &&
7572                     wps_nfc_gen_dh(&wpa_s->conf->wps_nfc_dh_pubkey,
7573                                    &wpa_s->conf->wps_nfc_dh_privkey) < 0)
7574                         return -1;
7575         } else {
7576                 wpa_printf(MSG_DEBUG, "P2P: Using abbreviated WPS handshake "
7577                            "without Device Password");
7578                 wpa_s->p2p_oob_dev_pw_id = DEV_PW_NFC_CONNECTION_HANDOVER;
7579         }
7580
7581         switch (params.next_step) {
7582         case NO_ACTION:
7583         case BOTH_GO:
7584         case PEER_CLIENT:
7585                 /* already covered above */
7586                 return 0;
7587         case JOIN_GROUP:
7588                 return wpas_p2p_nfc_join_group(wpa_s, &params);
7589         case AUTH_JOIN:
7590                 return wpas_p2p_nfc_auth_join(wpa_s, &params, tag);
7591         case INIT_GO_NEG:
7592                 return wpas_p2p_nfc_init_go_neg(wpa_s, &params, forced_freq);
7593         case RESP_GO_NEG:
7594                 /* TODO: use own OOB Dev Pw */
7595                 return wpas_p2p_nfc_resp_go_neg(wpa_s, &params, forced_freq);
7596         }
7597
7598         return -1;
7599 }
7600
7601
7602 int wpas_p2p_nfc_tag_process(struct wpa_supplicant *wpa_s,
7603                              const struct wpabuf *data, int forced_freq)
7604 {
7605         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
7606                 return -1;
7607
7608         return wpas_p2p_nfc_connection_handover(wpa_s, data, 1, 1, forced_freq);
7609 }
7610
7611
7612 int wpas_p2p_nfc_report_handover(struct wpa_supplicant *wpa_s, int init,
7613                                  const struct wpabuf *req,
7614                                  const struct wpabuf *sel, int forced_freq)
7615 {
7616         struct wpabuf *tmp;
7617         int ret;
7618
7619         if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL)
7620                 return -1;
7621
7622         wpa_printf(MSG_DEBUG, "NFC: P2P connection handover reported");
7623
7624         wpa_hexdump_ascii(MSG_DEBUG, "NFC: Req",
7625                           wpabuf_head(req), wpabuf_len(req));
7626         wpa_hexdump_ascii(MSG_DEBUG, "NFC: Sel",
7627                           wpabuf_head(sel), wpabuf_len(sel));
7628         if (forced_freq)
7629                 wpa_printf(MSG_DEBUG, "NFC: Forced freq %d", forced_freq);
7630         tmp = ndef_parse_p2p(init ? sel : req);
7631         if (tmp == NULL) {
7632                 wpa_printf(MSG_DEBUG, "P2P: Could not parse NDEF");
7633                 return -1;
7634         }
7635
7636         ret = wpas_p2p_nfc_connection_handover(wpa_s, tmp, init, 0,
7637                                                forced_freq);
7638         wpabuf_free(tmp);
7639
7640         return ret;
7641 }
7642
7643
7644 int wpas_p2p_nfc_tag_enabled(struct wpa_supplicant *wpa_s, int enabled)
7645 {
7646         const u8 *if_addr;
7647         int go_intent = wpa_s->conf->p2p_go_intent;
7648         struct wpa_supplicant *iface;
7649
7650         if (wpa_s->global->p2p == NULL)
7651                 return -1;
7652
7653         if (!enabled) {
7654                 wpa_printf(MSG_DEBUG, "P2P: Disable use of own NFC Tag");
7655                 for (iface = wpa_s->global->ifaces; iface; iface = iface->next)
7656                 {
7657                         if (!iface->ap_iface)
7658                                 continue;
7659                         hostapd_wps_nfc_token_disable(iface->ap_iface->bss[0]);
7660                 }
7661                 p2p_set_authorized_oob_dev_pw_id(wpa_s->global->p2p, 0,
7662                                                  0, NULL);
7663                 if (wpa_s->p2p_nfc_tag_enabled)
7664                         wpas_p2p_remove_pending_group_interface(wpa_s);
7665                 wpa_s->p2p_nfc_tag_enabled = 0;
7666                 return 0;
7667         }
7668
7669         if (wpa_s->global->p2p_disabled)
7670                 return -1;
7671
7672         if (wpa_s->conf->wps_nfc_dh_pubkey == NULL ||
7673             wpa_s->conf->wps_nfc_dh_privkey == NULL ||
7674             wpa_s->conf->wps_nfc_dev_pw == NULL ||
7675             wpa_s->conf->wps_nfc_dev_pw_id < 0x10) {
7676                 wpa_printf(MSG_DEBUG, "P2P: NFC password token not configured "
7677                            "to allow static handover cases");
7678                 return -1;
7679         }
7680
7681         wpa_printf(MSG_DEBUG, "P2P: Enable use of own NFC Tag");
7682
7683         wpa_s->p2p_oob_dev_pw_id = wpa_s->conf->wps_nfc_dev_pw_id;
7684         wpabuf_free(wpa_s->p2p_oob_dev_pw);
7685         wpa_s->p2p_oob_dev_pw = wpabuf_dup(wpa_s->conf->wps_nfc_dev_pw);
7686         if (wpa_s->p2p_oob_dev_pw == NULL)
7687                 return -1;
7688         wpa_s->p2p_peer_oob_pk_hash_known = 0;
7689
7690         if (wpa_s->p2p_group_interface == P2P_GROUP_INTERFACE_GO ||
7691             wpa_s->p2p_group_interface == P2P_GROUP_INTERFACE_CLIENT) {
7692                 /*
7693                  * P2P Group Interface present and the command came on group
7694                  * interface, so enable the token for the current interface.
7695                  */
7696                 wpa_s->create_p2p_iface = 0;
7697         } else {
7698                 wpa_s->create_p2p_iface = wpas_p2p_create_iface(wpa_s);
7699         }
7700
7701         if (wpa_s->create_p2p_iface) {
7702                 enum wpa_driver_if_type iftype;
7703                 /* Prepare to add a new interface for the group */
7704                 iftype = WPA_IF_P2P_GROUP;
7705                 if (go_intent == 15)
7706                         iftype = WPA_IF_P2P_GO;
7707                 if (wpas_p2p_add_group_interface(wpa_s, iftype) < 0) {
7708                         wpa_printf(MSG_ERROR, "P2P: Failed to allocate a new "
7709                                    "interface for the group");
7710                         return -1;
7711                 }
7712
7713                 if_addr = wpa_s->pending_interface_addr;
7714         } else
7715                 if_addr = wpa_s->own_addr;
7716
7717         wpa_s->p2p_nfc_tag_enabled = enabled;
7718
7719         for (iface = wpa_s->global->ifaces; iface; iface = iface->next) {
7720                 struct hostapd_data *hapd;
7721                 if (iface->ap_iface == NULL)
7722                         continue;
7723                 hapd = iface->ap_iface->bss[0];
7724                 wpabuf_free(hapd->conf->wps_nfc_dh_pubkey);
7725                 hapd->conf->wps_nfc_dh_pubkey =
7726                         wpabuf_dup(wpa_s->conf->wps_nfc_dh_pubkey);
7727                 wpabuf_free(hapd->conf->wps_nfc_dh_privkey);
7728                 hapd->conf->wps_nfc_dh_privkey =
7729                         wpabuf_dup(wpa_s->conf->wps_nfc_dh_privkey);
7730                 wpabuf_free(hapd->conf->wps_nfc_dev_pw);
7731                 hapd->conf->wps_nfc_dev_pw =
7732                         wpabuf_dup(wpa_s->conf->wps_nfc_dev_pw);
7733                 hapd->conf->wps_nfc_dev_pw_id = wpa_s->conf->wps_nfc_dev_pw_id;
7734
7735                 if (hostapd_wps_nfc_token_enable(iface->ap_iface->bss[0]) < 0) {
7736                         wpa_dbg(iface, MSG_DEBUG,
7737                                 "P2P: Failed to enable NFC Tag for GO");
7738                 }
7739         }
7740         p2p_set_authorized_oob_dev_pw_id(
7741                 wpa_s->global->p2p, wpa_s->conf->wps_nfc_dev_pw_id, go_intent,
7742                 if_addr);
7743
7744         return 0;
7745 }
7746
7747 #endif /* CONFIG_WPS_NFC */