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