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