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