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