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