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