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