tests: WPS AP and advertisement OOM
[mech_eap.git] / wpa_supplicant / wpa_supplicant.c
1 /*
2  * WPA Supplicant
3  * Copyright (c) 2003-2015, Jouni Malinen <j@w1.fi>
4  *
5  * This software may be distributed under the terms of the BSD license.
6  * See README for more details.
7  *
8  * This file implements functions for registering and unregistering
9  * %wpa_supplicant interfaces. In addition, this file contains number of
10  * functions for managing network connections.
11  */
12
13 #include "includes.h"
14
15 #include "common.h"
16 #include "crypto/random.h"
17 #include "crypto/sha1.h"
18 #include "eapol_supp/eapol_supp_sm.h"
19 #include "eap_peer/eap.h"
20 #include "eap_peer/eap_proxy.h"
21 #include "eap_server/eap_methods.h"
22 #include "rsn_supp/wpa.h"
23 #include "eloop.h"
24 #include "config.h"
25 #include "utils/ext_password.h"
26 #include "l2_packet/l2_packet.h"
27 #include "wpa_supplicant_i.h"
28 #include "driver_i.h"
29 #include "ctrl_iface.h"
30 #include "pcsc_funcs.h"
31 #include "common/version.h"
32 #include "rsn_supp/preauth.h"
33 #include "rsn_supp/pmksa_cache.h"
34 #include "common/wpa_ctrl.h"
35 #include "common/ieee802_11_defs.h"
36 #include "common/hw_features_common.h"
37 #include "p2p/p2p.h"
38 #include "fst/fst.h"
39 #include "blacklist.h"
40 #include "wpas_glue.h"
41 #include "wps_supplicant.h"
42 #include "ibss_rsn.h"
43 #include "sme.h"
44 #include "gas_query.h"
45 #include "ap.h"
46 #include "p2p_supplicant.h"
47 #include "wifi_display.h"
48 #include "notify.h"
49 #include "bgscan.h"
50 #include "autoscan.h"
51 #include "bss.h"
52 #include "scan.h"
53 #include "offchannel.h"
54 #include "hs20_supplicant.h"
55 #include "wnm_sta.h"
56 #include "wpas_kay.h"
57 #include "mesh.h"
58
59 const char *const wpa_supplicant_version =
60 "wpa_supplicant v" VERSION_STR "\n"
61 "Copyright (c) 2003-2015, Jouni Malinen <j@w1.fi> and contributors";
62
63 const char *const wpa_supplicant_license =
64 "This software may be distributed under the terms of the BSD license.\n"
65 "See README for more details.\n"
66 #ifdef EAP_TLS_OPENSSL
67 "\nThis product includes software developed by the OpenSSL Project\n"
68 "for use in the OpenSSL Toolkit (http://www.openssl.org/)\n"
69 #endif /* EAP_TLS_OPENSSL */
70 ;
71
72 #ifndef CONFIG_NO_STDOUT_DEBUG
73 /* Long text divided into parts in order to fit in C89 strings size limits. */
74 const char *const wpa_supplicant_full_license1 =
75 "";
76 const char *const wpa_supplicant_full_license2 =
77 "This software may be distributed under the terms of the BSD license.\n"
78 "\n"
79 "Redistribution and use in source and binary forms, with or without\n"
80 "modification, are permitted provided that the following conditions are\n"
81 "met:\n"
82 "\n";
83 const char *const wpa_supplicant_full_license3 =
84 "1. Redistributions of source code must retain the above copyright\n"
85 "   notice, this list of conditions and the following disclaimer.\n"
86 "\n"
87 "2. Redistributions in binary form must reproduce the above copyright\n"
88 "   notice, this list of conditions and the following disclaimer in the\n"
89 "   documentation and/or other materials provided with the distribution.\n"
90 "\n";
91 const char *const wpa_supplicant_full_license4 =
92 "3. Neither the name(s) of the above-listed copyright holder(s) nor the\n"
93 "   names of its contributors may be used to endorse or promote products\n"
94 "   derived from this software without specific prior written permission.\n"
95 "\n"
96 "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n"
97 "\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n"
98 "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n"
99 "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n";
100 const char *const wpa_supplicant_full_license5 =
101 "OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n"
102 "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n"
103 "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"
104 "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"
105 "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
106 "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n"
107 "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
108 "\n";
109 #endif /* CONFIG_NO_STDOUT_DEBUG */
110
111 /* Configure default/group WEP keys for static WEP */
112 int wpa_set_wep_keys(struct wpa_supplicant *wpa_s, struct wpa_ssid *ssid)
113 {
114         int i, set = 0;
115
116         for (i = 0; i < NUM_WEP_KEYS; i++) {
117                 if (ssid->wep_key_len[i] == 0)
118                         continue;
119
120                 set = 1;
121                 wpa_drv_set_key(wpa_s, WPA_ALG_WEP, NULL,
122                                 i, i == ssid->wep_tx_keyidx, NULL, 0,
123                                 ssid->wep_key[i], ssid->wep_key_len[i]);
124         }
125
126         return set;
127 }
128
129
130 int wpa_supplicant_set_wpa_none_key(struct wpa_supplicant *wpa_s,
131                                     struct wpa_ssid *ssid)
132 {
133         u8 key[32];
134         size_t keylen;
135         enum wpa_alg alg;
136         u8 seq[6] = { 0 };
137         int ret;
138
139         /* IBSS/WPA-None uses only one key (Group) for both receiving and
140          * sending unicast and multicast packets. */
141
142         if (ssid->mode != WPAS_MODE_IBSS) {
143                 wpa_msg(wpa_s, MSG_INFO, "WPA: Invalid mode %d (not "
144                         "IBSS/ad-hoc) for WPA-None", ssid->mode);
145                 return -1;
146         }
147
148         if (!ssid->psk_set) {
149                 wpa_msg(wpa_s, MSG_INFO, "WPA: No PSK configured for "
150                         "WPA-None");
151                 return -1;
152         }
153
154         switch (wpa_s->group_cipher) {
155         case WPA_CIPHER_CCMP:
156                 os_memcpy(key, ssid->psk, 16);
157                 keylen = 16;
158                 alg = WPA_ALG_CCMP;
159                 break;
160         case WPA_CIPHER_GCMP:
161                 os_memcpy(key, ssid->psk, 16);
162                 keylen = 16;
163                 alg = WPA_ALG_GCMP;
164                 break;
165         case WPA_CIPHER_TKIP:
166                 /* WPA-None uses the same Michael MIC key for both TX and RX */
167                 os_memcpy(key, ssid->psk, 16 + 8);
168                 os_memcpy(key + 16 + 8, ssid->psk + 16, 8);
169                 keylen = 32;
170                 alg = WPA_ALG_TKIP;
171                 break;
172         default:
173                 wpa_msg(wpa_s, MSG_INFO, "WPA: Invalid group cipher %d for "
174                         "WPA-None", wpa_s->group_cipher);
175                 return -1;
176         }
177
178         /* TODO: should actually remember the previously used seq#, both for TX
179          * and RX from each STA.. */
180
181         ret = wpa_drv_set_key(wpa_s, alg, NULL, 0, 1, seq, 6, key, keylen);
182         os_memset(key, 0, sizeof(key));
183         return ret;
184 }
185
186
187 static void wpa_supplicant_timeout(void *eloop_ctx, void *timeout_ctx)
188 {
189         struct wpa_supplicant *wpa_s = eloop_ctx;
190         const u8 *bssid = wpa_s->bssid;
191         if (is_zero_ether_addr(bssid))
192                 bssid = wpa_s->pending_bssid;
193         wpa_msg(wpa_s, MSG_INFO, "Authentication with " MACSTR " timed out.",
194                 MAC2STR(bssid));
195         wpa_blacklist_add(wpa_s, bssid);
196         wpa_sm_notify_disassoc(wpa_s->wpa);
197         wpa_supplicant_deauthenticate(wpa_s, WLAN_REASON_DEAUTH_LEAVING);
198         wpa_s->reassociate = 1;
199
200         /*
201          * If we timed out, the AP or the local radio may be busy.
202          * So, wait a second until scanning again.
203          */
204         wpa_supplicant_req_scan(wpa_s, 1, 0);
205 }
206
207
208 /**
209  * wpa_supplicant_req_auth_timeout - Schedule a timeout for authentication
210  * @wpa_s: Pointer to wpa_supplicant data
211  * @sec: Number of seconds after which to time out authentication
212  * @usec: Number of microseconds after which to time out authentication
213  *
214  * This function is used to schedule a timeout for the current authentication
215  * attempt.
216  */
217 void wpa_supplicant_req_auth_timeout(struct wpa_supplicant *wpa_s,
218                                      int sec, int usec)
219 {
220         if (wpa_s->conf->ap_scan == 0 &&
221             (wpa_s->drv_flags & WPA_DRIVER_FLAGS_WIRED))
222                 return;
223
224         wpa_dbg(wpa_s, MSG_DEBUG, "Setting authentication timeout: %d sec "
225                 "%d usec", sec, usec);
226         eloop_cancel_timeout(wpa_supplicant_timeout, wpa_s, NULL);
227         eloop_register_timeout(sec, usec, wpa_supplicant_timeout, wpa_s, NULL);
228 }
229
230
231 /**
232  * wpa_supplicant_cancel_auth_timeout - Cancel authentication timeout
233  * @wpa_s: Pointer to wpa_supplicant data
234  *
235  * This function is used to cancel authentication timeout scheduled with
236  * wpa_supplicant_req_auth_timeout() and it is called when authentication has
237  * been completed.
238  */
239 void wpa_supplicant_cancel_auth_timeout(struct wpa_supplicant *wpa_s)
240 {
241         wpa_dbg(wpa_s, MSG_DEBUG, "Cancelling authentication timeout");
242         eloop_cancel_timeout(wpa_supplicant_timeout, wpa_s, NULL);
243         wpa_blacklist_del(wpa_s, wpa_s->bssid);
244 }
245
246
247 /**
248  * wpa_supplicant_initiate_eapol - Configure EAPOL state machine
249  * @wpa_s: Pointer to wpa_supplicant data
250  *
251  * This function is used to configure EAPOL state machine based on the selected
252  * authentication mode.
253  */
254 void wpa_supplicant_initiate_eapol(struct wpa_supplicant *wpa_s)
255 {
256 #ifdef IEEE8021X_EAPOL
257         struct eapol_config eapol_conf;
258         struct wpa_ssid *ssid = wpa_s->current_ssid;
259
260 #ifdef CONFIG_IBSS_RSN
261         if (ssid->mode == WPAS_MODE_IBSS &&
262             wpa_s->key_mgmt != WPA_KEY_MGMT_NONE &&
263             wpa_s->key_mgmt != WPA_KEY_MGMT_WPA_NONE) {
264                 /*
265                  * RSN IBSS authentication is per-STA and we can disable the
266                  * per-BSSID EAPOL authentication.
267                  */
268                 eapol_sm_notify_portControl(wpa_s->eapol, ForceAuthorized);
269                 eapol_sm_notify_eap_success(wpa_s->eapol, TRUE);
270                 eapol_sm_notify_eap_fail(wpa_s->eapol, FALSE);
271                 return;
272         }
273 #endif /* CONFIG_IBSS_RSN */
274
275         eapol_sm_notify_eap_success(wpa_s->eapol, FALSE);
276         eapol_sm_notify_eap_fail(wpa_s->eapol, FALSE);
277
278         if (wpa_s->key_mgmt == WPA_KEY_MGMT_NONE ||
279             wpa_s->key_mgmt == WPA_KEY_MGMT_WPA_NONE)
280                 eapol_sm_notify_portControl(wpa_s->eapol, ForceAuthorized);
281         else
282                 eapol_sm_notify_portControl(wpa_s->eapol, Auto);
283
284         os_memset(&eapol_conf, 0, sizeof(eapol_conf));
285         if (wpa_s->key_mgmt == WPA_KEY_MGMT_IEEE8021X_NO_WPA) {
286                 eapol_conf.accept_802_1x_keys = 1;
287                 eapol_conf.required_keys = 0;
288                 if (ssid->eapol_flags & EAPOL_FLAG_REQUIRE_KEY_UNICAST) {
289                         eapol_conf.required_keys |= EAPOL_REQUIRE_KEY_UNICAST;
290                 }
291                 if (ssid->eapol_flags & EAPOL_FLAG_REQUIRE_KEY_BROADCAST) {
292                         eapol_conf.required_keys |=
293                                 EAPOL_REQUIRE_KEY_BROADCAST;
294                 }
295
296                 if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_WIRED)
297                         eapol_conf.required_keys = 0;
298         }
299         eapol_conf.fast_reauth = wpa_s->conf->fast_reauth;
300         eapol_conf.workaround = ssid->eap_workaround;
301         eapol_conf.eap_disabled =
302                 !wpa_key_mgmt_wpa_ieee8021x(wpa_s->key_mgmt) &&
303                 wpa_s->key_mgmt != WPA_KEY_MGMT_IEEE8021X_NO_WPA &&
304                 wpa_s->key_mgmt != WPA_KEY_MGMT_WPS;
305         eapol_conf.external_sim = wpa_s->conf->external_sim;
306
307 #ifdef CONFIG_WPS
308         if (wpa_s->key_mgmt == WPA_KEY_MGMT_WPS) {
309                 eapol_conf.wps |= EAPOL_LOCAL_WPS_IN_USE;
310                 if (wpa_s->current_bss) {
311                         struct wpabuf *ie;
312                         ie = wpa_bss_get_vendor_ie_multi(wpa_s->current_bss,
313                                                          WPS_IE_VENDOR_TYPE);
314                         if (ie) {
315                                 if (wps_is_20(ie))
316                                         eapol_conf.wps |=
317                                                 EAPOL_PEER_IS_WPS20_AP;
318                                 wpabuf_free(ie);
319                         }
320                 }
321         }
322 #endif /* CONFIG_WPS */
323
324         eapol_sm_notify_config(wpa_s->eapol, &ssid->eap, &eapol_conf);
325
326         ieee802_1x_alloc_kay_sm(wpa_s, ssid);
327 #endif /* IEEE8021X_EAPOL */
328 }
329
330
331 /**
332  * wpa_supplicant_set_non_wpa_policy - Set WPA parameters to non-WPA mode
333  * @wpa_s: Pointer to wpa_supplicant data
334  * @ssid: Configuration data for the network
335  *
336  * This function is used to configure WPA state machine and related parameters
337  * to a mode where WPA is not enabled. This is called as part of the
338  * authentication configuration when the selected network does not use WPA.
339  */
340 void wpa_supplicant_set_non_wpa_policy(struct wpa_supplicant *wpa_s,
341                                        struct wpa_ssid *ssid)
342 {
343         int i;
344
345         if (ssid->key_mgmt & WPA_KEY_MGMT_WPS)
346                 wpa_s->key_mgmt = WPA_KEY_MGMT_WPS;
347         else if (ssid->key_mgmt & WPA_KEY_MGMT_IEEE8021X_NO_WPA)
348                 wpa_s->key_mgmt = WPA_KEY_MGMT_IEEE8021X_NO_WPA;
349         else
350                 wpa_s->key_mgmt = WPA_KEY_MGMT_NONE;
351         wpa_sm_set_ap_wpa_ie(wpa_s->wpa, NULL, 0);
352         wpa_sm_set_ap_rsn_ie(wpa_s->wpa, NULL, 0);
353         wpa_sm_set_assoc_wpa_ie(wpa_s->wpa, NULL, 0);
354         wpa_s->pairwise_cipher = WPA_CIPHER_NONE;
355         wpa_s->group_cipher = WPA_CIPHER_NONE;
356         wpa_s->mgmt_group_cipher = 0;
357
358         for (i = 0; i < NUM_WEP_KEYS; i++) {
359                 if (ssid->wep_key_len[i] > 5) {
360                         wpa_s->pairwise_cipher = WPA_CIPHER_WEP104;
361                         wpa_s->group_cipher = WPA_CIPHER_WEP104;
362                         break;
363                 } else if (ssid->wep_key_len[i] > 0) {
364                         wpa_s->pairwise_cipher = WPA_CIPHER_WEP40;
365                         wpa_s->group_cipher = WPA_CIPHER_WEP40;
366                         break;
367                 }
368         }
369
370         wpa_sm_set_param(wpa_s->wpa, WPA_PARAM_RSN_ENABLED, 0);
371         wpa_sm_set_param(wpa_s->wpa, WPA_PARAM_KEY_MGMT, wpa_s->key_mgmt);
372         wpa_sm_set_param(wpa_s->wpa, WPA_PARAM_PAIRWISE,
373                          wpa_s->pairwise_cipher);
374         wpa_sm_set_param(wpa_s->wpa, WPA_PARAM_GROUP, wpa_s->group_cipher);
375 #ifdef CONFIG_IEEE80211W
376         wpa_sm_set_param(wpa_s->wpa, WPA_PARAM_MGMT_GROUP,
377                          wpa_s->mgmt_group_cipher);
378 #endif /* CONFIG_IEEE80211W */
379
380         pmksa_cache_clear_current(wpa_s->wpa);
381 }
382
383
384 void free_hw_features(struct wpa_supplicant *wpa_s)
385 {
386         int i;
387         if (wpa_s->hw.modes == NULL)
388                 return;
389
390         for (i = 0; i < wpa_s->hw.num_modes; i++) {
391                 os_free(wpa_s->hw.modes[i].channels);
392                 os_free(wpa_s->hw.modes[i].rates);
393         }
394
395         os_free(wpa_s->hw.modes);
396         wpa_s->hw.modes = NULL;
397 }
398
399
400 static void wpa_supplicant_cleanup(struct wpa_supplicant *wpa_s)
401 {
402         int i;
403
404         bgscan_deinit(wpa_s);
405         autoscan_deinit(wpa_s);
406         scard_deinit(wpa_s->scard);
407         wpa_s->scard = NULL;
408         wpa_sm_set_scard_ctx(wpa_s->wpa, NULL);
409         eapol_sm_register_scard_ctx(wpa_s->eapol, NULL);
410         l2_packet_deinit(wpa_s->l2);
411         wpa_s->l2 = NULL;
412         if (wpa_s->l2_br) {
413                 l2_packet_deinit(wpa_s->l2_br);
414                 wpa_s->l2_br = NULL;
415         }
416 #ifdef CONFIG_TESTING_OPTIONS
417         l2_packet_deinit(wpa_s->l2_test);
418         wpa_s->l2_test = NULL;
419 #endif /* CONFIG_TESTING_OPTIONS */
420
421         if (wpa_s->conf != NULL) {
422                 struct wpa_ssid *ssid;
423                 for (ssid = wpa_s->conf->ssid; ssid; ssid = ssid->next)
424                         wpas_notify_network_removed(wpa_s, ssid);
425         }
426
427         os_free(wpa_s->confname);
428         wpa_s->confname = NULL;
429
430         os_free(wpa_s->confanother);
431         wpa_s->confanother = NULL;
432
433         wpa_sm_set_eapol(wpa_s->wpa, NULL);
434         eapol_sm_deinit(wpa_s->eapol);
435         wpa_s->eapol = NULL;
436
437         rsn_preauth_deinit(wpa_s->wpa);
438
439 #ifdef CONFIG_TDLS
440         wpa_tdls_deinit(wpa_s->wpa);
441 #endif /* CONFIG_TDLS */
442
443         wmm_ac_clear_saved_tspecs(wpa_s);
444         pmksa_candidate_free(wpa_s->wpa);
445         wpa_sm_deinit(wpa_s->wpa);
446         wpa_s->wpa = NULL;
447         wpa_blacklist_clear(wpa_s);
448
449         wpa_bss_deinit(wpa_s);
450
451         wpa_supplicant_cancel_delayed_sched_scan(wpa_s);
452         wpa_supplicant_cancel_scan(wpa_s);
453         wpa_supplicant_cancel_auth_timeout(wpa_s);
454         eloop_cancel_timeout(wpa_supplicant_stop_countermeasures, wpa_s, NULL);
455 #ifdef CONFIG_DELAYED_MIC_ERROR_REPORT
456         eloop_cancel_timeout(wpa_supplicant_delayed_mic_error_report,
457                              wpa_s, NULL);
458 #endif /* CONFIG_DELAYED_MIC_ERROR_REPORT */
459
460         eloop_cancel_timeout(wpas_network_reenabled, wpa_s, NULL);
461
462         wpas_wps_deinit(wpa_s);
463
464         wpabuf_free(wpa_s->pending_eapol_rx);
465         wpa_s->pending_eapol_rx = NULL;
466
467 #ifdef CONFIG_IBSS_RSN
468         ibss_rsn_deinit(wpa_s->ibss_rsn);
469         wpa_s->ibss_rsn = NULL;
470 #endif /* CONFIG_IBSS_RSN */
471
472         sme_deinit(wpa_s);
473
474 #ifdef CONFIG_AP
475         wpa_supplicant_ap_deinit(wpa_s);
476 #endif /* CONFIG_AP */
477
478         wpas_p2p_deinit(wpa_s);
479
480 #ifdef CONFIG_OFFCHANNEL
481         offchannel_deinit(wpa_s);
482 #endif /* CONFIG_OFFCHANNEL */
483
484         wpa_supplicant_cancel_sched_scan(wpa_s);
485
486         os_free(wpa_s->next_scan_freqs);
487         wpa_s->next_scan_freqs = NULL;
488
489         os_free(wpa_s->manual_scan_freqs);
490         wpa_s->manual_scan_freqs = NULL;
491
492         os_free(wpa_s->manual_sched_scan_freqs);
493         wpa_s->manual_sched_scan_freqs = NULL;
494
495         wpas_mac_addr_rand_scan_clear(wpa_s, MAC_ADDR_RAND_ALL);
496
497         /*
498          * Need to remove any pending gas-query radio work before the
499          * gas_query_deinit() call because gas_query::work has not yet been set
500          * for works that have not been started. gas_query_free() will be unable
501          * to cancel such pending radio works and once the pending gas-query
502          * radio work eventually gets removed, the deinit notification call to
503          * gas_query_start_cb() would result in dereferencing freed memory.
504          */
505         if (wpa_s->radio)
506                 radio_remove_works(wpa_s, "gas-query", 0);
507         gas_query_deinit(wpa_s->gas);
508         wpa_s->gas = NULL;
509
510         free_hw_features(wpa_s);
511
512         ieee802_1x_dealloc_kay_sm(wpa_s);
513
514         os_free(wpa_s->bssid_filter);
515         wpa_s->bssid_filter = NULL;
516
517         os_free(wpa_s->disallow_aps_bssid);
518         wpa_s->disallow_aps_bssid = NULL;
519         os_free(wpa_s->disallow_aps_ssid);
520         wpa_s->disallow_aps_ssid = NULL;
521
522         wnm_bss_keep_alive_deinit(wpa_s);
523 #ifdef CONFIG_WNM
524         wnm_deallocate_memory(wpa_s);
525 #endif /* CONFIG_WNM */
526
527         ext_password_deinit(wpa_s->ext_pw);
528         wpa_s->ext_pw = NULL;
529
530         wpabuf_free(wpa_s->last_gas_resp);
531         wpa_s->last_gas_resp = NULL;
532         wpabuf_free(wpa_s->prev_gas_resp);
533         wpa_s->prev_gas_resp = NULL;
534
535         os_free(wpa_s->last_scan_res);
536         wpa_s->last_scan_res = NULL;
537
538 #ifdef CONFIG_HS20
539         hs20_deinit(wpa_s);
540 #endif /* CONFIG_HS20 */
541
542         for (i = 0; i < NUM_VENDOR_ELEM_FRAMES; i++) {
543                 wpabuf_free(wpa_s->vendor_elem[i]);
544                 wpa_s->vendor_elem[i] = NULL;
545         }
546
547         wmm_ac_notify_disassoc(wpa_s);
548 }
549
550
551 /**
552  * wpa_clear_keys - Clear keys configured for the driver
553  * @wpa_s: Pointer to wpa_supplicant data
554  * @addr: Previously used BSSID or %NULL if not available
555  *
556  * This function clears the encryption keys that has been previously configured
557  * for the driver.
558  */
559 void wpa_clear_keys(struct wpa_supplicant *wpa_s, const u8 *addr)
560 {
561         int i, max;
562
563 #ifdef CONFIG_IEEE80211W
564         max = 6;
565 #else /* CONFIG_IEEE80211W */
566         max = 4;
567 #endif /* CONFIG_IEEE80211W */
568
569         /* MLME-DELETEKEYS.request */
570         for (i = 0; i < max; i++) {
571                 if (wpa_s->keys_cleared & BIT(i))
572                         continue;
573                 wpa_drv_set_key(wpa_s, WPA_ALG_NONE, NULL, i, 0, NULL, 0,
574                                 NULL, 0);
575         }
576         if (!(wpa_s->keys_cleared & BIT(0)) && addr &&
577             !is_zero_ether_addr(addr)) {
578                 wpa_drv_set_key(wpa_s, WPA_ALG_NONE, addr, 0, 0, NULL, 0, NULL,
579                                 0);
580                 /* MLME-SETPROTECTION.request(None) */
581                 wpa_drv_mlme_setprotection(
582                         wpa_s, addr,
583                         MLME_SETPROTECTION_PROTECT_TYPE_NONE,
584                         MLME_SETPROTECTION_KEY_TYPE_PAIRWISE);
585         }
586         wpa_s->keys_cleared = (u32) -1;
587 }
588
589
590 /**
591  * wpa_supplicant_state_txt - Get the connection state name as a text string
592  * @state: State (wpa_state; WPA_*)
593  * Returns: The state name as a printable text string
594  */
595 const char * wpa_supplicant_state_txt(enum wpa_states state)
596 {
597         switch (state) {
598         case WPA_DISCONNECTED:
599                 return "DISCONNECTED";
600         case WPA_INACTIVE:
601                 return "INACTIVE";
602         case WPA_INTERFACE_DISABLED:
603                 return "INTERFACE_DISABLED";
604         case WPA_SCANNING:
605                 return "SCANNING";
606         case WPA_AUTHENTICATING:
607                 return "AUTHENTICATING";
608         case WPA_ASSOCIATING:
609                 return "ASSOCIATING";
610         case WPA_ASSOCIATED:
611                 return "ASSOCIATED";
612         case WPA_4WAY_HANDSHAKE:
613                 return "4WAY_HANDSHAKE";
614         case WPA_GROUP_HANDSHAKE:
615                 return "GROUP_HANDSHAKE";
616         case WPA_COMPLETED:
617                 return "COMPLETED";
618         default:
619                 return "UNKNOWN";
620         }
621 }
622
623
624 #ifdef CONFIG_BGSCAN
625
626 static void wpa_supplicant_start_bgscan(struct wpa_supplicant *wpa_s)
627 {
628         const char *name;
629
630         if (wpa_s->current_ssid && wpa_s->current_ssid->bgscan)
631                 name = wpa_s->current_ssid->bgscan;
632         else
633                 name = wpa_s->conf->bgscan;
634         if (name == NULL || name[0] == '\0')
635                 return;
636         if (wpas_driver_bss_selection(wpa_s))
637                 return;
638         if (wpa_s->current_ssid == wpa_s->bgscan_ssid)
639                 return;
640 #ifdef CONFIG_P2P
641         if (wpa_s->p2p_group_interface != NOT_P2P_GROUP_INTERFACE)
642                 return;
643 #endif /* CONFIG_P2P */
644
645         bgscan_deinit(wpa_s);
646         if (wpa_s->current_ssid) {
647                 if (bgscan_init(wpa_s, wpa_s->current_ssid, name)) {
648                         wpa_dbg(wpa_s, MSG_DEBUG, "Failed to initialize "
649                                 "bgscan");
650                         /*
651                          * Live without bgscan; it is only used as a roaming
652                          * optimization, so the initial connection is not
653                          * affected.
654                          */
655                 } else {
656                         struct wpa_scan_results *scan_res;
657                         wpa_s->bgscan_ssid = wpa_s->current_ssid;
658                         scan_res = wpa_supplicant_get_scan_results(wpa_s, NULL,
659                                                                    0);
660                         if (scan_res) {
661                                 bgscan_notify_scan(wpa_s, scan_res);
662                                 wpa_scan_results_free(scan_res);
663                         }
664                 }
665         } else
666                 wpa_s->bgscan_ssid = NULL;
667 }
668
669
670 static void wpa_supplicant_stop_bgscan(struct wpa_supplicant *wpa_s)
671 {
672         if (wpa_s->bgscan_ssid != NULL) {
673                 bgscan_deinit(wpa_s);
674                 wpa_s->bgscan_ssid = NULL;
675         }
676 }
677
678 #endif /* CONFIG_BGSCAN */
679
680
681 static void wpa_supplicant_start_autoscan(struct wpa_supplicant *wpa_s)
682 {
683         if (autoscan_init(wpa_s, 0))
684                 wpa_dbg(wpa_s, MSG_DEBUG, "Failed to initialize autoscan");
685 }
686
687
688 static void wpa_supplicant_stop_autoscan(struct wpa_supplicant *wpa_s)
689 {
690         autoscan_deinit(wpa_s);
691 }
692
693
694 void wpa_supplicant_reinit_autoscan(struct wpa_supplicant *wpa_s)
695 {
696         if (wpa_s->wpa_state == WPA_DISCONNECTED ||
697             wpa_s->wpa_state == WPA_SCANNING) {
698                 autoscan_deinit(wpa_s);
699                 wpa_supplicant_start_autoscan(wpa_s);
700         }
701 }
702
703
704 /**
705  * wpa_supplicant_set_state - Set current connection state
706  * @wpa_s: Pointer to wpa_supplicant data
707  * @state: The new connection state
708  *
709  * This function is called whenever the connection state changes, e.g.,
710  * association is completed for WPA/WPA2 4-Way Handshake is started.
711  */
712 void wpa_supplicant_set_state(struct wpa_supplicant *wpa_s,
713                               enum wpa_states state)
714 {
715         enum wpa_states old_state = wpa_s->wpa_state;
716
717         wpa_dbg(wpa_s, MSG_DEBUG, "State: %s -> %s",
718                 wpa_supplicant_state_txt(wpa_s->wpa_state),
719                 wpa_supplicant_state_txt(state));
720
721         if (state == WPA_INTERFACE_DISABLED) {
722                 /* Assure normal scan when interface is restored */
723                 wpa_s->normal_scans = 0;
724         }
725
726         if (state == WPA_COMPLETED) {
727                 wpas_connect_work_done(wpa_s);
728                 /* Reinitialize normal_scan counter */
729                 wpa_s->normal_scans = 0;
730         }
731
732 #ifdef CONFIG_P2P
733         /*
734          * P2PS client has to reply to Probe Request frames received on the
735          * group operating channel. Enable Probe Request frame reporting for
736          * P2P connected client in case p2p_cli_probe configuration property is
737          * set to 1.
738          */
739         if (wpa_s->conf->p2p_cli_probe && wpa_s->current_ssid &&
740             wpa_s->current_ssid->mode == WPAS_MODE_INFRA &&
741             wpa_s->current_ssid->p2p_group) {
742                 if (state == WPA_COMPLETED && !wpa_s->p2p_cli_probe) {
743                         wpa_dbg(wpa_s, MSG_DEBUG,
744                                 "P2P: Enable CLI Probe Request RX reporting");
745                         wpa_s->p2p_cli_probe =
746                                 wpa_drv_probe_req_report(wpa_s, 1) >= 0;
747                 } else if (state != WPA_COMPLETED && wpa_s->p2p_cli_probe) {
748                         wpa_dbg(wpa_s, MSG_DEBUG,
749                                 "P2P: Disable CLI Probe Request RX reporting");
750                         wpa_s->p2p_cli_probe = 0;
751                         wpa_drv_probe_req_report(wpa_s, 0);
752                 }
753         }
754 #endif /* CONFIG_P2P */
755
756         if (state != WPA_SCANNING)
757                 wpa_supplicant_notify_scanning(wpa_s, 0);
758
759         if (state == WPA_COMPLETED && wpa_s->new_connection) {
760                 struct wpa_ssid *ssid = wpa_s->current_ssid;
761 #if defined(CONFIG_CTRL_IFACE) || !defined(CONFIG_NO_STDOUT_DEBUG)
762                 wpa_msg(wpa_s, MSG_INFO, WPA_EVENT_CONNECTED "- Connection to "
763                         MACSTR " completed [id=%d id_str=%s]",
764                         MAC2STR(wpa_s->bssid),
765                         ssid ? ssid->id : -1,
766                         ssid && ssid->id_str ? ssid->id_str : "");
767 #endif /* CONFIG_CTRL_IFACE || !CONFIG_NO_STDOUT_DEBUG */
768                 wpas_clear_temp_disabled(wpa_s, ssid, 1);
769                 wpa_blacklist_clear(wpa_s);
770                 wpa_s->extra_blacklist_count = 0;
771                 wpa_s->new_connection = 0;
772                 wpa_drv_set_operstate(wpa_s, 1);
773 #ifndef IEEE8021X_EAPOL
774                 wpa_drv_set_supp_port(wpa_s, 1);
775 #endif /* IEEE8021X_EAPOL */
776                 wpa_s->after_wps = 0;
777                 wpa_s->known_wps_freq = 0;
778                 wpas_p2p_completed(wpa_s);
779
780                 sme_sched_obss_scan(wpa_s, 1);
781         } else if (state == WPA_DISCONNECTED || state == WPA_ASSOCIATING ||
782                    state == WPA_ASSOCIATED) {
783                 wpa_s->new_connection = 1;
784                 wpa_drv_set_operstate(wpa_s, 0);
785 #ifndef IEEE8021X_EAPOL
786                 wpa_drv_set_supp_port(wpa_s, 0);
787 #endif /* IEEE8021X_EAPOL */
788                 sme_sched_obss_scan(wpa_s, 0);
789         }
790         wpa_s->wpa_state = state;
791
792 #ifdef CONFIG_BGSCAN
793         if (state == WPA_COMPLETED)
794                 wpa_supplicant_start_bgscan(wpa_s);
795         else if (state < WPA_ASSOCIATED)
796                 wpa_supplicant_stop_bgscan(wpa_s);
797 #endif /* CONFIG_BGSCAN */
798
799         if (state == WPA_AUTHENTICATING)
800                 wpa_supplicant_stop_autoscan(wpa_s);
801
802         if (state == WPA_DISCONNECTED || state == WPA_INACTIVE)
803                 wpa_supplicant_start_autoscan(wpa_s);
804
805         if (old_state >= WPA_ASSOCIATED && wpa_s->wpa_state < WPA_ASSOCIATED)
806                 wmm_ac_notify_disassoc(wpa_s);
807
808         if (wpa_s->wpa_state != old_state) {
809                 wpas_notify_state_changed(wpa_s, wpa_s->wpa_state, old_state);
810
811                 /*
812                  * Notify the P2P Device interface about a state change in one
813                  * of the interfaces.
814                  */
815                 wpas_p2p_indicate_state_change(wpa_s);
816
817                 if (wpa_s->wpa_state == WPA_COMPLETED ||
818                     old_state == WPA_COMPLETED)
819                         wpas_notify_auth_changed(wpa_s);
820         }
821 }
822
823
824 void wpa_supplicant_terminate_proc(struct wpa_global *global)
825 {
826         int pending = 0;
827 #ifdef CONFIG_WPS
828         struct wpa_supplicant *wpa_s = global->ifaces;
829         while (wpa_s) {
830                 struct wpa_supplicant *next = wpa_s->next;
831                 if (wpas_wps_terminate_pending(wpa_s) == 1)
832                         pending = 1;
833 #ifdef CONFIG_P2P
834                 if (wpa_s->p2p_group_interface != NOT_P2P_GROUP_INTERFACE ||
835                     (wpa_s->current_ssid && wpa_s->current_ssid->p2p_group))
836                         wpas_p2p_disconnect(wpa_s);
837 #endif /* CONFIG_P2P */
838                 wpa_s = next;
839         }
840 #endif /* CONFIG_WPS */
841         if (pending)
842                 return;
843         eloop_terminate();
844 }
845
846
847 static void wpa_supplicant_terminate(int sig, void *signal_ctx)
848 {
849         struct wpa_global *global = signal_ctx;
850         wpa_supplicant_terminate_proc(global);
851 }
852
853
854 void wpa_supplicant_clear_status(struct wpa_supplicant *wpa_s)
855 {
856         enum wpa_states old_state = wpa_s->wpa_state;
857
858         wpa_s->pairwise_cipher = 0;
859         wpa_s->group_cipher = 0;
860         wpa_s->mgmt_group_cipher = 0;
861         wpa_s->key_mgmt = 0;
862         if (wpa_s->wpa_state != WPA_INTERFACE_DISABLED)
863                 wpa_supplicant_set_state(wpa_s, WPA_DISCONNECTED);
864
865         if (wpa_s->wpa_state != old_state)
866                 wpas_notify_state_changed(wpa_s, wpa_s->wpa_state, old_state);
867 }
868
869
870 /**
871  * wpa_supplicant_reload_configuration - Reload configuration data
872  * @wpa_s: Pointer to wpa_supplicant data
873  * Returns: 0 on success or -1 if configuration parsing failed
874  *
875  * This function can be used to request that the configuration data is reloaded
876  * (e.g., after configuration file change). This function is reloading
877  * configuration only for one interface, so this may need to be called multiple
878  * times if %wpa_supplicant is controlling multiple interfaces and all
879  * interfaces need reconfiguration.
880  */
881 int wpa_supplicant_reload_configuration(struct wpa_supplicant *wpa_s)
882 {
883         struct wpa_config *conf;
884         int reconf_ctrl;
885         int old_ap_scan;
886
887         if (wpa_s->confname == NULL)
888                 return -1;
889         conf = wpa_config_read(wpa_s->confname, NULL);
890         if (conf == NULL) {
891                 wpa_msg(wpa_s, MSG_ERROR, "Failed to parse the configuration "
892                         "file '%s' - exiting", wpa_s->confname);
893                 return -1;
894         }
895         wpa_config_read(wpa_s->confanother, conf);
896
897         conf->changed_parameters = (unsigned int) -1;
898
899         reconf_ctrl = !!conf->ctrl_interface != !!wpa_s->conf->ctrl_interface
900                 || (conf->ctrl_interface && wpa_s->conf->ctrl_interface &&
901                     os_strcmp(conf->ctrl_interface,
902                               wpa_s->conf->ctrl_interface) != 0);
903
904         if (reconf_ctrl && wpa_s->ctrl_iface) {
905                 wpa_supplicant_ctrl_iface_deinit(wpa_s->ctrl_iface);
906                 wpa_s->ctrl_iface = NULL;
907         }
908
909         eapol_sm_invalidate_cached_session(wpa_s->eapol);
910         if (wpa_s->current_ssid) {
911                 if (wpa_s->wpa_state >= WPA_AUTHENTICATING)
912                         wpa_s->own_disconnect_req = 1;
913                 wpa_supplicant_deauthenticate(wpa_s,
914                                               WLAN_REASON_DEAUTH_LEAVING);
915         }
916
917         /*
918          * TODO: should notify EAPOL SM about changes in opensc_engine_path,
919          * pkcs11_engine_path, pkcs11_module_path, openssl_ciphers.
920          */
921         if (wpa_key_mgmt_wpa_psk(wpa_s->key_mgmt)) {
922                 /*
923                  * Clear forced success to clear EAP state for next
924                  * authentication.
925                  */
926                 eapol_sm_notify_eap_success(wpa_s->eapol, FALSE);
927         }
928         eapol_sm_notify_config(wpa_s->eapol, NULL, NULL);
929         wpa_sm_set_config(wpa_s->wpa, NULL);
930         wpa_sm_pmksa_cache_flush(wpa_s->wpa, NULL);
931         wpa_sm_set_fast_reauth(wpa_s->wpa, wpa_s->conf->fast_reauth);
932         rsn_preauth_deinit(wpa_s->wpa);
933
934         old_ap_scan = wpa_s->conf->ap_scan;
935         wpa_config_free(wpa_s->conf);
936         wpa_s->conf = conf;
937         if (old_ap_scan != wpa_s->conf->ap_scan)
938                 wpas_notify_ap_scan_changed(wpa_s);
939
940         if (reconf_ctrl)
941                 wpa_s->ctrl_iface = wpa_supplicant_ctrl_iface_init(wpa_s);
942
943         wpa_supplicant_update_config(wpa_s);
944
945         wpa_supplicant_clear_status(wpa_s);
946         if (wpa_supplicant_enabled_networks(wpa_s)) {
947                 wpa_s->reassociate = 1;
948                 wpa_supplicant_req_scan(wpa_s, 0, 0);
949         }
950         wpa_dbg(wpa_s, MSG_DEBUG, "Reconfiguration completed");
951         return 0;
952 }
953
954
955 static void wpa_supplicant_reconfig(int sig, void *signal_ctx)
956 {
957         struct wpa_global *global = signal_ctx;
958         struct wpa_supplicant *wpa_s;
959         for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) {
960                 wpa_dbg(wpa_s, MSG_DEBUG, "Signal %d received - reconfiguring",
961                         sig);
962                 if (wpa_supplicant_reload_configuration(wpa_s) < 0) {
963                         wpa_supplicant_terminate_proc(global);
964                 }
965         }
966 }
967
968
969 static int wpa_supplicant_suites_from_ai(struct wpa_supplicant *wpa_s,
970                                          struct wpa_ssid *ssid,
971                                          struct wpa_ie_data *ie)
972 {
973         int ret = wpa_sm_parse_own_wpa_ie(wpa_s->wpa, ie);
974         if (ret) {
975                 if (ret == -2) {
976                         wpa_msg(wpa_s, MSG_INFO, "WPA: Failed to parse WPA IE "
977                                 "from association info");
978                 }
979                 return -1;
980         }
981
982         wpa_dbg(wpa_s, MSG_DEBUG, "WPA: Using WPA IE from AssocReq to set "
983                 "cipher suites");
984         if (!(ie->group_cipher & ssid->group_cipher)) {
985                 wpa_msg(wpa_s, MSG_INFO, "WPA: Driver used disabled group "
986                         "cipher 0x%x (mask 0x%x) - reject",
987                         ie->group_cipher, ssid->group_cipher);
988                 return -1;
989         }
990         if (!(ie->pairwise_cipher & ssid->pairwise_cipher)) {
991                 wpa_msg(wpa_s, MSG_INFO, "WPA: Driver used disabled pairwise "
992                         "cipher 0x%x (mask 0x%x) - reject",
993                         ie->pairwise_cipher, ssid->pairwise_cipher);
994                 return -1;
995         }
996         if (!(ie->key_mgmt & ssid->key_mgmt)) {
997                 wpa_msg(wpa_s, MSG_INFO, "WPA: Driver used disabled key "
998                         "management 0x%x (mask 0x%x) - reject",
999                         ie->key_mgmt, ssid->key_mgmt);
1000                 return -1;
1001         }
1002
1003 #ifdef CONFIG_IEEE80211W
1004         if (!(ie->capabilities & WPA_CAPABILITY_MFPC) &&
1005             wpas_get_ssid_pmf(wpa_s, ssid) == MGMT_FRAME_PROTECTION_REQUIRED) {
1006                 wpa_msg(wpa_s, MSG_INFO, "WPA: Driver associated with an AP "
1007                         "that does not support management frame protection - "
1008                         "reject");
1009                 return -1;
1010         }
1011 #endif /* CONFIG_IEEE80211W */
1012
1013         return 0;
1014 }
1015
1016
1017 /**
1018  * wpa_supplicant_set_suites - Set authentication and encryption parameters
1019  * @wpa_s: Pointer to wpa_supplicant data
1020  * @bss: Scan results for the selected BSS, or %NULL if not available
1021  * @ssid: Configuration data for the selected network
1022  * @wpa_ie: Buffer for the WPA/RSN IE
1023  * @wpa_ie_len: Maximum wpa_ie buffer size on input. This is changed to be the
1024  * used buffer length in case the functions returns success.
1025  * Returns: 0 on success or -1 on failure
1026  *
1027  * This function is used to configure authentication and encryption parameters
1028  * based on the network configuration and scan result for the selected BSS (if
1029  * available).
1030  */
1031 int wpa_supplicant_set_suites(struct wpa_supplicant *wpa_s,
1032                               struct wpa_bss *bss, struct wpa_ssid *ssid,
1033                               u8 *wpa_ie, size_t *wpa_ie_len)
1034 {
1035         struct wpa_ie_data ie;
1036         int sel, proto;
1037         const u8 *bss_wpa, *bss_rsn, *bss_osen;
1038
1039         if (bss) {
1040                 bss_wpa = wpa_bss_get_vendor_ie(bss, WPA_IE_VENDOR_TYPE);
1041                 bss_rsn = wpa_bss_get_ie(bss, WLAN_EID_RSN);
1042                 bss_osen = wpa_bss_get_vendor_ie(bss, OSEN_IE_VENDOR_TYPE);
1043         } else
1044                 bss_wpa = bss_rsn = bss_osen = NULL;
1045
1046         if (bss_rsn && (ssid->proto & WPA_PROTO_RSN) &&
1047             wpa_parse_wpa_ie(bss_rsn, 2 + bss_rsn[1], &ie) == 0 &&
1048             (ie.group_cipher & ssid->group_cipher) &&
1049             (ie.pairwise_cipher & ssid->pairwise_cipher) &&
1050             (ie.key_mgmt & ssid->key_mgmt)) {
1051                 wpa_dbg(wpa_s, MSG_DEBUG, "RSN: using IEEE 802.11i/D9.0");
1052                 proto = WPA_PROTO_RSN;
1053         } else if (bss_wpa && (ssid->proto & WPA_PROTO_WPA) &&
1054                    wpa_parse_wpa_ie(bss_wpa, 2 + bss_wpa[1], &ie) == 0 &&
1055                    (ie.group_cipher & ssid->group_cipher) &&
1056                    (ie.pairwise_cipher & ssid->pairwise_cipher) &&
1057                    (ie.key_mgmt & ssid->key_mgmt)) {
1058                 wpa_dbg(wpa_s, MSG_DEBUG, "WPA: using IEEE 802.11i/D3.0");
1059                 proto = WPA_PROTO_WPA;
1060 #ifdef CONFIG_HS20
1061         } else if (bss_osen && (ssid->proto & WPA_PROTO_OSEN)) {
1062                 wpa_dbg(wpa_s, MSG_DEBUG, "HS 2.0: using OSEN");
1063                 /* TODO: parse OSEN element */
1064                 os_memset(&ie, 0, sizeof(ie));
1065                 ie.group_cipher = WPA_CIPHER_CCMP;
1066                 ie.pairwise_cipher = WPA_CIPHER_CCMP;
1067                 ie.key_mgmt = WPA_KEY_MGMT_OSEN;
1068                 proto = WPA_PROTO_OSEN;
1069 #endif /* CONFIG_HS20 */
1070         } else if (bss) {
1071                 wpa_msg(wpa_s, MSG_WARNING, "WPA: Failed to select WPA/RSN");
1072                 wpa_dbg(wpa_s, MSG_DEBUG,
1073                         "WPA: ssid proto=0x%x pairwise_cipher=0x%x group_cipher=0x%x key_mgmt=0x%x",
1074                         ssid->proto, ssid->pairwise_cipher, ssid->group_cipher,
1075                         ssid->key_mgmt);
1076                 wpa_dbg(wpa_s, MSG_DEBUG, "WPA: BSS " MACSTR " ssid='%s'%s%s%s",
1077                         MAC2STR(bss->bssid),
1078                         wpa_ssid_txt(bss->ssid, bss->ssid_len),
1079                         bss_wpa ? " WPA" : "",
1080                         bss_rsn ? " RSN" : "",
1081                         bss_osen ? " OSEN" : "");
1082                 if (bss_rsn) {
1083                         wpa_hexdump(MSG_DEBUG, "RSN", bss_rsn, 2 + bss_rsn[1]);
1084                         if (wpa_parse_wpa_ie(bss_rsn, 2 + bss_rsn[1], &ie)) {
1085                                 wpa_dbg(wpa_s, MSG_DEBUG,
1086                                         "Could not parse RSN element");
1087                         } else {
1088                                 wpa_dbg(wpa_s, MSG_DEBUG,
1089                                         "RSN: pairwise_cipher=0x%x group_cipher=0x%x key_mgmt=0x%x",
1090                                         ie.pairwise_cipher, ie.group_cipher,
1091                                         ie.key_mgmt);
1092                         }
1093                 }
1094                 if (bss_wpa) {
1095                         wpa_hexdump(MSG_DEBUG, "WPA", bss_wpa, 2 + bss_wpa[1]);
1096                         if (wpa_parse_wpa_ie(bss_wpa, 2 + bss_wpa[1], &ie)) {
1097                                 wpa_dbg(wpa_s, MSG_DEBUG,
1098                                         "Could not parse WPA element");
1099                         } else {
1100                                 wpa_dbg(wpa_s, MSG_DEBUG,
1101                                         "WPA: pairwise_cipher=0x%x group_cipher=0x%x key_mgmt=0x%x",
1102                                         ie.pairwise_cipher, ie.group_cipher,
1103                                         ie.key_mgmt);
1104                         }
1105                 }
1106                 return -1;
1107         } else {
1108                 if (ssid->proto & WPA_PROTO_OSEN)
1109                         proto = WPA_PROTO_OSEN;
1110                 else if (ssid->proto & WPA_PROTO_RSN)
1111                         proto = WPA_PROTO_RSN;
1112                 else
1113                         proto = WPA_PROTO_WPA;
1114                 if (wpa_supplicant_suites_from_ai(wpa_s, ssid, &ie) < 0) {
1115                         os_memset(&ie, 0, sizeof(ie));
1116                         ie.group_cipher = ssid->group_cipher;
1117                         ie.pairwise_cipher = ssid->pairwise_cipher;
1118                         ie.key_mgmt = ssid->key_mgmt;
1119 #ifdef CONFIG_IEEE80211W
1120                         ie.mgmt_group_cipher =
1121                                 ssid->ieee80211w != NO_MGMT_FRAME_PROTECTION ?
1122                                 WPA_CIPHER_AES_128_CMAC : 0;
1123 #endif /* CONFIG_IEEE80211W */
1124                         wpa_dbg(wpa_s, MSG_DEBUG, "WPA: Set cipher suites "
1125                                 "based on configuration");
1126                 } else
1127                         proto = ie.proto;
1128         }
1129
1130         wpa_dbg(wpa_s, MSG_DEBUG, "WPA: Selected cipher suites: group %d "
1131                 "pairwise %d key_mgmt %d proto %d",
1132                 ie.group_cipher, ie.pairwise_cipher, ie.key_mgmt, proto);
1133 #ifdef CONFIG_IEEE80211W
1134         if (ssid->ieee80211w) {
1135                 wpa_dbg(wpa_s, MSG_DEBUG, "WPA: Selected mgmt group cipher %d",
1136                         ie.mgmt_group_cipher);
1137         }
1138 #endif /* CONFIG_IEEE80211W */
1139
1140         wpa_s->wpa_proto = proto;
1141         wpa_sm_set_param(wpa_s->wpa, WPA_PARAM_PROTO, proto);
1142         wpa_sm_set_param(wpa_s->wpa, WPA_PARAM_RSN_ENABLED,
1143                          !!(ssid->proto & (WPA_PROTO_RSN | WPA_PROTO_OSEN)));
1144
1145         if (bss || !wpa_s->ap_ies_from_associnfo) {
1146                 if (wpa_sm_set_ap_wpa_ie(wpa_s->wpa, bss_wpa,
1147                                          bss_wpa ? 2 + bss_wpa[1] : 0) ||
1148                     wpa_sm_set_ap_rsn_ie(wpa_s->wpa, bss_rsn,
1149                                          bss_rsn ? 2 + bss_rsn[1] : 0))
1150                         return -1;
1151         }
1152
1153         sel = ie.group_cipher & ssid->group_cipher;
1154         wpa_s->group_cipher = wpa_pick_group_cipher(sel);
1155         if (wpa_s->group_cipher < 0) {
1156                 wpa_msg(wpa_s, MSG_WARNING, "WPA: Failed to select group "
1157                         "cipher");
1158                 return -1;
1159         }
1160         wpa_dbg(wpa_s, MSG_DEBUG, "WPA: using GTK %s",
1161                 wpa_cipher_txt(wpa_s->group_cipher));
1162
1163         sel = ie.pairwise_cipher & ssid->pairwise_cipher;
1164         wpa_s->pairwise_cipher = wpa_pick_pairwise_cipher(sel, 1);
1165         if (wpa_s->pairwise_cipher < 0) {
1166                 wpa_msg(wpa_s, MSG_WARNING, "WPA: Failed to select pairwise "
1167                         "cipher");
1168                 return -1;
1169         }
1170         wpa_dbg(wpa_s, MSG_DEBUG, "WPA: using PTK %s",
1171                 wpa_cipher_txt(wpa_s->pairwise_cipher));
1172
1173         sel = ie.key_mgmt & ssid->key_mgmt;
1174 #ifdef CONFIG_SAE
1175         if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_SAE))
1176                 sel &= ~(WPA_KEY_MGMT_SAE | WPA_KEY_MGMT_FT_SAE);
1177 #endif /* CONFIG_SAE */
1178         if (0) {
1179 #ifdef CONFIG_SUITEB192
1180         } else if (sel & WPA_KEY_MGMT_IEEE8021X_SUITE_B_192) {
1181                 wpa_s->key_mgmt = WPA_KEY_MGMT_IEEE8021X_SUITE_B_192;
1182                 wpa_dbg(wpa_s, MSG_DEBUG,
1183                         "WPA: using KEY_MGMT 802.1X with Suite B (192-bit)");
1184 #endif /* CONFIG_SUITEB192 */
1185 #ifdef CONFIG_SUITEB
1186         } else if (sel & WPA_KEY_MGMT_IEEE8021X_SUITE_B) {
1187                 wpa_s->key_mgmt = WPA_KEY_MGMT_IEEE8021X_SUITE_B;
1188                 wpa_dbg(wpa_s, MSG_DEBUG,
1189                         "WPA: using KEY_MGMT 802.1X with Suite B");
1190 #endif /* CONFIG_SUITEB */
1191 #ifdef CONFIG_IEEE80211R
1192         } else if (sel & WPA_KEY_MGMT_FT_IEEE8021X) {
1193                 wpa_s->key_mgmt = WPA_KEY_MGMT_FT_IEEE8021X;
1194                 wpa_dbg(wpa_s, MSG_DEBUG, "WPA: using KEY_MGMT FT/802.1X");
1195         } else if (sel & WPA_KEY_MGMT_FT_PSK) {
1196                 wpa_s->key_mgmt = WPA_KEY_MGMT_FT_PSK;
1197                 wpa_dbg(wpa_s, MSG_DEBUG, "WPA: using KEY_MGMT FT/PSK");
1198 #endif /* CONFIG_IEEE80211R */
1199 #ifdef CONFIG_SAE
1200         } else if (sel & WPA_KEY_MGMT_SAE) {
1201                 wpa_s->key_mgmt = WPA_KEY_MGMT_SAE;
1202                 wpa_dbg(wpa_s, MSG_DEBUG, "RSN: using KEY_MGMT SAE");
1203         } else if (sel & WPA_KEY_MGMT_FT_SAE) {
1204                 wpa_s->key_mgmt = WPA_KEY_MGMT_FT_SAE;
1205                 wpa_dbg(wpa_s, MSG_DEBUG, "RSN: using KEY_MGMT FT/SAE");
1206 #endif /* CONFIG_SAE */
1207 #ifdef CONFIG_IEEE80211W
1208         } else if (sel & WPA_KEY_MGMT_IEEE8021X_SHA256) {
1209                 wpa_s->key_mgmt = WPA_KEY_MGMT_IEEE8021X_SHA256;
1210                 wpa_dbg(wpa_s, MSG_DEBUG,
1211                         "WPA: using KEY_MGMT 802.1X with SHA256");
1212         } else if (sel & WPA_KEY_MGMT_PSK_SHA256) {
1213                 wpa_s->key_mgmt = WPA_KEY_MGMT_PSK_SHA256;
1214                 wpa_dbg(wpa_s, MSG_DEBUG,
1215                         "WPA: using KEY_MGMT PSK with SHA256");
1216 #endif /* CONFIG_IEEE80211W */
1217         } else if (sel & WPA_KEY_MGMT_IEEE8021X) {
1218                 wpa_s->key_mgmt = WPA_KEY_MGMT_IEEE8021X;
1219                 wpa_dbg(wpa_s, MSG_DEBUG, "WPA: using KEY_MGMT 802.1X");
1220         } else if (sel & WPA_KEY_MGMT_PSK) {
1221                 wpa_s->key_mgmt = WPA_KEY_MGMT_PSK;
1222                 wpa_dbg(wpa_s, MSG_DEBUG, "WPA: using KEY_MGMT WPA-PSK");
1223         } else if (sel & WPA_KEY_MGMT_WPA_NONE) {
1224                 wpa_s->key_mgmt = WPA_KEY_MGMT_WPA_NONE;
1225                 wpa_dbg(wpa_s, MSG_DEBUG, "WPA: using KEY_MGMT WPA-NONE");
1226 #ifdef CONFIG_HS20
1227         } else if (sel & WPA_KEY_MGMT_OSEN) {
1228                 wpa_s->key_mgmt = WPA_KEY_MGMT_OSEN;
1229                 wpa_dbg(wpa_s, MSG_DEBUG, "HS 2.0: using KEY_MGMT OSEN");
1230 #endif /* CONFIG_HS20 */
1231         } else {
1232                 wpa_msg(wpa_s, MSG_WARNING, "WPA: Failed to select "
1233                         "authenticated key management type");
1234                 return -1;
1235         }
1236
1237         wpa_sm_set_param(wpa_s->wpa, WPA_PARAM_KEY_MGMT, wpa_s->key_mgmt);
1238         wpa_sm_set_param(wpa_s->wpa, WPA_PARAM_PAIRWISE,
1239                          wpa_s->pairwise_cipher);
1240         wpa_sm_set_param(wpa_s->wpa, WPA_PARAM_GROUP, wpa_s->group_cipher);
1241
1242 #ifdef CONFIG_IEEE80211W
1243         sel = ie.mgmt_group_cipher;
1244         if (wpas_get_ssid_pmf(wpa_s, ssid) == NO_MGMT_FRAME_PROTECTION ||
1245             !(ie.capabilities & WPA_CAPABILITY_MFPC))
1246                 sel = 0;
1247         if (sel & WPA_CIPHER_AES_128_CMAC) {
1248                 wpa_s->mgmt_group_cipher = WPA_CIPHER_AES_128_CMAC;
1249                 wpa_dbg(wpa_s, MSG_DEBUG, "WPA: using MGMT group cipher "
1250                         "AES-128-CMAC");
1251         } else if (sel & WPA_CIPHER_BIP_GMAC_128) {
1252                 wpa_s->mgmt_group_cipher = WPA_CIPHER_BIP_GMAC_128;
1253                 wpa_dbg(wpa_s, MSG_DEBUG, "WPA: using MGMT group cipher "
1254                         "BIP-GMAC-128");
1255         } else if (sel & WPA_CIPHER_BIP_GMAC_256) {
1256                 wpa_s->mgmt_group_cipher = WPA_CIPHER_BIP_GMAC_256;
1257                 wpa_dbg(wpa_s, MSG_DEBUG, "WPA: using MGMT group cipher "
1258                         "BIP-GMAC-256");
1259         } else if (sel & WPA_CIPHER_BIP_CMAC_256) {
1260                 wpa_s->mgmt_group_cipher = WPA_CIPHER_BIP_CMAC_256;
1261                 wpa_dbg(wpa_s, MSG_DEBUG, "WPA: using MGMT group cipher "
1262                         "BIP-CMAC-256");
1263         } else {
1264                 wpa_s->mgmt_group_cipher = 0;
1265                 wpa_dbg(wpa_s, MSG_DEBUG, "WPA: not using MGMT group cipher");
1266         }
1267         wpa_sm_set_param(wpa_s->wpa, WPA_PARAM_MGMT_GROUP,
1268                          wpa_s->mgmt_group_cipher);
1269         wpa_sm_set_param(wpa_s->wpa, WPA_PARAM_MFP,
1270                          wpas_get_ssid_pmf(wpa_s, ssid));
1271 #endif /* CONFIG_IEEE80211W */
1272
1273         if (wpa_sm_set_assoc_wpa_ie_default(wpa_s->wpa, wpa_ie, wpa_ie_len)) {
1274                 wpa_msg(wpa_s, MSG_WARNING, "WPA: Failed to generate WPA IE");
1275                 return -1;
1276         }
1277
1278         if (wpa_key_mgmt_wpa_psk(ssid->key_mgmt)) {
1279                 int psk_set = 0;
1280
1281                 if (ssid->psk_set) {
1282                         wpa_sm_set_pmk(wpa_s->wpa, ssid->psk, PMK_LEN, NULL);
1283                         psk_set = 1;
1284                 }
1285 #ifndef CONFIG_NO_PBKDF2
1286                 if (bss && ssid->bssid_set && ssid->ssid_len == 0 &&
1287                     ssid->passphrase) {
1288                         u8 psk[PMK_LEN];
1289                         pbkdf2_sha1(ssid->passphrase, bss->ssid, bss->ssid_len,
1290                                     4096, psk, PMK_LEN);
1291                         wpa_hexdump_key(MSG_MSGDUMP, "PSK (from passphrase)",
1292                                         psk, PMK_LEN);
1293                         wpa_sm_set_pmk(wpa_s->wpa, psk, PMK_LEN, NULL);
1294                         psk_set = 1;
1295                         os_memset(psk, 0, sizeof(psk));
1296                 }
1297 #endif /* CONFIG_NO_PBKDF2 */
1298 #ifdef CONFIG_EXT_PASSWORD
1299                 if (ssid->ext_psk) {
1300                         struct wpabuf *pw = ext_password_get(wpa_s->ext_pw,
1301                                                              ssid->ext_psk);
1302                         char pw_str[64 + 1];
1303                         u8 psk[PMK_LEN];
1304
1305                         if (pw == NULL) {
1306                                 wpa_msg(wpa_s, MSG_INFO, "EXT PW: No PSK "
1307                                         "found from external storage");
1308                                 return -1;
1309                         }
1310
1311                         if (wpabuf_len(pw) < 8 || wpabuf_len(pw) > 64) {
1312                                 wpa_msg(wpa_s, MSG_INFO, "EXT PW: Unexpected "
1313                                         "PSK length %d in external storage",
1314                                         (int) wpabuf_len(pw));
1315                                 ext_password_free(pw);
1316                                 return -1;
1317                         }
1318
1319                         os_memcpy(pw_str, wpabuf_head(pw), wpabuf_len(pw));
1320                         pw_str[wpabuf_len(pw)] = '\0';
1321
1322 #ifndef CONFIG_NO_PBKDF2
1323                         if (wpabuf_len(pw) >= 8 && wpabuf_len(pw) < 64 && bss)
1324                         {
1325                                 pbkdf2_sha1(pw_str, bss->ssid, bss->ssid_len,
1326                                             4096, psk, PMK_LEN);
1327                                 os_memset(pw_str, 0, sizeof(pw_str));
1328                                 wpa_hexdump_key(MSG_MSGDUMP, "PSK (from "
1329                                                 "external passphrase)",
1330                                                 psk, PMK_LEN);
1331                                 wpa_sm_set_pmk(wpa_s->wpa, psk, PMK_LEN, NULL);
1332                                 psk_set = 1;
1333                                 os_memset(psk, 0, sizeof(psk));
1334                         } else
1335 #endif /* CONFIG_NO_PBKDF2 */
1336                         if (wpabuf_len(pw) == 2 * PMK_LEN) {
1337                                 if (hexstr2bin(pw_str, psk, PMK_LEN) < 0) {
1338                                         wpa_msg(wpa_s, MSG_INFO, "EXT PW: "
1339                                                 "Invalid PSK hex string");
1340                                         os_memset(pw_str, 0, sizeof(pw_str));
1341                                         ext_password_free(pw);
1342                                         return -1;
1343                                 }
1344                                 wpa_sm_set_pmk(wpa_s->wpa, psk, PMK_LEN, NULL);
1345                                 psk_set = 1;
1346                                 os_memset(psk, 0, sizeof(psk));
1347                         } else {
1348                                 wpa_msg(wpa_s, MSG_INFO, "EXT PW: No suitable "
1349                                         "PSK available");
1350                                 os_memset(pw_str, 0, sizeof(pw_str));
1351                                 ext_password_free(pw);
1352                                 return -1;
1353                         }
1354
1355                         os_memset(pw_str, 0, sizeof(pw_str));
1356                         ext_password_free(pw);
1357                 }
1358 #endif /* CONFIG_EXT_PASSWORD */
1359
1360                 if (!psk_set) {
1361                         wpa_msg(wpa_s, MSG_INFO,
1362                                 "No PSK available for association");
1363                         return -1;
1364                 }
1365         } else
1366                 wpa_sm_set_pmk_from_pmksa(wpa_s->wpa);
1367
1368         return 0;
1369 }
1370
1371
1372 static void wpas_ext_capab_byte(struct wpa_supplicant *wpa_s, u8 *pos, int idx)
1373 {
1374         *pos = 0x00;
1375
1376         switch (idx) {
1377         case 0: /* Bits 0-7 */
1378                 break;
1379         case 1: /* Bits 8-15 */
1380                 break;
1381         case 2: /* Bits 16-23 */
1382 #ifdef CONFIG_WNM
1383                 *pos |= 0x02; /* Bit 17 - WNM-Sleep Mode */
1384                 *pos |= 0x08; /* Bit 19 - BSS Transition */
1385 #endif /* CONFIG_WNM */
1386                 break;
1387         case 3: /* Bits 24-31 */
1388 #ifdef CONFIG_WNM
1389                 *pos |= 0x02; /* Bit 25 - SSID List */
1390 #endif /* CONFIG_WNM */
1391 #ifdef CONFIG_INTERWORKING
1392                 if (wpa_s->conf->interworking)
1393                         *pos |= 0x80; /* Bit 31 - Interworking */
1394 #endif /* CONFIG_INTERWORKING */
1395                 break;
1396         case 4: /* Bits 32-39 */
1397 #ifdef CONFIG_INTERWORKING
1398                 if (wpa_s->drv_flags / WPA_DRIVER_FLAGS_QOS_MAPPING)
1399                         *pos |= 0x01; /* Bit 32 - QoS Map */
1400 #endif /* CONFIG_INTERWORKING */
1401                 break;
1402         case 5: /* Bits 40-47 */
1403 #ifdef CONFIG_HS20
1404                 if (wpa_s->conf->hs20)
1405                         *pos |= 0x40; /* Bit 46 - WNM-Notification */
1406 #endif /* CONFIG_HS20 */
1407                 break;
1408         case 6: /* Bits 48-55 */
1409                 break;
1410         }
1411 }
1412
1413
1414 int wpas_build_ext_capab(struct wpa_supplicant *wpa_s, u8 *buf, size_t buflen)
1415 {
1416         u8 *pos = buf;
1417         u8 len = 6, i;
1418
1419         if (len < wpa_s->extended_capa_len)
1420                 len = wpa_s->extended_capa_len;
1421         if (buflen < (size_t) len + 2) {
1422                 wpa_printf(MSG_INFO,
1423                            "Not enough room for building extended capabilities element");
1424                 return -1;
1425         }
1426
1427         *pos++ = WLAN_EID_EXT_CAPAB;
1428         *pos++ = len;
1429         for (i = 0; i < len; i++, pos++) {
1430                 wpas_ext_capab_byte(wpa_s, pos, i);
1431
1432                 if (i < wpa_s->extended_capa_len) {
1433                         *pos &= ~wpa_s->extended_capa_mask[i];
1434                         *pos |= wpa_s->extended_capa[i];
1435                 }
1436         }
1437
1438         while (len > 0 && buf[1 + len] == 0) {
1439                 len--;
1440                 buf[1] = len;
1441         }
1442         if (len == 0)
1443                 return 0;
1444
1445         return 2 + len;
1446 }
1447
1448
1449 static int wpas_valid_bss(struct wpa_supplicant *wpa_s,
1450                           struct wpa_bss *test_bss)
1451 {
1452         struct wpa_bss *bss;
1453
1454         dl_list_for_each(bss, &wpa_s->bss, struct wpa_bss, list) {
1455                 if (bss == test_bss)
1456                         return 1;
1457         }
1458
1459         return 0;
1460 }
1461
1462
1463 static int wpas_valid_ssid(struct wpa_supplicant *wpa_s,
1464                            struct wpa_ssid *test_ssid)
1465 {
1466         struct wpa_ssid *ssid;
1467
1468         for (ssid = wpa_s->conf->ssid; ssid; ssid = ssid->next) {
1469                 if (ssid == test_ssid)
1470                         return 1;
1471         }
1472
1473         return 0;
1474 }
1475
1476
1477 int wpas_valid_bss_ssid(struct wpa_supplicant *wpa_s, struct wpa_bss *test_bss,
1478                         struct wpa_ssid *test_ssid)
1479 {
1480         if (test_bss && !wpas_valid_bss(wpa_s, test_bss))
1481                 return 0;
1482
1483         return test_ssid == NULL || wpas_valid_ssid(wpa_s, test_ssid);
1484 }
1485
1486
1487 void wpas_connect_work_free(struct wpa_connect_work *cwork)
1488 {
1489         if (cwork == NULL)
1490                 return;
1491         os_free(cwork);
1492 }
1493
1494
1495 void wpas_connect_work_done(struct wpa_supplicant *wpa_s)
1496 {
1497         struct wpa_connect_work *cwork;
1498         struct wpa_radio_work *work = wpa_s->connect_work;
1499
1500         if (!work)
1501                 return;
1502
1503         wpa_s->connect_work = NULL;
1504         cwork = work->ctx;
1505         work->ctx = NULL;
1506         wpas_connect_work_free(cwork);
1507         radio_work_done(work);
1508 }
1509
1510
1511 int wpas_update_random_addr(struct wpa_supplicant *wpa_s, int style)
1512 {
1513         struct os_reltime now;
1514         u8 addr[ETH_ALEN];
1515
1516         os_get_reltime(&now);
1517         if (wpa_s->last_mac_addr_style == style &&
1518             wpa_s->last_mac_addr_change.sec != 0 &&
1519             !os_reltime_expired(&now, &wpa_s->last_mac_addr_change,
1520                                 wpa_s->conf->rand_addr_lifetime)) {
1521                 wpa_msg(wpa_s, MSG_DEBUG,
1522                         "Previously selected random MAC address has not yet expired");
1523                 return 0;
1524         }
1525
1526         switch (style) {
1527         case 1:
1528                 if (random_mac_addr(addr) < 0)
1529                         return -1;
1530                 break;
1531         case 2:
1532                 os_memcpy(addr, wpa_s->perm_addr, ETH_ALEN);
1533                 if (random_mac_addr_keep_oui(addr) < 0)
1534                         return -1;
1535                 break;
1536         default:
1537                 return -1;
1538         }
1539
1540         if (wpa_drv_set_mac_addr(wpa_s, addr) < 0) {
1541                 wpa_msg(wpa_s, MSG_INFO,
1542                         "Failed to set random MAC address");
1543                 return -1;
1544         }
1545
1546         os_get_reltime(&wpa_s->last_mac_addr_change);
1547         wpa_s->mac_addr_changed = 1;
1548         wpa_s->last_mac_addr_style = style;
1549
1550         if (wpa_supplicant_update_mac_addr(wpa_s) < 0) {
1551                 wpa_msg(wpa_s, MSG_INFO,
1552                         "Could not update MAC address information");
1553                 return -1;
1554         }
1555
1556         wpa_msg(wpa_s, MSG_DEBUG, "Using random MAC address " MACSTR,
1557                 MAC2STR(addr));
1558
1559         return 0;
1560 }
1561
1562
1563 int wpas_update_random_addr_disassoc(struct wpa_supplicant *wpa_s)
1564 {
1565         if (wpa_s->wpa_state >= WPA_AUTHENTICATING ||
1566             !wpa_s->conf->preassoc_mac_addr)
1567                 return 0;
1568
1569         return wpas_update_random_addr(wpa_s, wpa_s->conf->preassoc_mac_addr);
1570 }
1571
1572
1573 static void wpas_start_assoc_cb(struct wpa_radio_work *work, int deinit);
1574
1575 /**
1576  * wpa_supplicant_associate - Request association
1577  * @wpa_s: Pointer to wpa_supplicant data
1578  * @bss: Scan results for the selected BSS, or %NULL if not available
1579  * @ssid: Configuration data for the selected network
1580  *
1581  * This function is used to request %wpa_supplicant to associate with a BSS.
1582  */
1583 void wpa_supplicant_associate(struct wpa_supplicant *wpa_s,
1584                               struct wpa_bss *bss, struct wpa_ssid *ssid)
1585 {
1586         struct wpa_connect_work *cwork;
1587         int rand_style;
1588
1589         if (ssid->mac_addr == -1)
1590                 rand_style = wpa_s->conf->mac_addr;
1591         else
1592                 rand_style = ssid->mac_addr;
1593
1594         wmm_ac_clear_saved_tspecs(wpa_s);
1595         wpa_s->reassoc_same_bss = 0;
1596
1597         if (wpa_s->last_ssid == ssid) {
1598                 wpa_dbg(wpa_s, MSG_DEBUG, "Re-association to the same ESS");
1599                 if (wpa_s->current_bss && wpa_s->current_bss == bss) {
1600                         wmm_ac_save_tspecs(wpa_s);
1601                         wpa_s->reassoc_same_bss = 1;
1602                 }
1603         } else if (rand_style > 0) {
1604                 if (wpas_update_random_addr(wpa_s, rand_style) < 0)
1605                         return;
1606                 wpa_sm_pmksa_cache_flush(wpa_s->wpa, ssid);
1607         } else if (wpa_s->mac_addr_changed) {
1608                 if (wpa_drv_set_mac_addr(wpa_s, NULL) < 0) {
1609                         wpa_msg(wpa_s, MSG_INFO,
1610                                 "Could not restore permanent MAC address");
1611                         return;
1612                 }
1613                 wpa_s->mac_addr_changed = 0;
1614                 if (wpa_supplicant_update_mac_addr(wpa_s) < 0) {
1615                         wpa_msg(wpa_s, MSG_INFO,
1616                                 "Could not update MAC address information");
1617                         return;
1618                 }
1619                 wpa_msg(wpa_s, MSG_DEBUG, "Using permanent MAC address");
1620         }
1621         wpa_s->last_ssid = ssid;
1622
1623 #ifdef CONFIG_IBSS_RSN
1624         ibss_rsn_deinit(wpa_s->ibss_rsn);
1625         wpa_s->ibss_rsn = NULL;
1626 #endif /* CONFIG_IBSS_RSN */
1627
1628         if (ssid->mode == WPAS_MODE_AP || ssid->mode == WPAS_MODE_P2P_GO ||
1629             ssid->mode == WPAS_MODE_P2P_GROUP_FORMATION) {
1630 #ifdef CONFIG_AP
1631                 if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_AP)) {
1632                         wpa_msg(wpa_s, MSG_INFO, "Driver does not support AP "
1633                                 "mode");
1634                         return;
1635                 }
1636                 if (wpa_supplicant_create_ap(wpa_s, ssid) < 0) {
1637                         wpa_supplicant_set_state(wpa_s, WPA_DISCONNECTED);
1638                         if (ssid->mode == WPAS_MODE_P2P_GROUP_FORMATION)
1639                                 wpas_p2p_ap_setup_failed(wpa_s);
1640                         return;
1641                 }
1642                 wpa_s->current_bss = bss;
1643 #else /* CONFIG_AP */
1644                 wpa_msg(wpa_s, MSG_ERROR, "AP mode support not included in "
1645                         "the build");
1646 #endif /* CONFIG_AP */
1647                 return;
1648         }
1649
1650         if (ssid->mode == WPAS_MODE_MESH) {
1651 #ifdef CONFIG_MESH
1652                 if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_MESH)) {
1653                         wpa_msg(wpa_s, MSG_INFO,
1654                                 "Driver does not support mesh mode");
1655                         return;
1656                 }
1657                 if (bss)
1658                         ssid->frequency = bss->freq;
1659                 if (wpa_supplicant_join_mesh(wpa_s, ssid) < 0) {
1660                         wpa_msg(wpa_s, MSG_ERROR, "Could not join mesh");
1661                         return;
1662                 }
1663                 wpa_s->current_bss = bss;
1664                 wpa_msg_ctrl(wpa_s, MSG_INFO, MESH_GROUP_STARTED
1665                              "ssid=\"%s\" id=%d",
1666                              wpa_ssid_txt(ssid->ssid, ssid->ssid_len),
1667                              ssid->id);
1668 #else /* CONFIG_MESH */
1669                 wpa_msg(wpa_s, MSG_ERROR,
1670                         "mesh mode support not included in the build");
1671 #endif /* CONFIG_MESH */
1672                 return;
1673         }
1674
1675 #ifdef CONFIG_TDLS
1676         if (bss)
1677                 wpa_tdls_ap_ies(wpa_s->wpa, (const u8 *) (bss + 1),
1678                                 bss->ie_len);
1679 #endif /* CONFIG_TDLS */
1680
1681         if ((wpa_s->drv_flags & WPA_DRIVER_FLAGS_SME) &&
1682             ssid->mode == IEEE80211_MODE_INFRA) {
1683                 sme_authenticate(wpa_s, bss, ssid);
1684                 return;
1685         }
1686
1687         if (wpa_s->connect_work) {
1688                 wpa_dbg(wpa_s, MSG_DEBUG, "Reject wpa_supplicant_associate() call since connect_work exist");
1689                 return;
1690         }
1691
1692         if (radio_work_pending(wpa_s, "connect")) {
1693                 wpa_dbg(wpa_s, MSG_DEBUG, "Reject wpa_supplicant_associate() call since pending work exist");
1694                 return;
1695         }
1696
1697         cwork = os_zalloc(sizeof(*cwork));
1698         if (cwork == NULL)
1699                 return;
1700
1701         cwork->bss = bss;
1702         cwork->ssid = ssid;
1703
1704         if (radio_add_work(wpa_s, bss ? bss->freq : 0, "connect", 1,
1705                            wpas_start_assoc_cb, cwork) < 0) {
1706                 os_free(cwork);
1707         }
1708 }
1709
1710
1711 static int bss_is_ibss(struct wpa_bss *bss)
1712 {
1713         return (bss->caps & (IEEE80211_CAP_ESS | IEEE80211_CAP_IBSS)) ==
1714                 IEEE80211_CAP_IBSS;
1715 }
1716
1717
1718 void ibss_mesh_setup_freq(struct wpa_supplicant *wpa_s,
1719                           const struct wpa_ssid *ssid,
1720                           struct hostapd_freq_params *freq)
1721 {
1722         enum hostapd_hw_mode hw_mode;
1723         struct hostapd_hw_modes *mode = NULL;
1724         int ht40plus[] = { 36, 44, 52, 60, 100, 108, 116, 124, 132, 149, 157,
1725                            184, 192 };
1726         int vht80[] = { 36, 52, 100, 116, 132, 149 };
1727         struct hostapd_channel_data *pri_chan = NULL, *sec_chan = NULL;
1728         u8 channel;
1729         int i, chan_idx, ht40 = -1, res, obss_scan = 1;
1730         unsigned int j;
1731         struct hostapd_freq_params vht_freq;
1732
1733         freq->freq = ssid->frequency;
1734
1735         for (j = 0; j < wpa_s->last_scan_res_used; j++) {
1736                 struct wpa_bss *bss = wpa_s->last_scan_res[j];
1737
1738                 if (ssid->mode != WPAS_MODE_IBSS)
1739                         break;
1740
1741                 /* Don't adjust control freq in case of fixed_freq */
1742                 if (ssid->fixed_freq)
1743                         break;
1744
1745                 if (!bss_is_ibss(bss))
1746                         continue;
1747
1748                 if (ssid->ssid_len == bss->ssid_len &&
1749                     os_memcmp(ssid->ssid, bss->ssid, bss->ssid_len) == 0) {
1750                         wpa_printf(MSG_DEBUG,
1751                                    "IBSS already found in scan results, adjust control freq: %d",
1752                                    bss->freq);
1753                         freq->freq = bss->freq;
1754                         obss_scan = 0;
1755                         break;
1756                 }
1757         }
1758
1759         /* For IBSS check HT_IBSS flag */
1760         if (ssid->mode == WPAS_MODE_IBSS &&
1761             !(wpa_s->drv_flags & WPA_DRIVER_FLAGS_HT_IBSS))
1762                 return;
1763
1764         if (wpa_s->group_cipher == WPA_CIPHER_WEP40 ||
1765             wpa_s->group_cipher == WPA_CIPHER_WEP104 ||
1766             wpa_s->pairwise_cipher == WPA_CIPHER_TKIP) {
1767                 wpa_printf(MSG_DEBUG,
1768                            "IBSS: WEP/TKIP detected, do not try to enable HT");
1769                 return;
1770         }
1771
1772         hw_mode = ieee80211_freq_to_chan(freq->freq, &channel);
1773         for (i = 0; wpa_s->hw.modes && i < wpa_s->hw.num_modes; i++) {
1774                 if (wpa_s->hw.modes[i].mode == hw_mode) {
1775                         mode = &wpa_s->hw.modes[i];
1776                         break;
1777                 }
1778         }
1779
1780         if (!mode)
1781                 return;
1782
1783         freq->ht_enabled = ht_supported(mode);
1784         if (!freq->ht_enabled)
1785                 return;
1786
1787         /* Setup higher BW only for 5 GHz */
1788         if (mode->mode != HOSTAPD_MODE_IEEE80211A)
1789                 return;
1790
1791         for (chan_idx = 0; chan_idx < mode->num_channels; chan_idx++) {
1792                 pri_chan = &mode->channels[chan_idx];
1793                 if (pri_chan->chan == channel)
1794                         break;
1795                 pri_chan = NULL;
1796         }
1797         if (!pri_chan)
1798                 return;
1799
1800         /* Check primary channel flags */
1801         if (pri_chan->flag & (HOSTAPD_CHAN_DISABLED | HOSTAPD_CHAN_NO_IR))
1802                 return;
1803
1804         /* Check/setup HT40+/HT40- */
1805         for (j = 0; j < ARRAY_SIZE(ht40plus); j++) {
1806                 if (ht40plus[j] == channel) {
1807                         ht40 = 1;
1808                         break;
1809                 }
1810         }
1811
1812         /* Find secondary channel */
1813         for (i = 0; i < mode->num_channels; i++) {
1814                 sec_chan = &mode->channels[i];
1815                 if (sec_chan->chan == channel + ht40 * 4)
1816                         break;
1817                 sec_chan = NULL;
1818         }
1819         if (!sec_chan)
1820                 return;
1821
1822         /* Check secondary channel flags */
1823         if (sec_chan->flag & (HOSTAPD_CHAN_DISABLED | HOSTAPD_CHAN_NO_IR))
1824                 return;
1825
1826         freq->channel = pri_chan->chan;
1827
1828         switch (ht40) {
1829         case -1:
1830                 if (!(pri_chan->flag & HOSTAPD_CHAN_HT40MINUS))
1831                         return;
1832                 freq->sec_channel_offset = -1;
1833                 break;
1834         case 1:
1835                 if (!(pri_chan->flag & HOSTAPD_CHAN_HT40PLUS))
1836                         return;
1837                 freq->sec_channel_offset = 1;
1838                 break;
1839         default:
1840                 break;
1841         }
1842
1843         if (freq->sec_channel_offset && obss_scan) {
1844                 struct wpa_scan_results *scan_res;
1845
1846                 scan_res = wpa_supplicant_get_scan_results(wpa_s, NULL, 0);
1847                 if (scan_res == NULL) {
1848                         /* Back to HT20 */
1849                         freq->sec_channel_offset = 0;
1850                         return;
1851                 }
1852
1853                 res = check_40mhz_5g(mode, scan_res, pri_chan->chan,
1854                                      sec_chan->chan);
1855                 switch (res) {
1856                 case 0:
1857                         /* Back to HT20 */
1858                         freq->sec_channel_offset = 0;
1859                         break;
1860                 case 1:
1861                         /* Configuration allowed */
1862                         break;
1863                 case 2:
1864                         /* Switch pri/sec channels */
1865                         freq->freq = hw_get_freq(mode, sec_chan->chan);
1866                         freq->sec_channel_offset = -freq->sec_channel_offset;
1867                         freq->channel = sec_chan->chan;
1868                         break;
1869                 default:
1870                         freq->sec_channel_offset = 0;
1871                         break;
1872                 }
1873
1874                 wpa_scan_results_free(scan_res);
1875         }
1876
1877         wpa_printf(MSG_DEBUG,
1878                    "IBSS/mesh: setup freq channel %d, sec_channel_offset %d",
1879                    freq->channel, freq->sec_channel_offset);
1880
1881         /* Not sure if mesh is ready for VHT */
1882         if (ssid->mode != WPAS_MODE_IBSS)
1883                 return;
1884
1885         /* For IBSS check VHT_IBSS flag */
1886         if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_VHT_IBSS))
1887                 return;
1888
1889         vht_freq = *freq;
1890
1891         vht_freq.vht_enabled = vht_supported(mode);
1892         if (!vht_freq.vht_enabled)
1893                 return;
1894
1895         /* setup center_freq1, bandwidth */
1896         for (j = 0; j < ARRAY_SIZE(vht80); j++) {
1897                 if (freq->channel >= vht80[j] &&
1898                     freq->channel < vht80[j] + 16)
1899                         break;
1900         }
1901
1902         if (j == ARRAY_SIZE(vht80))
1903                 return;
1904
1905         for (i = vht80[j]; i < vht80[j] + 16; i += 4) {
1906                 struct hostapd_channel_data *chan;
1907
1908                 chan = hw_get_channel_chan(mode, i, NULL);
1909                 if (!chan)
1910                         return;
1911
1912                 /* Back to HT configuration if channel not usable */
1913                 if (chan->flag & (HOSTAPD_CHAN_DISABLED | HOSTAPD_CHAN_NO_IR))
1914                         return;
1915         }
1916
1917         if (hostapd_set_freq_params(&vht_freq, mode->mode, freq->freq,
1918                                     freq->channel, freq->ht_enabled,
1919                                     vht_freq.vht_enabled,
1920                                     freq->sec_channel_offset,
1921                                     VHT_CHANWIDTH_80MHZ,
1922                                     vht80[j] + 6, 0, 0) != 0)
1923                 return;
1924
1925         *freq = vht_freq;
1926
1927         wpa_printf(MSG_DEBUG, "IBSS: VHT setup freq cf1 %d, cf2 %d, bw %d",
1928                    freq->center_freq1, freq->center_freq2, freq->bandwidth);
1929 }
1930
1931
1932 static void wpas_start_assoc_cb(struct wpa_radio_work *work, int deinit)
1933 {
1934         struct wpa_connect_work *cwork = work->ctx;
1935         struct wpa_bss *bss = cwork->bss;
1936         struct wpa_ssid *ssid = cwork->ssid;
1937         struct wpa_supplicant *wpa_s = work->wpa_s;
1938         u8 wpa_ie[200];
1939         size_t wpa_ie_len;
1940         int use_crypt, ret, i, bssid_changed;
1941         int algs = WPA_AUTH_ALG_OPEN;
1942         unsigned int cipher_pairwise, cipher_group;
1943         struct wpa_driver_associate_params params;
1944         int wep_keys_set = 0;
1945         int assoc_failed = 0;
1946         struct wpa_ssid *old_ssid;
1947 #ifdef CONFIG_HT_OVERRIDES
1948         struct ieee80211_ht_capabilities htcaps;
1949         struct ieee80211_ht_capabilities htcaps_mask;
1950 #endif /* CONFIG_HT_OVERRIDES */
1951 #ifdef CONFIG_VHT_OVERRIDES
1952        struct ieee80211_vht_capabilities vhtcaps;
1953        struct ieee80211_vht_capabilities vhtcaps_mask;
1954 #endif /* CONFIG_VHT_OVERRIDES */
1955
1956         if (deinit) {
1957                 if (work->started) {
1958                         wpa_s->connect_work = NULL;
1959
1960                         /* cancel possible auth. timeout */
1961                         eloop_cancel_timeout(wpa_supplicant_timeout, wpa_s,
1962                                              NULL);
1963                 }
1964                 wpas_connect_work_free(cwork);
1965                 return;
1966         }
1967
1968         wpa_s->connect_work = work;
1969
1970         if (cwork->bss_removed || !wpas_valid_bss_ssid(wpa_s, bss, ssid) ||
1971             wpas_network_disabled(wpa_s, ssid)) {
1972                 wpa_dbg(wpa_s, MSG_DEBUG, "BSS/SSID entry for association not valid anymore - drop connection attempt");
1973                 wpas_connect_work_done(wpa_s);
1974                 return;
1975         }
1976
1977         os_memset(&params, 0, sizeof(params));
1978         wpa_s->reassociate = 0;
1979         wpa_s->eap_expected_failure = 0;
1980         if (bss &&
1981             (!wpas_driver_bss_selection(wpa_s) || wpas_wps_searching(wpa_s))) {
1982 #ifdef CONFIG_IEEE80211R
1983                 const u8 *ie, *md = NULL;
1984 #endif /* CONFIG_IEEE80211R */
1985                 wpa_msg(wpa_s, MSG_INFO, "Trying to associate with " MACSTR
1986                         " (SSID='%s' freq=%d MHz)", MAC2STR(bss->bssid),
1987                         wpa_ssid_txt(bss->ssid, bss->ssid_len), bss->freq);
1988                 bssid_changed = !is_zero_ether_addr(wpa_s->bssid);
1989                 os_memset(wpa_s->bssid, 0, ETH_ALEN);
1990                 os_memcpy(wpa_s->pending_bssid, bss->bssid, ETH_ALEN);
1991                 if (bssid_changed)
1992                         wpas_notify_bssid_changed(wpa_s);
1993 #ifdef CONFIG_IEEE80211R
1994                 ie = wpa_bss_get_ie(bss, WLAN_EID_MOBILITY_DOMAIN);
1995                 if (ie && ie[1] >= MOBILITY_DOMAIN_ID_LEN)
1996                         md = ie + 2;
1997                 wpa_sm_set_ft_params(wpa_s->wpa, ie, ie ? 2 + ie[1] : 0);
1998                 if (md) {
1999                         /* Prepare for the next transition */
2000                         wpa_ft_prepare_auth_request(wpa_s->wpa, ie);
2001                 }
2002 #endif /* CONFIG_IEEE80211R */
2003 #ifdef CONFIG_WPS
2004         } else if ((ssid->ssid == NULL || ssid->ssid_len == 0) &&
2005                    wpa_s->conf->ap_scan == 2 &&
2006                    (ssid->key_mgmt & WPA_KEY_MGMT_WPS)) {
2007                 /* Use ap_scan==1 style network selection to find the network
2008                  */
2009                 wpas_connect_work_done(wpa_s);
2010                 wpa_s->scan_req = MANUAL_SCAN_REQ;
2011                 wpa_s->reassociate = 1;
2012                 wpa_supplicant_req_scan(wpa_s, 0, 0);
2013                 return;
2014 #endif /* CONFIG_WPS */
2015         } else {
2016                 wpa_msg(wpa_s, MSG_INFO, "Trying to associate with SSID '%s'",
2017                         wpa_ssid_txt(ssid->ssid, ssid->ssid_len));
2018                 os_memset(wpa_s->pending_bssid, 0, ETH_ALEN);
2019         }
2020         if (!wpa_s->pno)
2021                 wpa_supplicant_cancel_sched_scan(wpa_s);
2022
2023         wpa_supplicant_cancel_scan(wpa_s);
2024
2025         /* Starting new association, so clear the possibly used WPA IE from the
2026          * previous association. */
2027         wpa_sm_set_assoc_wpa_ie(wpa_s->wpa, NULL, 0);
2028
2029 #ifdef IEEE8021X_EAPOL
2030         if (ssid->key_mgmt & WPA_KEY_MGMT_IEEE8021X_NO_WPA) {
2031                 if (ssid->leap) {
2032                         if (ssid->non_leap == 0)
2033                                 algs = WPA_AUTH_ALG_LEAP;
2034                         else
2035                                 algs |= WPA_AUTH_ALG_LEAP;
2036                 }
2037         }
2038 #endif /* IEEE8021X_EAPOL */
2039         wpa_dbg(wpa_s, MSG_DEBUG, "Automatic auth_alg selection: 0x%x", algs);
2040         if (ssid->auth_alg) {
2041                 algs = ssid->auth_alg;
2042                 wpa_dbg(wpa_s, MSG_DEBUG, "Overriding auth_alg selection: "
2043                         "0x%x", algs);
2044         }
2045
2046         if (bss && (wpa_bss_get_vendor_ie(bss, WPA_IE_VENDOR_TYPE) ||
2047                     wpa_bss_get_ie(bss, WLAN_EID_RSN)) &&
2048             wpa_key_mgmt_wpa(ssid->key_mgmt)) {
2049                 int try_opportunistic;
2050                 try_opportunistic = (ssid->proactive_key_caching < 0 ?
2051                                      wpa_s->conf->okc :
2052                                      ssid->proactive_key_caching) &&
2053                         (ssid->proto & WPA_PROTO_RSN);
2054                 if (pmksa_cache_set_current(wpa_s->wpa, NULL, bss->bssid,
2055                                             ssid, try_opportunistic) == 0)
2056                         eapol_sm_notify_pmkid_attempt(wpa_s->eapol);
2057                 wpa_ie_len = sizeof(wpa_ie);
2058                 if (wpa_supplicant_set_suites(wpa_s, bss, ssid,
2059                                               wpa_ie, &wpa_ie_len)) {
2060                         wpa_msg(wpa_s, MSG_WARNING, "WPA: Failed to set WPA "
2061                                 "key management and encryption suites");
2062                         wpas_connect_work_done(wpa_s);
2063                         return;
2064                 }
2065         } else if ((ssid->key_mgmt & WPA_KEY_MGMT_IEEE8021X_NO_WPA) && bss &&
2066                    wpa_key_mgmt_wpa_ieee8021x(ssid->key_mgmt)) {
2067                 /*
2068                  * Both WPA and non-WPA IEEE 802.1X enabled in configuration -
2069                  * use non-WPA since the scan results did not indicate that the
2070                  * AP is using WPA or WPA2.
2071                  */
2072                 wpa_supplicant_set_non_wpa_policy(wpa_s, ssid);
2073                 wpa_ie_len = 0;
2074                 wpa_s->wpa_proto = 0;
2075         } else if (wpa_key_mgmt_wpa_any(ssid->key_mgmt)) {
2076                 wpa_ie_len = sizeof(wpa_ie);
2077                 if (wpa_supplicant_set_suites(wpa_s, NULL, ssid,
2078                                               wpa_ie, &wpa_ie_len)) {
2079                         wpa_msg(wpa_s, MSG_WARNING, "WPA: Failed to set WPA "
2080                                 "key management and encryption suites (no "
2081                                 "scan results)");
2082                         wpas_connect_work_done(wpa_s);
2083                         return;
2084                 }
2085 #ifdef CONFIG_WPS
2086         } else if (ssid->key_mgmt & WPA_KEY_MGMT_WPS) {
2087                 struct wpabuf *wps_ie;
2088                 wps_ie = wps_build_assoc_req_ie(wpas_wps_get_req_type(ssid));
2089                 if (wps_ie && wpabuf_len(wps_ie) <= sizeof(wpa_ie)) {
2090                         wpa_ie_len = wpabuf_len(wps_ie);
2091                         os_memcpy(wpa_ie, wpabuf_head(wps_ie), wpa_ie_len);
2092                 } else
2093                         wpa_ie_len = 0;
2094                 wpabuf_free(wps_ie);
2095                 wpa_supplicant_set_non_wpa_policy(wpa_s, ssid);
2096                 if (!bss || (bss->caps & IEEE80211_CAP_PRIVACY))
2097                         params.wps = WPS_MODE_PRIVACY;
2098                 else
2099                         params.wps = WPS_MODE_OPEN;
2100                 wpa_s->wpa_proto = 0;
2101 #endif /* CONFIG_WPS */
2102         } else {
2103                 wpa_supplicant_set_non_wpa_policy(wpa_s, ssid);
2104                 wpa_ie_len = 0;
2105                 wpa_s->wpa_proto = 0;
2106         }
2107
2108 #ifdef CONFIG_P2P
2109         if (wpa_s->global->p2p) {
2110                 u8 *pos;
2111                 size_t len;
2112                 int res;
2113                 pos = wpa_ie + wpa_ie_len;
2114                 len = sizeof(wpa_ie) - wpa_ie_len;
2115                 res = wpas_p2p_assoc_req_ie(wpa_s, bss, pos, len,
2116                                             ssid->p2p_group);
2117                 if (res >= 0)
2118                         wpa_ie_len += res;
2119         }
2120
2121         wpa_s->cross_connect_disallowed = 0;
2122         if (bss) {
2123                 struct wpabuf *p2p;
2124                 p2p = wpa_bss_get_vendor_ie_multi(bss, P2P_IE_VENDOR_TYPE);
2125                 if (p2p) {
2126                         wpa_s->cross_connect_disallowed =
2127                                 p2p_get_cross_connect_disallowed(p2p);
2128                         wpabuf_free(p2p);
2129                         wpa_dbg(wpa_s, MSG_DEBUG, "P2P: WLAN AP %s cross "
2130                                 "connection",
2131                                 wpa_s->cross_connect_disallowed ?
2132                                 "disallows" : "allows");
2133                 }
2134         }
2135
2136         os_memset(wpa_s->p2p_ip_addr_info, 0, sizeof(wpa_s->p2p_ip_addr_info));
2137 #endif /* CONFIG_P2P */
2138
2139 #ifdef CONFIG_HS20
2140         if (is_hs20_network(wpa_s, ssid, bss)) {
2141                 struct wpabuf *hs20;
2142                 hs20 = wpabuf_alloc(20);
2143                 if (hs20) {
2144                         int pps_mo_id = hs20_get_pps_mo_id(wpa_s, ssid);
2145                         size_t len;
2146
2147                         wpas_hs20_add_indication(hs20, pps_mo_id);
2148                         len = sizeof(wpa_ie) - wpa_ie_len;
2149                         if (wpabuf_len(hs20) <= len) {
2150                                 os_memcpy(wpa_ie + wpa_ie_len,
2151                                           wpabuf_head(hs20), wpabuf_len(hs20));
2152                                 wpa_ie_len += wpabuf_len(hs20);
2153                         }
2154                         wpabuf_free(hs20);
2155                 }
2156         }
2157 #endif /* CONFIG_HS20 */
2158
2159         /*
2160          * Workaround: Add Extended Capabilities element only if the AP
2161          * included this element in Beacon/Probe Response frames. Some older
2162          * APs seem to have interoperability issues if this element is
2163          * included, so while the standard may require us to include the
2164          * element in all cases, it is justifiable to skip it to avoid
2165          * interoperability issues.
2166          */
2167         if (!bss || wpa_bss_get_ie(bss, WLAN_EID_EXT_CAPAB)) {
2168                 u8 ext_capab[18];
2169                 int ext_capab_len;
2170                 ext_capab_len = wpas_build_ext_capab(wpa_s, ext_capab,
2171                                                      sizeof(ext_capab));
2172                 if (ext_capab_len > 0) {
2173                         u8 *pos = wpa_ie;
2174                         if (wpa_ie_len > 0 && pos[0] == WLAN_EID_RSN)
2175                                 pos += 2 + pos[1];
2176                         os_memmove(pos + ext_capab_len, pos,
2177                                    wpa_ie_len - (pos - wpa_ie));
2178                         wpa_ie_len += ext_capab_len;
2179                         os_memcpy(pos, ext_capab, ext_capab_len);
2180                 }
2181         }
2182
2183         if (wpa_s->vendor_elem[VENDOR_ELEM_ASSOC_REQ]) {
2184                 struct wpabuf *buf = wpa_s->vendor_elem[VENDOR_ELEM_ASSOC_REQ];
2185                 size_t len;
2186
2187                 len = sizeof(wpa_ie) - wpa_ie_len;
2188                 if (wpabuf_len(buf) <= len) {
2189                         os_memcpy(wpa_ie + wpa_ie_len,
2190                                   wpabuf_head(buf), wpabuf_len(buf));
2191                         wpa_ie_len += wpabuf_len(buf);
2192                 }
2193         }
2194
2195 #ifdef CONFIG_FST
2196         if (wpa_s->fst_ies) {
2197                 int fst_ies_len = wpabuf_len(wpa_s->fst_ies);
2198
2199                 if (wpa_ie_len + fst_ies_len <= sizeof(wpa_ie)) {
2200                         os_memcpy(wpa_ie + wpa_ie_len,
2201                                   wpabuf_head(wpa_s->fst_ies), fst_ies_len);
2202                         wpa_ie_len += fst_ies_len;
2203                 }
2204         }
2205 #endif /* CONFIG_FST */
2206
2207         wpa_clear_keys(wpa_s, bss ? bss->bssid : NULL);
2208         use_crypt = 1;
2209         cipher_pairwise = wpa_s->pairwise_cipher;
2210         cipher_group = wpa_s->group_cipher;
2211         if (wpa_s->key_mgmt == WPA_KEY_MGMT_NONE ||
2212             wpa_s->key_mgmt == WPA_KEY_MGMT_IEEE8021X_NO_WPA) {
2213                 if (wpa_s->key_mgmt == WPA_KEY_MGMT_NONE)
2214                         use_crypt = 0;
2215                 if (wpa_set_wep_keys(wpa_s, ssid)) {
2216                         use_crypt = 1;
2217                         wep_keys_set = 1;
2218                 }
2219         }
2220         if (wpa_s->key_mgmt == WPA_KEY_MGMT_WPS)
2221                 use_crypt = 0;
2222
2223 #ifdef IEEE8021X_EAPOL
2224         if (wpa_s->key_mgmt == WPA_KEY_MGMT_IEEE8021X_NO_WPA) {
2225                 if ((ssid->eapol_flags &
2226                      (EAPOL_FLAG_REQUIRE_KEY_UNICAST |
2227                       EAPOL_FLAG_REQUIRE_KEY_BROADCAST)) == 0 &&
2228                     !wep_keys_set) {
2229                         use_crypt = 0;
2230                 } else {
2231                         /* Assume that dynamic WEP-104 keys will be used and
2232                          * set cipher suites in order for drivers to expect
2233                          * encryption. */
2234                         cipher_pairwise = cipher_group = WPA_CIPHER_WEP104;
2235                 }
2236         }
2237 #endif /* IEEE8021X_EAPOL */
2238
2239         if (wpa_s->key_mgmt == WPA_KEY_MGMT_WPA_NONE) {
2240                 /* Set the key before (and later after) association */
2241                 wpa_supplicant_set_wpa_none_key(wpa_s, ssid);
2242         }
2243
2244         wpa_supplicant_set_state(wpa_s, WPA_ASSOCIATING);
2245         if (bss) {
2246                 params.ssid = bss->ssid;
2247                 params.ssid_len = bss->ssid_len;
2248                 if (!wpas_driver_bss_selection(wpa_s) || ssid->bssid_set) {
2249                         wpa_printf(MSG_DEBUG, "Limit connection to BSSID "
2250                                    MACSTR " freq=%u MHz based on scan results "
2251                                    "(bssid_set=%d)",
2252                                    MAC2STR(bss->bssid), bss->freq,
2253                                    ssid->bssid_set);
2254                         params.bssid = bss->bssid;
2255                         params.freq.freq = bss->freq;
2256                 }
2257                 params.bssid_hint = bss->bssid;
2258                 params.freq_hint = bss->freq;
2259         } else {
2260                 params.ssid = ssid->ssid;
2261                 params.ssid_len = ssid->ssid_len;
2262         }
2263
2264         if (ssid->mode == WPAS_MODE_IBSS && ssid->bssid_set &&
2265             wpa_s->conf->ap_scan == 2) {
2266                 params.bssid = ssid->bssid;
2267                 params.fixed_bssid = 1;
2268         }
2269
2270         /* Initial frequency for IBSS/mesh */
2271         if ((ssid->mode == WPAS_MODE_IBSS || ssid->mode == WPAS_MODE_MESH) &&
2272             ssid->frequency > 0 && params.freq.freq == 0)
2273                 ibss_mesh_setup_freq(wpa_s, ssid, &params.freq);
2274
2275         if (ssid->mode == WPAS_MODE_IBSS) {
2276                 params.fixed_freq = ssid->fixed_freq;
2277                 if (ssid->beacon_int)
2278                         params.beacon_int = ssid->beacon_int;
2279                 else
2280                         params.beacon_int = wpa_s->conf->beacon_int;
2281         }
2282
2283         params.wpa_ie = wpa_ie;
2284         params.wpa_ie_len = wpa_ie_len;
2285         params.pairwise_suite = cipher_pairwise;
2286         params.group_suite = cipher_group;
2287         params.key_mgmt_suite = wpa_s->key_mgmt;
2288         params.wpa_proto = wpa_s->wpa_proto;
2289         params.auth_alg = algs;
2290         params.mode = ssid->mode;
2291         params.bg_scan_period = ssid->bg_scan_period;
2292         for (i = 0; i < NUM_WEP_KEYS; i++) {
2293                 if (ssid->wep_key_len[i])
2294                         params.wep_key[i] = ssid->wep_key[i];
2295                 params.wep_key_len[i] = ssid->wep_key_len[i];
2296         }
2297         params.wep_tx_keyidx = ssid->wep_tx_keyidx;
2298
2299         if ((wpa_s->drv_flags & WPA_DRIVER_FLAGS_4WAY_HANDSHAKE) &&
2300             (params.key_mgmt_suite == WPA_KEY_MGMT_PSK ||
2301              params.key_mgmt_suite == WPA_KEY_MGMT_FT_PSK)) {
2302                 params.passphrase = ssid->passphrase;
2303                 if (ssid->psk_set)
2304                         params.psk = ssid->psk;
2305         }
2306
2307         if (wpa_s->conf->key_mgmt_offload) {
2308                 if (params.key_mgmt_suite == WPA_KEY_MGMT_IEEE8021X ||
2309                     params.key_mgmt_suite == WPA_KEY_MGMT_IEEE8021X_SHA256 ||
2310                     params.key_mgmt_suite == WPA_KEY_MGMT_IEEE8021X_SUITE_B ||
2311                     params.key_mgmt_suite == WPA_KEY_MGMT_IEEE8021X_SUITE_B_192)
2312                         params.req_key_mgmt_offload =
2313                                 ssid->proactive_key_caching < 0 ?
2314                                 wpa_s->conf->okc : ssid->proactive_key_caching;
2315                 else
2316                         params.req_key_mgmt_offload = 1;
2317
2318                 if ((params.key_mgmt_suite == WPA_KEY_MGMT_PSK ||
2319                      params.key_mgmt_suite == WPA_KEY_MGMT_PSK_SHA256 ||
2320                      params.key_mgmt_suite == WPA_KEY_MGMT_FT_PSK) &&
2321                     ssid->psk_set)
2322                         params.psk = ssid->psk;
2323         }
2324
2325         params.drop_unencrypted = use_crypt;
2326
2327 #ifdef CONFIG_IEEE80211W
2328         params.mgmt_frame_protection = wpas_get_ssid_pmf(wpa_s, ssid);
2329         if (params.mgmt_frame_protection != NO_MGMT_FRAME_PROTECTION && bss) {
2330                 const u8 *rsn = wpa_bss_get_ie(bss, WLAN_EID_RSN);
2331                 struct wpa_ie_data ie;
2332                 if (rsn && wpa_parse_wpa_ie(rsn, 2 + rsn[1], &ie) == 0 &&
2333                     ie.capabilities &
2334                     (WPA_CAPABILITY_MFPC | WPA_CAPABILITY_MFPR)) {
2335                         wpa_dbg(wpa_s, MSG_DEBUG, "WPA: Selected AP supports "
2336                                 "MFP: require MFP");
2337                         params.mgmt_frame_protection =
2338                                 MGMT_FRAME_PROTECTION_REQUIRED;
2339                 }
2340         }
2341 #endif /* CONFIG_IEEE80211W */
2342
2343         params.p2p = ssid->p2p_group;
2344
2345         if (wpa_s->parent->set_sta_uapsd)
2346                 params.uapsd = wpa_s->parent->sta_uapsd;
2347         else
2348                 params.uapsd = -1;
2349
2350 #ifdef CONFIG_HT_OVERRIDES
2351         os_memset(&htcaps, 0, sizeof(htcaps));
2352         os_memset(&htcaps_mask, 0, sizeof(htcaps_mask));
2353         params.htcaps = (u8 *) &htcaps;
2354         params.htcaps_mask = (u8 *) &htcaps_mask;
2355         wpa_supplicant_apply_ht_overrides(wpa_s, ssid, &params);
2356 #endif /* CONFIG_HT_OVERRIDES */
2357 #ifdef CONFIG_VHT_OVERRIDES
2358         os_memset(&vhtcaps, 0, sizeof(vhtcaps));
2359         os_memset(&vhtcaps_mask, 0, sizeof(vhtcaps_mask));
2360         params.vhtcaps = &vhtcaps;
2361         params.vhtcaps_mask = &vhtcaps_mask;
2362         wpa_supplicant_apply_vht_overrides(wpa_s, ssid, &params);
2363 #endif /* CONFIG_VHT_OVERRIDES */
2364
2365 #ifdef CONFIG_P2P
2366         /*
2367          * If multi-channel concurrency is not supported, check for any
2368          * frequency conflict. In case of any frequency conflict, remove the
2369          * least prioritized connection.
2370          */
2371         if (wpa_s->num_multichan_concurrent < 2) {
2372                 int freq, num;
2373                 num = get_shared_radio_freqs(wpa_s, &freq, 1);
2374                 if (num > 0 && freq > 0 && freq != params.freq.freq) {
2375                         wpa_printf(MSG_DEBUG,
2376                                    "Assoc conflicting freq found (%d != %d)",
2377                                    freq, params.freq.freq);
2378                         if (wpas_p2p_handle_frequency_conflicts(
2379                                     wpa_s, params.freq.freq, ssid) < 0) {
2380                                 wpas_connect_work_done(wpa_s);
2381                                 return;
2382                         }
2383                 }
2384         }
2385 #endif /* CONFIG_P2P */
2386
2387         ret = wpa_drv_associate(wpa_s, &params);
2388         if (ret < 0) {
2389                 wpa_msg(wpa_s, MSG_INFO, "Association request to the driver "
2390                         "failed");
2391                 if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_SANE_ERROR_CODES) {
2392                         /*
2393                          * The driver is known to mean what is saying, so we
2394                          * can stop right here; the association will not
2395                          * succeed.
2396                          */
2397                         wpas_connection_failed(wpa_s, wpa_s->pending_bssid);
2398                         wpa_supplicant_set_state(wpa_s, WPA_DISCONNECTED);
2399                         os_memset(wpa_s->pending_bssid, 0, ETH_ALEN);
2400                         return;
2401                 }
2402                 /* try to continue anyway; new association will be tried again
2403                  * after timeout */
2404                 assoc_failed = 1;
2405         }
2406
2407         if (wpa_s->key_mgmt == WPA_KEY_MGMT_WPA_NONE) {
2408                 /* Set the key after the association just in case association
2409                  * cleared the previously configured key. */
2410                 wpa_supplicant_set_wpa_none_key(wpa_s, ssid);
2411                 /* No need to timeout authentication since there is no key
2412                  * management. */
2413                 wpa_supplicant_cancel_auth_timeout(wpa_s);
2414                 wpa_supplicant_set_state(wpa_s, WPA_COMPLETED);
2415 #ifdef CONFIG_IBSS_RSN
2416         } else if (ssid->mode == WPAS_MODE_IBSS &&
2417                    wpa_s->key_mgmt != WPA_KEY_MGMT_NONE &&
2418                    wpa_s->key_mgmt != WPA_KEY_MGMT_WPA_NONE) {
2419                 /*
2420                  * RSN IBSS authentication is per-STA and we can disable the
2421                  * per-BSSID authentication.
2422                  */
2423                 wpa_supplicant_cancel_auth_timeout(wpa_s);
2424 #endif /* CONFIG_IBSS_RSN */
2425         } else {
2426                 /* Timeout for IEEE 802.11 authentication and association */
2427                 int timeout = 60;
2428
2429                 if (assoc_failed) {
2430                         /* give IBSS a bit more time */
2431                         timeout = ssid->mode == WPAS_MODE_IBSS ? 10 : 5;
2432                 } else if (wpa_s->conf->ap_scan == 1) {
2433                         /* give IBSS a bit more time */
2434                         timeout = ssid->mode == WPAS_MODE_IBSS ? 20 : 10;
2435                 }
2436                 wpa_supplicant_req_auth_timeout(wpa_s, timeout, 0);
2437         }
2438
2439         if (wep_keys_set &&
2440             (wpa_s->drv_flags & WPA_DRIVER_FLAGS_SET_KEYS_AFTER_ASSOC)) {
2441                 /* Set static WEP keys again */
2442                 wpa_set_wep_keys(wpa_s, ssid);
2443         }
2444
2445         if (wpa_s->current_ssid && wpa_s->current_ssid != ssid) {
2446                 /*
2447                  * Do not allow EAP session resumption between different
2448                  * network configurations.
2449                  */
2450                 eapol_sm_invalidate_cached_session(wpa_s->eapol);
2451         }
2452         old_ssid = wpa_s->current_ssid;
2453         wpa_s->current_ssid = ssid;
2454         if (!wpas_driver_bss_selection(wpa_s) || ssid->bssid_set)
2455                 wpa_s->current_bss = bss;
2456         wpa_supplicant_rsn_supp_set_config(wpa_s, wpa_s->current_ssid);
2457         wpa_supplicant_initiate_eapol(wpa_s);
2458         if (old_ssid != wpa_s->current_ssid)
2459                 wpas_notify_network_changed(wpa_s);
2460 }
2461
2462
2463 static void wpa_supplicant_clear_connection(struct wpa_supplicant *wpa_s,
2464                                             const u8 *addr)
2465 {
2466         struct wpa_ssid *old_ssid;
2467
2468         wpas_connect_work_done(wpa_s);
2469         wpa_clear_keys(wpa_s, addr);
2470         old_ssid = wpa_s->current_ssid;
2471         wpa_supplicant_mark_disassoc(wpa_s);
2472         wpa_sm_set_config(wpa_s->wpa, NULL);
2473         eapol_sm_notify_config(wpa_s->eapol, NULL, NULL);
2474         if (old_ssid != wpa_s->current_ssid)
2475                 wpas_notify_network_changed(wpa_s);
2476         eloop_cancel_timeout(wpa_supplicant_timeout, wpa_s, NULL);
2477 }
2478
2479
2480 /**
2481  * wpa_supplicant_deauthenticate - Deauthenticate the current connection
2482  * @wpa_s: Pointer to wpa_supplicant data
2483  * @reason_code: IEEE 802.11 reason code for the deauthenticate frame
2484  *
2485  * This function is used to request %wpa_supplicant to deauthenticate from the
2486  * current AP.
2487  */
2488 void wpa_supplicant_deauthenticate(struct wpa_supplicant *wpa_s,
2489                                    int reason_code)
2490 {
2491         u8 *addr = NULL;
2492         union wpa_event_data event;
2493         int zero_addr = 0;
2494
2495         wpa_dbg(wpa_s, MSG_DEBUG, "Request to deauthenticate - bssid=" MACSTR
2496                 " pending_bssid=" MACSTR " reason=%d state=%s",
2497                 MAC2STR(wpa_s->bssid), MAC2STR(wpa_s->pending_bssid),
2498                 reason_code, wpa_supplicant_state_txt(wpa_s->wpa_state));
2499
2500         if (!is_zero_ether_addr(wpa_s->bssid))
2501                 addr = wpa_s->bssid;
2502         else if (!is_zero_ether_addr(wpa_s->pending_bssid) &&
2503                  (wpa_s->wpa_state == WPA_AUTHENTICATING ||
2504                   wpa_s->wpa_state == WPA_ASSOCIATING))
2505                 addr = wpa_s->pending_bssid;
2506         else if (wpa_s->wpa_state == WPA_ASSOCIATING) {
2507                 /*
2508                  * When using driver-based BSS selection, we may not know the
2509                  * BSSID with which we are currently trying to associate. We
2510                  * need to notify the driver of this disconnection even in such
2511                  * a case, so use the all zeros address here.
2512                  */
2513                 addr = wpa_s->bssid;
2514                 zero_addr = 1;
2515         }
2516
2517 #ifdef CONFIG_TDLS
2518         wpa_tdls_teardown_peers(wpa_s->wpa);
2519 #endif /* CONFIG_TDLS */
2520
2521 #ifdef CONFIG_MESH
2522         if (wpa_s->ifmsh) {
2523                 wpa_msg_ctrl(wpa_s, MSG_INFO, MESH_GROUP_REMOVED "%s",
2524                              wpa_s->ifname);
2525                 wpa_supplicant_leave_mesh(wpa_s);
2526         }
2527 #endif /* CONFIG_MESH */
2528
2529         if (addr) {
2530                 wpa_drv_deauthenticate(wpa_s, addr, reason_code);
2531                 os_memset(&event, 0, sizeof(event));
2532                 event.deauth_info.reason_code = (u16) reason_code;
2533                 event.deauth_info.locally_generated = 1;
2534                 wpa_supplicant_event(wpa_s, EVENT_DEAUTH, &event);
2535                 if (zero_addr)
2536                         addr = NULL;
2537         }
2538
2539         wpa_supplicant_clear_connection(wpa_s, addr);
2540 }
2541
2542 static void wpa_supplicant_enable_one_network(struct wpa_supplicant *wpa_s,
2543                                               struct wpa_ssid *ssid)
2544 {
2545         if (!ssid || !ssid->disabled || ssid->disabled == 2)
2546                 return;
2547
2548         ssid->disabled = 0;
2549         wpas_clear_temp_disabled(wpa_s, ssid, 1);
2550         wpas_notify_network_enabled_changed(wpa_s, ssid);
2551
2552         /*
2553          * Try to reassociate since there is no current configuration and a new
2554          * network was made available.
2555          */
2556         if (!wpa_s->current_ssid && !wpa_s->disconnected)
2557                 wpa_s->reassociate = 1;
2558 }
2559
2560
2561 /**
2562  * wpa_supplicant_enable_network - Mark a configured network as enabled
2563  * @wpa_s: wpa_supplicant structure for a network interface
2564  * @ssid: wpa_ssid structure for a configured network or %NULL
2565  *
2566  * Enables the specified network or all networks if no network specified.
2567  */
2568 void wpa_supplicant_enable_network(struct wpa_supplicant *wpa_s,
2569                                    struct wpa_ssid *ssid)
2570 {
2571         if (ssid == NULL) {
2572                 for (ssid = wpa_s->conf->ssid; ssid; ssid = ssid->next)
2573                         wpa_supplicant_enable_one_network(wpa_s, ssid);
2574         } else
2575                 wpa_supplicant_enable_one_network(wpa_s, ssid);
2576
2577         if (wpa_s->reassociate && !wpa_s->disconnected) {
2578                 if (wpa_s->sched_scanning) {
2579                         wpa_printf(MSG_DEBUG, "Stop ongoing sched_scan to add "
2580                                    "new network to scan filters");
2581                         wpa_supplicant_cancel_sched_scan(wpa_s);
2582                 }
2583
2584                 if (wpa_supplicant_fast_associate(wpa_s) != 1) {
2585                         wpa_s->scan_req = NORMAL_SCAN_REQ;
2586                         wpa_supplicant_req_scan(wpa_s, 0, 0);
2587                 }
2588         }
2589 }
2590
2591
2592 /**
2593  * wpa_supplicant_disable_network - Mark a configured network as disabled
2594  * @wpa_s: wpa_supplicant structure for a network interface
2595  * @ssid: wpa_ssid structure for a configured network or %NULL
2596  *
2597  * Disables the specified network or all networks if no network specified.
2598  */
2599 void wpa_supplicant_disable_network(struct wpa_supplicant *wpa_s,
2600                                     struct wpa_ssid *ssid)
2601 {
2602         struct wpa_ssid *other_ssid;
2603         int was_disabled;
2604
2605         if (ssid == NULL) {
2606                 if (wpa_s->sched_scanning)
2607                         wpa_supplicant_cancel_sched_scan(wpa_s);
2608
2609                 for (other_ssid = wpa_s->conf->ssid; other_ssid;
2610                      other_ssid = other_ssid->next) {
2611                         was_disabled = other_ssid->disabled;
2612                         if (was_disabled == 2)
2613                                 continue; /* do not change persistent P2P group
2614                                            * data */
2615
2616                         other_ssid->disabled = 1;
2617
2618                         if (was_disabled != other_ssid->disabled)
2619                                 wpas_notify_network_enabled_changed(
2620                                         wpa_s, other_ssid);
2621                 }
2622                 if (wpa_s->current_ssid)
2623                         wpa_supplicant_deauthenticate(
2624                                 wpa_s, WLAN_REASON_DEAUTH_LEAVING);
2625         } else if (ssid->disabled != 2) {
2626                 if (ssid == wpa_s->current_ssid)
2627                         wpa_supplicant_deauthenticate(
2628                                 wpa_s, WLAN_REASON_DEAUTH_LEAVING);
2629
2630                 was_disabled = ssid->disabled;
2631
2632                 ssid->disabled = 1;
2633
2634                 if (was_disabled != ssid->disabled) {
2635                         wpas_notify_network_enabled_changed(wpa_s, ssid);
2636                         if (wpa_s->sched_scanning) {
2637                                 wpa_printf(MSG_DEBUG, "Stop ongoing sched_scan "
2638                                            "to remove network from filters");
2639                                 wpa_supplicant_cancel_sched_scan(wpa_s);
2640                                 wpa_supplicant_req_scan(wpa_s, 0, 0);
2641                         }
2642                 }
2643         }
2644 }
2645
2646
2647 /**
2648  * wpa_supplicant_select_network - Attempt association with a network
2649  * @wpa_s: wpa_supplicant structure for a network interface
2650  * @ssid: wpa_ssid structure for a configured network or %NULL for any network
2651  */
2652 void wpa_supplicant_select_network(struct wpa_supplicant *wpa_s,
2653                                    struct wpa_ssid *ssid)
2654 {
2655
2656         struct wpa_ssid *other_ssid;
2657         int disconnected = 0;
2658
2659         if (ssid && ssid != wpa_s->current_ssid && wpa_s->current_ssid) {
2660                 if (wpa_s->wpa_state >= WPA_AUTHENTICATING)
2661                         wpa_s->own_disconnect_req = 1;
2662                 wpa_supplicant_deauthenticate(
2663                         wpa_s, WLAN_REASON_DEAUTH_LEAVING);
2664                 disconnected = 1;
2665         }
2666
2667         if (ssid)
2668                 wpas_clear_temp_disabled(wpa_s, ssid, 1);
2669
2670         /*
2671          * Mark all other networks disabled or mark all networks enabled if no
2672          * network specified.
2673          */
2674         for (other_ssid = wpa_s->conf->ssid; other_ssid;
2675              other_ssid = other_ssid->next) {
2676                 int was_disabled = other_ssid->disabled;
2677                 if (was_disabled == 2)
2678                         continue; /* do not change persistent P2P group data */
2679
2680                 other_ssid->disabled = ssid ? (ssid->id != other_ssid->id) : 0;
2681                 if (was_disabled && !other_ssid->disabled)
2682                         wpas_clear_temp_disabled(wpa_s, other_ssid, 0);
2683
2684                 if (was_disabled != other_ssid->disabled)
2685                         wpas_notify_network_enabled_changed(wpa_s, other_ssid);
2686         }
2687
2688         if (ssid && ssid == wpa_s->current_ssid && wpa_s->current_ssid) {
2689                 /* We are already associated with the selected network */
2690                 wpa_printf(MSG_DEBUG, "Already associated with the "
2691                            "selected network - do nothing");
2692                 return;
2693         }
2694
2695         if (ssid) {
2696                 wpa_s->current_ssid = ssid;
2697                 eapol_sm_notify_config(wpa_s->eapol, NULL, NULL);
2698                 wpa_s->connect_without_scan =
2699                         (ssid->mode == WPAS_MODE_MESH) ? ssid : NULL;
2700
2701                 /*
2702                  * Don't optimize next scan freqs since a new ESS has been
2703                  * selected.
2704                  */
2705                 os_free(wpa_s->next_scan_freqs);
2706                 wpa_s->next_scan_freqs = NULL;
2707         } else {
2708                 wpa_s->connect_without_scan = NULL;
2709         }
2710
2711         wpa_s->disconnected = 0;
2712         wpa_s->reassociate = 1;
2713
2714         if (wpa_s->connect_without_scan ||
2715             wpa_supplicant_fast_associate(wpa_s) != 1) {
2716                 wpa_s->scan_req = NORMAL_SCAN_REQ;
2717                 wpa_supplicant_req_scan(wpa_s, 0, disconnected ? 100000 : 0);
2718         }
2719
2720         if (ssid)
2721                 wpas_notify_network_selected(wpa_s, ssid);
2722 }
2723
2724
2725 /**
2726  * wpas_set_pkcs11_engine_and_module_path - Set PKCS #11 engine and module path
2727  * @wpa_s: wpa_supplicant structure for a network interface
2728  * @pkcs11_engine_path: PKCS #11 engine path or NULL
2729  * @pkcs11_module_path: PKCS #11 module path or NULL
2730  * Returns: 0 on success; -1 on failure
2731  *
2732  * Sets the PKCS #11 engine and module path. Both have to be NULL or a valid
2733  * path. If resetting the EAPOL state machine with the new PKCS #11 engine and
2734  * module path fails the paths will be reset to the default value (NULL).
2735  */
2736 int wpas_set_pkcs11_engine_and_module_path(struct wpa_supplicant *wpa_s,
2737                                            const char *pkcs11_engine_path,
2738                                            const char *pkcs11_module_path)
2739 {
2740         char *pkcs11_engine_path_copy = NULL;
2741         char *pkcs11_module_path_copy = NULL;
2742
2743         if (pkcs11_engine_path != NULL) {
2744                 pkcs11_engine_path_copy = os_strdup(pkcs11_engine_path);
2745                 if (pkcs11_engine_path_copy == NULL)
2746                         return -1;
2747         }
2748         if (pkcs11_module_path != NULL) {
2749                 pkcs11_module_path_copy = os_strdup(pkcs11_module_path);
2750                 if (pkcs11_module_path_copy == NULL) {
2751                         os_free(pkcs11_engine_path_copy);
2752                         return -1;
2753                 }
2754         }
2755
2756         os_free(wpa_s->conf->pkcs11_engine_path);
2757         os_free(wpa_s->conf->pkcs11_module_path);
2758         wpa_s->conf->pkcs11_engine_path = pkcs11_engine_path_copy;
2759         wpa_s->conf->pkcs11_module_path = pkcs11_module_path_copy;
2760
2761         wpa_sm_set_eapol(wpa_s->wpa, NULL);
2762         eapol_sm_deinit(wpa_s->eapol);
2763         wpa_s->eapol = NULL;
2764         if (wpa_supplicant_init_eapol(wpa_s)) {
2765                 /* Error -> Reset paths to the default value (NULL) once. */
2766                 if (pkcs11_engine_path != NULL && pkcs11_module_path != NULL)
2767                         wpas_set_pkcs11_engine_and_module_path(wpa_s, NULL,
2768                                                                NULL);
2769
2770                 return -1;
2771         }
2772         wpa_sm_set_eapol(wpa_s->wpa, wpa_s->eapol);
2773
2774         return 0;
2775 }
2776
2777
2778 /**
2779  * wpa_supplicant_set_ap_scan - Set AP scan mode for interface
2780  * @wpa_s: wpa_supplicant structure for a network interface
2781  * @ap_scan: AP scan mode
2782  * Returns: 0 if succeed or -1 if ap_scan has an invalid value
2783  *
2784  */
2785 int wpa_supplicant_set_ap_scan(struct wpa_supplicant *wpa_s, int ap_scan)
2786 {
2787
2788         int old_ap_scan;
2789
2790         if (ap_scan < 0 || ap_scan > 2)
2791                 return -1;
2792
2793 #ifdef ANDROID
2794         if (ap_scan == 2 && ap_scan != wpa_s->conf->ap_scan &&
2795             wpa_s->wpa_state >= WPA_ASSOCIATING &&
2796             wpa_s->wpa_state < WPA_COMPLETED) {
2797                 wpa_printf(MSG_ERROR, "ap_scan = %d (%d) rejected while "
2798                            "associating", wpa_s->conf->ap_scan, ap_scan);
2799                 return 0;
2800         }
2801 #endif /* ANDROID */
2802
2803         old_ap_scan = wpa_s->conf->ap_scan;
2804         wpa_s->conf->ap_scan = ap_scan;
2805
2806         if (old_ap_scan != wpa_s->conf->ap_scan)
2807                 wpas_notify_ap_scan_changed(wpa_s);
2808
2809         return 0;
2810 }
2811
2812
2813 /**
2814  * wpa_supplicant_set_bss_expiration_age - Set BSS entry expiration age
2815  * @wpa_s: wpa_supplicant structure for a network interface
2816  * @expire_age: Expiration age in seconds
2817  * Returns: 0 if succeed or -1 if expire_age has an invalid value
2818  *
2819  */
2820 int wpa_supplicant_set_bss_expiration_age(struct wpa_supplicant *wpa_s,
2821                                           unsigned int bss_expire_age)
2822 {
2823         if (bss_expire_age < 10) {
2824                 wpa_msg(wpa_s, MSG_ERROR, "Invalid bss expiration age %u",
2825                         bss_expire_age);
2826                 return -1;
2827         }
2828         wpa_msg(wpa_s, MSG_DEBUG, "Setting bss expiration age: %d sec",
2829                 bss_expire_age);
2830         wpa_s->conf->bss_expiration_age = bss_expire_age;
2831
2832         return 0;
2833 }
2834
2835
2836 /**
2837  * wpa_supplicant_set_bss_expiration_count - Set BSS entry expiration scan count
2838  * @wpa_s: wpa_supplicant structure for a network interface
2839  * @expire_count: number of scans after which an unseen BSS is reclaimed
2840  * Returns: 0 if succeed or -1 if expire_count has an invalid value
2841  *
2842  */
2843 int wpa_supplicant_set_bss_expiration_count(struct wpa_supplicant *wpa_s,
2844                                             unsigned int bss_expire_count)
2845 {
2846         if (bss_expire_count < 1) {
2847                 wpa_msg(wpa_s, MSG_ERROR, "Invalid bss expiration count %u",
2848                         bss_expire_count);
2849                 return -1;
2850         }
2851         wpa_msg(wpa_s, MSG_DEBUG, "Setting bss expiration scan count: %u",
2852                 bss_expire_count);
2853         wpa_s->conf->bss_expiration_scan_count = bss_expire_count;
2854
2855         return 0;
2856 }
2857
2858
2859 /**
2860  * wpa_supplicant_set_scan_interval - Set scan interval
2861  * @wpa_s: wpa_supplicant structure for a network interface
2862  * @scan_interval: scan interval in seconds
2863  * Returns: 0 if succeed or -1 if scan_interval has an invalid value
2864  *
2865  */
2866 int wpa_supplicant_set_scan_interval(struct wpa_supplicant *wpa_s,
2867                                      int scan_interval)
2868 {
2869         if (scan_interval < 0) {
2870                 wpa_msg(wpa_s, MSG_ERROR, "Invalid scan interval %d",
2871                         scan_interval);
2872                 return -1;
2873         }
2874         wpa_msg(wpa_s, MSG_DEBUG, "Setting scan interval: %d sec",
2875                 scan_interval);
2876         wpa_supplicant_update_scan_int(wpa_s, scan_interval);
2877
2878         return 0;
2879 }
2880
2881
2882 /**
2883  * wpa_supplicant_set_debug_params - Set global debug params
2884  * @global: wpa_global structure
2885  * @debug_level: debug level
2886  * @debug_timestamp: determines if show timestamp in debug data
2887  * @debug_show_keys: determines if show keys in debug data
2888  * Returns: 0 if succeed or -1 if debug_level has wrong value
2889  */
2890 int wpa_supplicant_set_debug_params(struct wpa_global *global, int debug_level,
2891                                     int debug_timestamp, int debug_show_keys)
2892 {
2893
2894         int old_level, old_timestamp, old_show_keys;
2895
2896         /* check for allowed debuglevels */
2897         if (debug_level != MSG_EXCESSIVE &&
2898             debug_level != MSG_MSGDUMP &&
2899             debug_level != MSG_DEBUG &&
2900             debug_level != MSG_INFO &&
2901             debug_level != MSG_WARNING &&
2902             debug_level != MSG_ERROR)
2903                 return -1;
2904
2905         old_level = wpa_debug_level;
2906         old_timestamp = wpa_debug_timestamp;
2907         old_show_keys = wpa_debug_show_keys;
2908
2909         wpa_debug_level = debug_level;
2910         wpa_debug_timestamp = debug_timestamp ? 1 : 0;
2911         wpa_debug_show_keys = debug_show_keys ? 1 : 0;
2912
2913         if (wpa_debug_level != old_level)
2914                 wpas_notify_debug_level_changed(global);
2915         if (wpa_debug_timestamp != old_timestamp)
2916                 wpas_notify_debug_timestamp_changed(global);
2917         if (wpa_debug_show_keys != old_show_keys)
2918                 wpas_notify_debug_show_keys_changed(global);
2919
2920         return 0;
2921 }
2922
2923
2924 /**
2925  * wpa_supplicant_get_ssid - Get a pointer to the current network structure
2926  * @wpa_s: Pointer to wpa_supplicant data
2927  * Returns: A pointer to the current network structure or %NULL on failure
2928  */
2929 struct wpa_ssid * wpa_supplicant_get_ssid(struct wpa_supplicant *wpa_s)
2930 {
2931         struct wpa_ssid *entry;
2932         u8 ssid[SSID_MAX_LEN];
2933         int res;
2934         size_t ssid_len;
2935         u8 bssid[ETH_ALEN];
2936         int wired;
2937
2938         res = wpa_drv_get_ssid(wpa_s, ssid);
2939         if (res < 0) {
2940                 wpa_msg(wpa_s, MSG_WARNING, "Could not read SSID from "
2941                         "driver");
2942                 return NULL;
2943         }
2944         ssid_len = res;
2945
2946         if (wpa_drv_get_bssid(wpa_s, bssid) < 0) {
2947                 wpa_msg(wpa_s, MSG_WARNING, "Could not read BSSID from "
2948                         "driver");
2949                 return NULL;
2950         }
2951
2952         wired = wpa_s->conf->ap_scan == 0 &&
2953                 (wpa_s->drv_flags & WPA_DRIVER_FLAGS_WIRED);
2954
2955         entry = wpa_s->conf->ssid;
2956         while (entry) {
2957                 if (!wpas_network_disabled(wpa_s, entry) &&
2958                     ((ssid_len == entry->ssid_len &&
2959                       os_memcmp(ssid, entry->ssid, ssid_len) == 0) || wired) &&
2960                     (!entry->bssid_set ||
2961                      os_memcmp(bssid, entry->bssid, ETH_ALEN) == 0))
2962                         return entry;
2963 #ifdef CONFIG_WPS
2964                 if (!wpas_network_disabled(wpa_s, entry) &&
2965                     (entry->key_mgmt & WPA_KEY_MGMT_WPS) &&
2966                     (entry->ssid == NULL || entry->ssid_len == 0) &&
2967                     (!entry->bssid_set ||
2968                      os_memcmp(bssid, entry->bssid, ETH_ALEN) == 0))
2969                         return entry;
2970 #endif /* CONFIG_WPS */
2971
2972                 if (!wpas_network_disabled(wpa_s, entry) && entry->bssid_set &&
2973                     entry->ssid_len == 0 &&
2974                     os_memcmp(bssid, entry->bssid, ETH_ALEN) == 0)
2975                         return entry;
2976
2977                 entry = entry->next;
2978         }
2979
2980         return NULL;
2981 }
2982
2983
2984 static int select_driver(struct wpa_supplicant *wpa_s, int i)
2985 {
2986         struct wpa_global *global = wpa_s->global;
2987
2988         if (wpa_drivers[i]->global_init && global->drv_priv[i] == NULL) {
2989                 global->drv_priv[i] = wpa_drivers[i]->global_init();
2990                 if (global->drv_priv[i] == NULL) {
2991                         wpa_printf(MSG_ERROR, "Failed to initialize driver "
2992                                    "'%s'", wpa_drivers[i]->name);
2993                         return -1;
2994                 }
2995         }
2996
2997         wpa_s->driver = wpa_drivers[i];
2998         wpa_s->global_drv_priv = global->drv_priv[i];
2999
3000         return 0;
3001 }
3002
3003
3004 static int wpa_supplicant_set_driver(struct wpa_supplicant *wpa_s,
3005                                      const char *name)
3006 {
3007         int i;
3008         size_t len;
3009         const char *pos, *driver = name;
3010
3011         if (wpa_s == NULL)
3012                 return -1;
3013
3014         if (wpa_drivers[0] == NULL) {
3015                 wpa_msg(wpa_s, MSG_ERROR, "No driver interfaces build into "
3016                         "wpa_supplicant");
3017                 return -1;
3018         }
3019
3020         if (name == NULL) {
3021                 /* default to first driver in the list */
3022                 return select_driver(wpa_s, 0);
3023         }
3024
3025         do {
3026                 pos = os_strchr(driver, ',');
3027                 if (pos)
3028                         len = pos - driver;
3029                 else
3030                         len = os_strlen(driver);
3031
3032                 for (i = 0; wpa_drivers[i]; i++) {
3033                         if (os_strlen(wpa_drivers[i]->name) == len &&
3034                             os_strncmp(driver, wpa_drivers[i]->name, len) ==
3035                             0) {
3036                                 /* First driver that succeeds wins */
3037                                 if (select_driver(wpa_s, i) == 0)
3038                                         return 0;
3039                         }
3040                 }
3041
3042                 driver = pos + 1;
3043         } while (pos);
3044
3045         wpa_msg(wpa_s, MSG_ERROR, "Unsupported driver '%s'", name);
3046         return -1;
3047 }
3048
3049
3050 /**
3051  * wpa_supplicant_rx_eapol - Deliver a received EAPOL frame to wpa_supplicant
3052  * @ctx: Context pointer (wpa_s); this is the ctx variable registered
3053  *      with struct wpa_driver_ops::init()
3054  * @src_addr: Source address of the EAPOL frame
3055  * @buf: EAPOL data starting from the EAPOL header (i.e., no Ethernet header)
3056  * @len: Length of the EAPOL data
3057  *
3058  * This function is called for each received EAPOL frame. Most driver
3059  * interfaces rely on more generic OS mechanism for receiving frames through
3060  * l2_packet, but if such a mechanism is not available, the driver wrapper may
3061  * take care of received EAPOL frames and deliver them to the core supplicant
3062  * code by calling this function.
3063  */
3064 void wpa_supplicant_rx_eapol(void *ctx, const u8 *src_addr,
3065                              const u8 *buf, size_t len)
3066 {
3067         struct wpa_supplicant *wpa_s = ctx;
3068
3069         wpa_dbg(wpa_s, MSG_DEBUG, "RX EAPOL from " MACSTR, MAC2STR(src_addr));
3070         wpa_hexdump(MSG_MSGDUMP, "RX EAPOL", buf, len);
3071
3072 #ifdef CONFIG_PEERKEY
3073         if (wpa_s->wpa_state > WPA_ASSOCIATED && wpa_s->current_ssid &&
3074             wpa_s->current_ssid->peerkey &&
3075             !(wpa_s->drv_flags & WPA_DRIVER_FLAGS_4WAY_HANDSHAKE) &&
3076             wpa_sm_rx_eapol_peerkey(wpa_s->wpa, src_addr, buf, len) == 1) {
3077                 wpa_dbg(wpa_s, MSG_DEBUG, "RSN: Processed PeerKey EAPOL-Key");
3078                 return;
3079         }
3080 #endif /* CONFIG_PEERKEY */
3081
3082         if (wpa_s->wpa_state < WPA_ASSOCIATED ||
3083             (wpa_s->last_eapol_matches_bssid &&
3084 #ifdef CONFIG_AP
3085              !wpa_s->ap_iface &&
3086 #endif /* CONFIG_AP */
3087              os_memcmp(src_addr, wpa_s->bssid, ETH_ALEN) != 0)) {
3088                 /*
3089                  * There is possible race condition between receiving the
3090                  * association event and the EAPOL frame since they are coming
3091                  * through different paths from the driver. In order to avoid
3092                  * issues in trying to process the EAPOL frame before receiving
3093                  * association information, lets queue it for processing until
3094                  * the association event is received. This may also be needed in
3095                  * driver-based roaming case, so also use src_addr != BSSID as a
3096                  * trigger if we have previously confirmed that the
3097                  * Authenticator uses BSSID as the src_addr (which is not the
3098                  * case with wired IEEE 802.1X).
3099                  */
3100                 wpa_dbg(wpa_s, MSG_DEBUG, "Not associated - Delay processing "
3101                         "of received EAPOL frame (state=%s bssid=" MACSTR ")",
3102                         wpa_supplicant_state_txt(wpa_s->wpa_state),
3103                         MAC2STR(wpa_s->bssid));
3104                 wpabuf_free(wpa_s->pending_eapol_rx);
3105                 wpa_s->pending_eapol_rx = wpabuf_alloc_copy(buf, len);
3106                 if (wpa_s->pending_eapol_rx) {
3107                         os_get_reltime(&wpa_s->pending_eapol_rx_time);
3108                         os_memcpy(wpa_s->pending_eapol_rx_src, src_addr,
3109                                   ETH_ALEN);
3110                 }
3111                 return;
3112         }
3113
3114         wpa_s->last_eapol_matches_bssid =
3115                 os_memcmp(src_addr, wpa_s->bssid, ETH_ALEN) == 0;
3116
3117 #ifdef CONFIG_AP
3118         if (wpa_s->ap_iface) {
3119                 wpa_supplicant_ap_rx_eapol(wpa_s, src_addr, buf, len);
3120                 return;
3121         }
3122 #endif /* CONFIG_AP */
3123
3124         if (wpa_s->key_mgmt == WPA_KEY_MGMT_NONE) {
3125                 wpa_dbg(wpa_s, MSG_DEBUG, "Ignored received EAPOL frame since "
3126                         "no key management is configured");
3127                 return;
3128         }
3129
3130         if (wpa_s->eapol_received == 0 &&
3131             (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_4WAY_HANDSHAKE) ||
3132              !wpa_key_mgmt_wpa_psk(wpa_s->key_mgmt) ||
3133              wpa_s->wpa_state != WPA_COMPLETED) &&
3134             (wpa_s->current_ssid == NULL ||
3135              wpa_s->current_ssid->mode != IEEE80211_MODE_IBSS)) {
3136                 /* Timeout for completing IEEE 802.1X and WPA authentication */
3137                 int timeout = 10;
3138
3139                 if (wpa_key_mgmt_wpa_ieee8021x(wpa_s->key_mgmt) ||
3140                     wpa_s->key_mgmt == WPA_KEY_MGMT_IEEE8021X_NO_WPA ||
3141                     wpa_s->key_mgmt == WPA_KEY_MGMT_WPS) {
3142                         /* Use longer timeout for IEEE 802.1X/EAP */
3143                         timeout = 70;
3144                 }
3145
3146 #ifdef CONFIG_WPS
3147                 if (wpa_s->current_ssid && wpa_s->current_bss &&
3148                     (wpa_s->current_ssid->key_mgmt & WPA_KEY_MGMT_WPS) &&
3149                     eap_is_wps_pin_enrollee(&wpa_s->current_ssid->eap)) {
3150                         /*
3151                          * Use shorter timeout if going through WPS AP iteration
3152                          * for PIN config method with an AP that does not
3153                          * advertise Selected Registrar.
3154                          */
3155                         struct wpabuf *wps_ie;
3156
3157                         wps_ie = wpa_bss_get_vendor_ie_multi(
3158                                 wpa_s->current_bss, WPS_IE_VENDOR_TYPE);
3159                         if (wps_ie &&
3160                             !wps_is_addr_authorized(wps_ie, wpa_s->own_addr, 1))
3161                                 timeout = 10;
3162                         wpabuf_free(wps_ie);
3163                 }
3164 #endif /* CONFIG_WPS */
3165
3166                 wpa_supplicant_req_auth_timeout(wpa_s, timeout, 0);
3167         }
3168         wpa_s->eapol_received++;
3169
3170         if (wpa_s->countermeasures) {
3171                 wpa_msg(wpa_s, MSG_INFO, "WPA: Countermeasures - dropped "
3172                         "EAPOL packet");
3173                 return;
3174         }
3175
3176 #ifdef CONFIG_IBSS_RSN
3177         if (wpa_s->current_ssid &&
3178             wpa_s->current_ssid->mode == WPAS_MODE_IBSS) {
3179                 ibss_rsn_rx_eapol(wpa_s->ibss_rsn, src_addr, buf, len);
3180                 return;
3181         }
3182 #endif /* CONFIG_IBSS_RSN */
3183
3184         /* Source address of the incoming EAPOL frame could be compared to the
3185          * current BSSID. However, it is possible that a centralized
3186          * Authenticator could be using another MAC address than the BSSID of
3187          * an AP, so just allow any address to be used for now. The replies are
3188          * still sent to the current BSSID (if available), though. */
3189
3190         os_memcpy(wpa_s->last_eapol_src, src_addr, ETH_ALEN);
3191         if (!wpa_key_mgmt_wpa_psk(wpa_s->key_mgmt) &&
3192             eapol_sm_rx_eapol(wpa_s->eapol, src_addr, buf, len) > 0)
3193                 return;
3194         wpa_drv_poll(wpa_s);
3195         if (!(wpa_s->drv_flags & WPA_DRIVER_FLAGS_4WAY_HANDSHAKE))
3196                 wpa_sm_rx_eapol(wpa_s->wpa, src_addr, buf, len);
3197         else if (wpa_key_mgmt_wpa_ieee8021x(wpa_s->key_mgmt)) {
3198                 /*
3199                  * Set portValid = TRUE here since we are going to skip 4-way
3200                  * handshake processing which would normally set portValid. We
3201                  * need this to allow the EAPOL state machines to be completed
3202                  * without going through EAPOL-Key handshake.
3203                  */
3204                 eapol_sm_notify_portValid(wpa_s->eapol, TRUE);
3205         }
3206 }
3207
3208
3209 int wpa_supplicant_update_mac_addr(struct wpa_supplicant *wpa_s)
3210 {
3211         if ((!wpa_s->p2p_mgmt ||
3212              !(wpa_s->drv_flags & WPA_DRIVER_FLAGS_DEDICATED_P2P_DEVICE)) &&
3213             !(wpa_s->drv_flags & WPA_DRIVER_FLAGS_P2P_DEDICATED_INTERFACE)) {
3214                 l2_packet_deinit(wpa_s->l2);
3215                 wpa_s->l2 = l2_packet_init(wpa_s->ifname,
3216                                            wpa_drv_get_mac_addr(wpa_s),
3217                                            ETH_P_EAPOL,
3218                                            wpa_supplicant_rx_eapol, wpa_s, 0);
3219                 if (wpa_s->l2 == NULL)
3220                         return -1;
3221         } else {
3222                 const u8 *addr = wpa_drv_get_mac_addr(wpa_s);
3223                 if (addr)
3224                         os_memcpy(wpa_s->own_addr, addr, ETH_ALEN);
3225         }
3226
3227         if (wpa_s->l2 && l2_packet_get_own_addr(wpa_s->l2, wpa_s->own_addr)) {
3228                 wpa_msg(wpa_s, MSG_ERROR, "Failed to get own L2 address");
3229                 return -1;
3230         }
3231
3232         wpa_sm_set_own_addr(wpa_s->wpa, wpa_s->own_addr);
3233
3234         return 0;
3235 }
3236
3237
3238 static void wpa_supplicant_rx_eapol_bridge(void *ctx, const u8 *src_addr,
3239                                            const u8 *buf, size_t len)
3240 {
3241         struct wpa_supplicant *wpa_s = ctx;
3242         const struct l2_ethhdr *eth;
3243
3244         if (len < sizeof(*eth))
3245                 return;
3246         eth = (const struct l2_ethhdr *) buf;
3247
3248         if (os_memcmp(eth->h_dest, wpa_s->own_addr, ETH_ALEN) != 0 &&
3249             !(eth->h_dest[0] & 0x01)) {
3250                 wpa_dbg(wpa_s, MSG_DEBUG, "RX EAPOL from " MACSTR " to " MACSTR
3251                         " (bridge - not for this interface - ignore)",
3252                         MAC2STR(src_addr), MAC2STR(eth->h_dest));
3253                 return;
3254         }
3255
3256         wpa_dbg(wpa_s, MSG_DEBUG, "RX EAPOL from " MACSTR " to " MACSTR
3257                 " (bridge)", MAC2STR(src_addr), MAC2STR(eth->h_dest));
3258         wpa_supplicant_rx_eapol(wpa_s, src_addr, buf + sizeof(*eth),
3259                                 len - sizeof(*eth));
3260 }
3261
3262
3263 /**
3264  * wpa_supplicant_driver_init - Initialize driver interface parameters
3265  * @wpa_s: Pointer to wpa_supplicant data
3266  * Returns: 0 on success, -1 on failure
3267  *
3268  * This function is called to initialize driver interface parameters.
3269  * wpa_drv_init() must have been called before this function to initialize the
3270  * driver interface.
3271  */
3272 int wpa_supplicant_driver_init(struct wpa_supplicant *wpa_s)
3273 {
3274         static int interface_count = 0;
3275
3276         if (wpa_supplicant_update_mac_addr(wpa_s) < 0)
3277                 return -1;
3278
3279         wpa_dbg(wpa_s, MSG_DEBUG, "Own MAC address: " MACSTR,
3280                 MAC2STR(wpa_s->own_addr));
3281         os_memcpy(wpa_s->perm_addr, wpa_s->own_addr, ETH_ALEN);
3282         wpa_sm_set_own_addr(wpa_s->wpa, wpa_s->own_addr);
3283
3284         if (wpa_s->bridge_ifname[0]) {
3285                 wpa_dbg(wpa_s, MSG_DEBUG, "Receiving packets from bridge "
3286                         "interface '%s'", wpa_s->bridge_ifname);
3287                 wpa_s->l2_br = l2_packet_init_bridge(
3288                         wpa_s->bridge_ifname, wpa_s->ifname, wpa_s->own_addr,
3289                         ETH_P_EAPOL, wpa_supplicant_rx_eapol_bridge, wpa_s, 1);
3290                 if (wpa_s->l2_br == NULL) {
3291                         wpa_msg(wpa_s, MSG_ERROR, "Failed to open l2_packet "
3292                                 "connection for the bridge interface '%s'",
3293                                 wpa_s->bridge_ifname);
3294                         return -1;
3295                 }
3296         }
3297
3298         wpa_clear_keys(wpa_s, NULL);
3299
3300         /* Make sure that TKIP countermeasures are not left enabled (could
3301          * happen if wpa_supplicant is killed during countermeasures. */
3302         wpa_drv_set_countermeasures(wpa_s, 0);
3303
3304         wpa_dbg(wpa_s, MSG_DEBUG, "RSN: flushing PMKID list in the driver");
3305         wpa_drv_flush_pmkid(wpa_s);
3306
3307         wpa_s->prev_scan_ssid = WILDCARD_SSID_SCAN;
3308         wpa_s->prev_scan_wildcard = 0;
3309
3310         if (wpa_supplicant_enabled_networks(wpa_s)) {
3311                 if (wpa_s->wpa_state == WPA_INTERFACE_DISABLED) {
3312                         wpa_supplicant_set_state(wpa_s, WPA_DISCONNECTED);
3313                         interface_count = 0;
3314                 }
3315 #ifndef ANDROID
3316                 if (!wpa_s->p2p_mgmt &&
3317                     wpa_supplicant_delayed_sched_scan(wpa_s,
3318                                                       interface_count % 3,
3319                                                       100000))
3320                         wpa_supplicant_req_scan(wpa_s, interface_count % 3,
3321                                                 100000);
3322 #endif /* ANDROID */
3323                 interface_count++;
3324         } else
3325                 wpa_supplicant_set_state(wpa_s, WPA_INACTIVE);
3326
3327         return 0;
3328 }
3329
3330
3331 static int wpa_supplicant_daemon(const char *pid_file)
3332 {
3333         wpa_printf(MSG_DEBUG, "Daemonize..");
3334         return os_daemonize(pid_file);
3335 }
3336
3337
3338 static struct wpa_supplicant *
3339 wpa_supplicant_alloc(struct wpa_supplicant *parent)
3340 {
3341         struct wpa_supplicant *wpa_s;
3342
3343         wpa_s = os_zalloc(sizeof(*wpa_s));
3344         if (wpa_s == NULL)
3345                 return NULL;
3346         wpa_s->scan_req = INITIAL_SCAN_REQ;
3347         wpa_s->scan_interval = 5;
3348         wpa_s->new_connection = 1;
3349         wpa_s->parent = parent ? parent : wpa_s;
3350         wpa_s->sched_scanning = 0;
3351
3352         return wpa_s;
3353 }
3354
3355
3356 #ifdef CONFIG_HT_OVERRIDES
3357
3358 static int wpa_set_htcap_mcs(struct wpa_supplicant *wpa_s,
3359                              struct ieee80211_ht_capabilities *htcaps,
3360                              struct ieee80211_ht_capabilities *htcaps_mask,
3361                              const char *ht_mcs)
3362 {
3363         /* parse ht_mcs into hex array */
3364         int i;
3365         const char *tmp = ht_mcs;
3366         char *end = NULL;
3367
3368         /* If ht_mcs is null, do not set anything */
3369         if (!ht_mcs)
3370                 return 0;
3371
3372         /* This is what we are setting in the kernel */
3373         os_memset(&htcaps->supported_mcs_set, 0, IEEE80211_HT_MCS_MASK_LEN);
3374
3375         wpa_msg(wpa_s, MSG_DEBUG, "set_htcap, ht_mcs -:%s:-", ht_mcs);
3376
3377         for (i = 0; i < IEEE80211_HT_MCS_MASK_LEN; i++) {
3378                 errno = 0;
3379                 long v = strtol(tmp, &end, 16);
3380                 if (errno == 0) {
3381                         wpa_msg(wpa_s, MSG_DEBUG,
3382                                 "htcap value[%i]: %ld end: %p  tmp: %p",
3383                                 i, v, end, tmp);
3384                         if (end == tmp)
3385                                 break;
3386
3387                         htcaps->supported_mcs_set[i] = v;
3388                         tmp = end;
3389                 } else {
3390                         wpa_msg(wpa_s, MSG_ERROR,
3391                                 "Failed to parse ht-mcs: %s, error: %s\n",
3392                                 ht_mcs, strerror(errno));
3393                         return -1;
3394                 }
3395         }
3396
3397         /*
3398          * If we were able to parse any values, then set mask for the MCS set.
3399          */
3400         if (i) {
3401                 os_memset(&htcaps_mask->supported_mcs_set, 0xff,
3402                           IEEE80211_HT_MCS_MASK_LEN - 1);
3403                 /* skip the 3 reserved bits */
3404                 htcaps_mask->supported_mcs_set[IEEE80211_HT_MCS_MASK_LEN - 1] =
3405                         0x1f;
3406         }
3407
3408         return 0;
3409 }
3410
3411
3412 static int wpa_disable_max_amsdu(struct wpa_supplicant *wpa_s,
3413                                  struct ieee80211_ht_capabilities *htcaps,
3414                                  struct ieee80211_ht_capabilities *htcaps_mask,
3415                                  int disabled)
3416 {
3417         le16 msk;
3418
3419         wpa_msg(wpa_s, MSG_DEBUG, "set_disable_max_amsdu: %d", disabled);
3420
3421         if (disabled == -1)
3422                 return 0;
3423
3424         msk = host_to_le16(HT_CAP_INFO_MAX_AMSDU_SIZE);
3425         htcaps_mask->ht_capabilities_info |= msk;
3426         if (disabled)
3427                 htcaps->ht_capabilities_info &= msk;
3428         else
3429                 htcaps->ht_capabilities_info |= msk;
3430
3431         return 0;
3432 }
3433
3434
3435 static int wpa_set_ampdu_factor(struct wpa_supplicant *wpa_s,
3436                                 struct ieee80211_ht_capabilities *htcaps,
3437                                 struct ieee80211_ht_capabilities *htcaps_mask,
3438                                 int factor)
3439 {
3440         wpa_msg(wpa_s, MSG_DEBUG, "set_ampdu_factor: %d", factor);
3441
3442         if (factor == -1)
3443                 return 0;
3444
3445         if (factor < 0 || factor > 3) {
3446                 wpa_msg(wpa_s, MSG_ERROR, "ampdu_factor: %d out of range. "
3447                         "Must be 0-3 or -1", factor);
3448                 return -EINVAL;
3449         }
3450
3451         htcaps_mask->a_mpdu_params |= 0x3; /* 2 bits for factor */
3452         htcaps->a_mpdu_params &= ~0x3;
3453         htcaps->a_mpdu_params |= factor & 0x3;
3454
3455         return 0;
3456 }
3457
3458
3459 static int wpa_set_ampdu_density(struct wpa_supplicant *wpa_s,
3460                                  struct ieee80211_ht_capabilities *htcaps,
3461                                  struct ieee80211_ht_capabilities *htcaps_mask,
3462                                  int density)
3463 {
3464         wpa_msg(wpa_s, MSG_DEBUG, "set_ampdu_density: %d", density);
3465
3466         if (density == -1)
3467                 return 0;
3468
3469         if (density < 0 || density > 7) {
3470                 wpa_msg(wpa_s, MSG_ERROR,
3471                         "ampdu_density: %d out of range. Must be 0-7 or -1.",
3472                         density);
3473                 return -EINVAL;
3474         }
3475
3476         htcaps_mask->a_mpdu_params |= 0x1C;
3477         htcaps->a_mpdu_params &= ~(0x1C);
3478         htcaps->a_mpdu_params |= (density << 2) & 0x1C;
3479
3480         return 0;
3481 }
3482
3483
3484 static int wpa_set_disable_ht40(struct wpa_supplicant *wpa_s,
3485                                 struct ieee80211_ht_capabilities *htcaps,
3486                                 struct ieee80211_ht_capabilities *htcaps_mask,
3487                                 int disabled)
3488 {
3489         /* Masking these out disables HT40 */
3490         le16 msk = host_to_le16(HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET |
3491                                 HT_CAP_INFO_SHORT_GI40MHZ);
3492
3493         wpa_msg(wpa_s, MSG_DEBUG, "set_disable_ht40: %d", disabled);
3494
3495         if (disabled)
3496                 htcaps->ht_capabilities_info &= ~msk;
3497         else
3498                 htcaps->ht_capabilities_info |= msk;
3499
3500         htcaps_mask->ht_capabilities_info |= msk;
3501
3502         return 0;
3503 }
3504
3505
3506 static int wpa_set_disable_sgi(struct wpa_supplicant *wpa_s,
3507                                struct ieee80211_ht_capabilities *htcaps,
3508                                struct ieee80211_ht_capabilities *htcaps_mask,
3509                                int disabled)
3510 {
3511         /* Masking these out disables SGI */
3512         le16 msk = host_to_le16(HT_CAP_INFO_SHORT_GI20MHZ |
3513                                 HT_CAP_INFO_SHORT_GI40MHZ);
3514
3515         wpa_msg(wpa_s, MSG_DEBUG, "set_disable_sgi: %d", disabled);
3516
3517         if (disabled)
3518                 htcaps->ht_capabilities_info &= ~msk;
3519         else
3520                 htcaps->ht_capabilities_info |= msk;
3521
3522         htcaps_mask->ht_capabilities_info |= msk;
3523
3524         return 0;
3525 }
3526
3527
3528 static int wpa_set_disable_ldpc(struct wpa_supplicant *wpa_s,
3529                                struct ieee80211_ht_capabilities *htcaps,
3530                                struct ieee80211_ht_capabilities *htcaps_mask,
3531                                int disabled)
3532 {
3533         /* Masking these out disables LDPC */
3534         le16 msk = host_to_le16(HT_CAP_INFO_LDPC_CODING_CAP);
3535
3536         wpa_msg(wpa_s, MSG_DEBUG, "set_disable_ldpc: %d", disabled);
3537
3538         if (disabled)
3539                 htcaps->ht_capabilities_info &= ~msk;
3540         else
3541                 htcaps->ht_capabilities_info |= msk;
3542
3543         htcaps_mask->ht_capabilities_info |= msk;
3544
3545         return 0;
3546 }
3547
3548
3549 void wpa_supplicant_apply_ht_overrides(
3550         struct wpa_supplicant *wpa_s, struct wpa_ssid *ssid,
3551         struct wpa_driver_associate_params *params)
3552 {
3553         struct ieee80211_ht_capabilities *htcaps;
3554         struct ieee80211_ht_capabilities *htcaps_mask;
3555
3556         if (!ssid)
3557                 return;
3558
3559         params->disable_ht = ssid->disable_ht;
3560         if (!params->htcaps || !params->htcaps_mask)
3561                 return;
3562
3563         htcaps = (struct ieee80211_ht_capabilities *) params->htcaps;
3564         htcaps_mask = (struct ieee80211_ht_capabilities *) params->htcaps_mask;
3565         wpa_set_htcap_mcs(wpa_s, htcaps, htcaps_mask, ssid->ht_mcs);
3566         wpa_disable_max_amsdu(wpa_s, htcaps, htcaps_mask,
3567                               ssid->disable_max_amsdu);
3568         wpa_set_ampdu_factor(wpa_s, htcaps, htcaps_mask, ssid->ampdu_factor);
3569         wpa_set_ampdu_density(wpa_s, htcaps, htcaps_mask, ssid->ampdu_density);
3570         wpa_set_disable_ht40(wpa_s, htcaps, htcaps_mask, ssid->disable_ht40);
3571         wpa_set_disable_sgi(wpa_s, htcaps, htcaps_mask, ssid->disable_sgi);
3572         wpa_set_disable_ldpc(wpa_s, htcaps, htcaps_mask, ssid->disable_ldpc);
3573
3574         if (ssid->ht40_intolerant) {
3575                 le16 bit = host_to_le16(HT_CAP_INFO_40MHZ_INTOLERANT);
3576                 htcaps->ht_capabilities_info |= bit;
3577                 htcaps_mask->ht_capabilities_info |= bit;
3578         }
3579 }
3580
3581 #endif /* CONFIG_HT_OVERRIDES */
3582
3583
3584 #ifdef CONFIG_VHT_OVERRIDES
3585 void wpa_supplicant_apply_vht_overrides(
3586         struct wpa_supplicant *wpa_s, struct wpa_ssid *ssid,
3587         struct wpa_driver_associate_params *params)
3588 {
3589         struct ieee80211_vht_capabilities *vhtcaps;
3590         struct ieee80211_vht_capabilities *vhtcaps_mask;
3591
3592         if (!ssid)
3593                 return;
3594
3595         params->disable_vht = ssid->disable_vht;
3596
3597         vhtcaps = (void *) params->vhtcaps;
3598         vhtcaps_mask = (void *) params->vhtcaps_mask;
3599
3600         if (!vhtcaps || !vhtcaps_mask)
3601                 return;
3602
3603         vhtcaps->vht_capabilities_info = ssid->vht_capa;
3604         vhtcaps_mask->vht_capabilities_info = ssid->vht_capa_mask;
3605
3606 #ifdef CONFIG_HT_OVERRIDES
3607         /* if max ampdu is <= 3, we have to make the HT cap the same */
3608         if (ssid->vht_capa_mask & VHT_CAP_MAX_A_MPDU_LENGTH_EXPONENT_MAX) {
3609                 int max_ampdu;
3610
3611                 max_ampdu = (ssid->vht_capa &
3612                              VHT_CAP_MAX_A_MPDU_LENGTH_EXPONENT_MAX) >>
3613                         VHT_CAP_MAX_A_MPDU_LENGTH_EXPONENT_MAX_SHIFT;
3614
3615                 max_ampdu = max_ampdu < 3 ? max_ampdu : 3;
3616                 wpa_set_ampdu_factor(wpa_s,
3617                                      (void *) params->htcaps,
3618                                      (void *) params->htcaps_mask,
3619                                      max_ampdu);
3620         }
3621 #endif /* CONFIG_HT_OVERRIDES */
3622
3623 #define OVERRIDE_MCS(i)                                                 \
3624         if (ssid->vht_tx_mcs_nss_ ##i >= 0) {                           \
3625                 vhtcaps_mask->vht_supported_mcs_set.tx_map |=           \
3626                         3 << 2 * (i - 1);                               \
3627                 vhtcaps->vht_supported_mcs_set.tx_map |=                \
3628                         ssid->vht_tx_mcs_nss_ ##i << 2 * (i - 1);       \
3629         }                                                               \
3630         if (ssid->vht_rx_mcs_nss_ ##i >= 0) {                           \
3631                 vhtcaps_mask->vht_supported_mcs_set.rx_map |=           \
3632                         3 << 2 * (i - 1);                               \
3633                 vhtcaps->vht_supported_mcs_set.rx_map |=                \
3634                         ssid->vht_rx_mcs_nss_ ##i << 2 * (i - 1);       \
3635         }
3636
3637         OVERRIDE_MCS(1);
3638         OVERRIDE_MCS(2);
3639         OVERRIDE_MCS(3);
3640         OVERRIDE_MCS(4);
3641         OVERRIDE_MCS(5);
3642         OVERRIDE_MCS(6);
3643         OVERRIDE_MCS(7);
3644         OVERRIDE_MCS(8);
3645 }
3646 #endif /* CONFIG_VHT_OVERRIDES */
3647
3648
3649 static int pcsc_reader_init(struct wpa_supplicant *wpa_s)
3650 {
3651 #ifdef PCSC_FUNCS
3652         size_t len;
3653
3654         if (!wpa_s->conf->pcsc_reader)
3655                 return 0;
3656
3657         wpa_s->scard = scard_init(wpa_s->conf->pcsc_reader);
3658         if (!wpa_s->scard)
3659                 return 1;
3660
3661         if (wpa_s->conf->pcsc_pin &&
3662             scard_set_pin(wpa_s->scard, wpa_s->conf->pcsc_pin) < 0) {
3663                 scard_deinit(wpa_s->scard);
3664                 wpa_s->scard = NULL;
3665                 wpa_msg(wpa_s, MSG_ERROR, "PC/SC PIN validation failed");
3666                 return -1;
3667         }
3668
3669         len = sizeof(wpa_s->imsi) - 1;
3670         if (scard_get_imsi(wpa_s->scard, wpa_s->imsi, &len)) {
3671                 scard_deinit(wpa_s->scard);
3672                 wpa_s->scard = NULL;
3673                 wpa_msg(wpa_s, MSG_ERROR, "Could not read IMSI");
3674                 return -1;
3675         }
3676         wpa_s->imsi[len] = '\0';
3677
3678         wpa_s->mnc_len = scard_get_mnc_len(wpa_s->scard);
3679
3680         wpa_printf(MSG_DEBUG, "SCARD: IMSI %s (MNC length %d)",
3681                    wpa_s->imsi, wpa_s->mnc_len);
3682
3683         wpa_sm_set_scard_ctx(wpa_s->wpa, wpa_s->scard);
3684         eapol_sm_register_scard_ctx(wpa_s->eapol, wpa_s->scard);
3685 #endif /* PCSC_FUNCS */
3686
3687         return 0;
3688 }
3689
3690
3691 int wpas_init_ext_pw(struct wpa_supplicant *wpa_s)
3692 {
3693         char *val, *pos;
3694
3695         ext_password_deinit(wpa_s->ext_pw);
3696         wpa_s->ext_pw = NULL;
3697         eapol_sm_set_ext_pw_ctx(wpa_s->eapol, NULL);
3698
3699         if (!wpa_s->conf->ext_password_backend)
3700                 return 0;
3701
3702         val = os_strdup(wpa_s->conf->ext_password_backend);
3703         if (val == NULL)
3704                 return -1;
3705         pos = os_strchr(val, ':');
3706         if (pos)
3707                 *pos++ = '\0';
3708
3709         wpa_printf(MSG_DEBUG, "EXT PW: Initialize backend '%s'", val);
3710
3711         wpa_s->ext_pw = ext_password_init(val, pos);
3712         os_free(val);
3713         if (wpa_s->ext_pw == NULL) {
3714                 wpa_printf(MSG_DEBUG, "EXT PW: Failed to initialize backend");
3715                 return -1;
3716         }
3717         eapol_sm_set_ext_pw_ctx(wpa_s->eapol, wpa_s->ext_pw);
3718
3719         return 0;
3720 }
3721
3722
3723 #ifdef CONFIG_FST
3724
3725 static const u8 * wpas_fst_get_bssid_cb(void *ctx)
3726 {
3727         struct wpa_supplicant *wpa_s = ctx;
3728
3729         return (is_zero_ether_addr(wpa_s->bssid) ||
3730                 wpa_s->wpa_state != WPA_COMPLETED) ? NULL : wpa_s->bssid;
3731 }
3732
3733
3734 static void wpas_fst_get_channel_info_cb(void *ctx,
3735                                          enum hostapd_hw_mode *hw_mode,
3736                                          u8 *channel)
3737 {
3738         struct wpa_supplicant *wpa_s = ctx;
3739
3740         if (wpa_s->current_bss) {
3741                 *hw_mode = ieee80211_freq_to_chan(wpa_s->current_bss->freq,
3742                                                   channel);
3743         } else if (wpa_s->hw.num_modes) {
3744                 *hw_mode = wpa_s->hw.modes[0].mode;
3745         } else {
3746                 WPA_ASSERT(0);
3747                 *hw_mode = 0;
3748         }
3749 }
3750
3751
3752 static int wpas_fst_get_hw_modes(void *ctx, struct hostapd_hw_modes **modes)
3753 {
3754         struct wpa_supplicant *wpa_s = ctx;
3755
3756         *modes = wpa_s->hw.modes;
3757         return wpa_s->hw.num_modes;
3758 }
3759
3760
3761 static void wpas_fst_set_ies_cb(void *ctx, const struct wpabuf *fst_ies)
3762 {
3763         struct wpa_supplicant *wpa_s = ctx;
3764
3765         wpa_hexdump_buf(MSG_DEBUG, "FST: Set IEs", fst_ies);
3766         wpa_s->fst_ies = fst_ies;
3767 }
3768
3769
3770 static int wpas_fst_send_action_cb(void *ctx, const u8 *da, struct wpabuf *data)
3771 {
3772         struct wpa_supplicant *wpa_s = ctx;
3773
3774         WPA_ASSERT(os_memcmp(wpa_s->bssid, da, ETH_ALEN) == 0);
3775         return wpa_drv_send_action(wpa_s, wpa_s->assoc_freq, 0, wpa_s->bssid,
3776                                           wpa_s->own_addr, wpa_s->bssid,
3777                                           wpabuf_head(data), wpabuf_len(data),
3778                                    0);
3779 }
3780
3781
3782 static const struct wpabuf * wpas_fst_get_mb_ie_cb(void *ctx, const u8 *addr)
3783 {
3784         struct wpa_supplicant *wpa_s = ctx;
3785
3786         WPA_ASSERT(os_memcmp(wpa_s->bssid, addr, ETH_ALEN) == 0);
3787         return wpa_s->received_mb_ies;
3788 }
3789
3790
3791 static void wpas_fst_update_mb_ie_cb(void *ctx, const u8 *addr,
3792                                      const u8 *buf, size_t size)
3793 {
3794         struct wpa_supplicant *wpa_s = ctx;
3795         struct mb_ies_info info;
3796
3797         WPA_ASSERT(os_memcmp(wpa_s->bssid, addr, ETH_ALEN) == 0);
3798
3799         if (!mb_ies_info_by_ies(&info, buf, size)) {
3800                 wpabuf_free(wpa_s->received_mb_ies);
3801                 wpa_s->received_mb_ies = mb_ies_by_info(&info);
3802         }
3803 }
3804
3805
3806 const u8 * wpas_fst_get_peer_first(void *ctx, struct fst_get_peer_ctx **get_ctx,
3807                                    Boolean mb_only)
3808 {
3809         struct wpa_supplicant *wpa_s = ctx;
3810
3811         *get_ctx = NULL;
3812         if (!is_zero_ether_addr(wpa_s->bssid))
3813                 return (wpa_s->received_mb_ies || !mb_only) ?
3814                         wpa_s->bssid : NULL;
3815         return NULL;
3816 }
3817
3818
3819 const u8 * wpas_fst_get_peer_next(void *ctx, struct fst_get_peer_ctx **get_ctx,
3820                                   Boolean mb_only)
3821 {
3822         return NULL;
3823 }
3824
3825 void fst_wpa_supplicant_fill_iface_obj(struct wpa_supplicant *wpa_s,
3826                                        struct fst_wpa_obj *iface_obj)
3827 {
3828         iface_obj->ctx              = wpa_s;
3829         iface_obj->get_bssid        = wpas_fst_get_bssid_cb;
3830         iface_obj->get_channel_info = wpas_fst_get_channel_info_cb;
3831         iface_obj->get_hw_modes     = wpas_fst_get_hw_modes;
3832         iface_obj->set_ies          = wpas_fst_set_ies_cb;
3833         iface_obj->send_action      = wpas_fst_send_action_cb;
3834         iface_obj->get_mb_ie        = wpas_fst_get_mb_ie_cb;
3835         iface_obj->update_mb_ie     = wpas_fst_update_mb_ie_cb;
3836         iface_obj->get_peer_first   = wpas_fst_get_peer_first;
3837         iface_obj->get_peer_next    = wpas_fst_get_peer_next;
3838 }
3839 #endif /* CONFIG_FST */
3840
3841 static int wpas_set_wowlan_triggers(struct wpa_supplicant *wpa_s,
3842                                     const struct wpa_driver_capa *capa)
3843 {
3844         struct wowlan_triggers *triggers;
3845         int ret = 0;
3846
3847         if (!wpa_s->conf->wowlan_triggers)
3848                 return 0;
3849
3850         triggers = wpa_get_wowlan_triggers(wpa_s->conf->wowlan_triggers, capa);
3851         if (triggers) {
3852                 ret = wpa_drv_wowlan(wpa_s, triggers);
3853                 os_free(triggers);
3854         }
3855         return ret;
3856 }
3857
3858
3859 static struct wpa_radio * radio_add_interface(struct wpa_supplicant *wpa_s,
3860                                               const char *rn)
3861 {
3862         struct wpa_supplicant *iface = wpa_s->global->ifaces;
3863         struct wpa_radio *radio;
3864
3865         while (rn && iface) {
3866                 radio = iface->radio;
3867                 if (radio && os_strcmp(rn, radio->name) == 0) {
3868                         wpa_printf(MSG_DEBUG, "Add interface %s to existing radio %s",
3869                                    wpa_s->ifname, rn);
3870                         dl_list_add(&radio->ifaces, &wpa_s->radio_list);
3871                         return radio;
3872                 }
3873
3874                 iface = iface->next;
3875         }
3876
3877         wpa_printf(MSG_DEBUG, "Add interface %s to a new radio %s",
3878                    wpa_s->ifname, rn ? rn : "N/A");
3879         radio = os_zalloc(sizeof(*radio));
3880         if (radio == NULL)
3881                 return NULL;
3882
3883         if (rn)
3884                 os_strlcpy(radio->name, rn, sizeof(radio->name));
3885         dl_list_init(&radio->ifaces);
3886         dl_list_init(&radio->work);
3887         dl_list_add(&radio->ifaces, &wpa_s->radio_list);
3888
3889         return radio;
3890 }
3891
3892
3893 static void radio_work_free(struct wpa_radio_work *work)
3894 {
3895         if (work->wpa_s->scan_work == work) {
3896                 /* This should not really happen. */
3897                 wpa_dbg(work->wpa_s, MSG_INFO, "Freeing radio work '%s'@%p (started=%d) that is marked as scan_work",
3898                         work->type, work, work->started);
3899                 work->wpa_s->scan_work = NULL;
3900         }
3901
3902 #ifdef CONFIG_P2P
3903         if (work->wpa_s->p2p_scan_work == work) {
3904                 /* This should not really happen. */
3905                 wpa_dbg(work->wpa_s, MSG_INFO, "Freeing radio work '%s'@%p (started=%d) that is marked as p2p_scan_work",
3906                         work->type, work, work->started);
3907                 work->wpa_s->p2p_scan_work = NULL;
3908         }
3909 #endif /* CONFIG_P2P */
3910
3911         dl_list_del(&work->list);
3912         os_free(work);
3913 }
3914
3915
3916 static void radio_start_next_work(void *eloop_ctx, void *timeout_ctx)
3917 {
3918         struct wpa_radio *radio = eloop_ctx;
3919         struct wpa_radio_work *work;
3920         struct os_reltime now, diff;
3921         struct wpa_supplicant *wpa_s;
3922
3923         work = dl_list_first(&radio->work, struct wpa_radio_work, list);
3924         if (work == NULL)
3925                 return;
3926
3927         if (work->started)
3928                 return; /* already started and still in progress */
3929
3930         wpa_s = dl_list_first(&radio->ifaces, struct wpa_supplicant,
3931                               radio_list);
3932         if (wpa_s && wpa_s->radio->external_scan_running) {
3933                 wpa_printf(MSG_DEBUG, "Delay radio work start until externally triggered scan completes");
3934                 return;
3935         }
3936
3937         os_get_reltime(&now);
3938         os_reltime_sub(&now, &work->time, &diff);
3939         wpa_dbg(work->wpa_s, MSG_DEBUG, "Starting radio work '%s'@%p after %ld.%06ld second wait",
3940                 work->type, work, diff.sec, diff.usec);
3941         work->started = 1;
3942         work->time = now;
3943         work->cb(work, 0);
3944 }
3945
3946
3947 /*
3948  * This function removes both started and pending radio works running on
3949  * the provided interface's radio.
3950  * Prior to the removal of the radio work, its callback (cb) is called with
3951  * deinit set to be 1. Each work's callback is responsible for clearing its
3952  * internal data and restoring to a correct state.
3953  * @wpa_s: wpa_supplicant data
3954  * @type: type of works to be removed
3955  * @remove_all: 1 to remove all the works on this radio, 0 to remove only
3956  * this interface's works.
3957  */
3958 void radio_remove_works(struct wpa_supplicant *wpa_s,
3959                         const char *type, int remove_all)
3960 {
3961         struct wpa_radio_work *work, *tmp;
3962         struct wpa_radio *radio = wpa_s->radio;
3963
3964         dl_list_for_each_safe(work, tmp, &radio->work, struct wpa_radio_work,
3965                               list) {
3966                 if (type && os_strcmp(type, work->type) != 0)
3967                         continue;
3968
3969                 /* skip other ifaces' works */
3970                 if (!remove_all && work->wpa_s != wpa_s)
3971                         continue;
3972
3973                 wpa_dbg(wpa_s, MSG_DEBUG, "Remove radio work '%s'@%p%s",
3974                         work->type, work, work->started ? " (started)" : "");
3975                 work->cb(work, 1);
3976                 radio_work_free(work);
3977         }
3978
3979         /* in case we removed the started work */
3980         radio_work_check_next(wpa_s);
3981 }
3982
3983
3984 static void radio_remove_interface(struct wpa_supplicant *wpa_s)
3985 {
3986         struct wpa_radio *radio = wpa_s->radio;
3987
3988         if (!radio)
3989                 return;
3990
3991         wpa_printf(MSG_DEBUG, "Remove interface %s from radio %s",
3992                    wpa_s->ifname, radio->name);
3993         dl_list_del(&wpa_s->radio_list);
3994         radio_remove_works(wpa_s, NULL, 0);
3995         wpa_s->radio = NULL;
3996         if (!dl_list_empty(&radio->ifaces))
3997                 return; /* Interfaces remain for this radio */
3998
3999         wpa_printf(MSG_DEBUG, "Remove radio %s", radio->name);
4000         eloop_cancel_timeout(radio_start_next_work, radio, NULL);
4001         os_free(radio);
4002 }
4003
4004
4005 void radio_work_check_next(struct wpa_supplicant *wpa_s)
4006 {
4007         struct wpa_radio *radio = wpa_s->radio;
4008
4009         if (dl_list_empty(&radio->work))
4010                 return;
4011         if (wpa_s->ext_work_in_progress) {
4012                 wpa_printf(MSG_DEBUG,
4013                            "External radio work in progress - delay start of pending item");
4014                 return;
4015         }
4016         eloop_cancel_timeout(radio_start_next_work, radio, NULL);
4017         eloop_register_timeout(0, 0, radio_start_next_work, radio, NULL);
4018 }
4019
4020
4021 /**
4022  * radio_add_work - Add a radio work item
4023  * @wpa_s: Pointer to wpa_supplicant data
4024  * @freq: Frequency of the offchannel operation in MHz or 0
4025  * @type: Unique identifier for each type of work
4026  * @next: Force as the next work to be executed
4027  * @cb: Callback function for indicating when radio is available
4028  * @ctx: Context pointer for the work (work->ctx in cb())
4029  * Returns: 0 on success, -1 on failure
4030  *
4031  * This function is used to request time for an operation that requires
4032  * exclusive radio control. Once the radio is available, the registered callback
4033  * function will be called. radio_work_done() must be called once the exclusive
4034  * radio operation has been completed, so that the radio is freed for other
4035  * operations. The special case of deinit=1 is used to free the context data
4036  * during interface removal. That does not allow the callback function to start
4037  * the radio operation, i.e., it must free any resources allocated for the radio
4038  * work and return.
4039  *
4040  * The @freq parameter can be used to indicate a single channel on which the
4041  * offchannel operation will occur. This may allow multiple radio work
4042  * operations to be performed in parallel if they apply for the same channel.
4043  * Setting this to 0 indicates that the work item may use multiple channels or
4044  * requires exclusive control of the radio.
4045  */
4046 int radio_add_work(struct wpa_supplicant *wpa_s, unsigned int freq,
4047                    const char *type, int next,
4048                    void (*cb)(struct wpa_radio_work *work, int deinit),
4049                    void *ctx)
4050 {
4051         struct wpa_radio_work *work;
4052         int was_empty;
4053
4054         work = os_zalloc(sizeof(*work));
4055         if (work == NULL)
4056                 return -1;
4057         wpa_dbg(wpa_s, MSG_DEBUG, "Add radio work '%s'@%p", type, work);
4058         os_get_reltime(&work->time);
4059         work->freq = freq;
4060         work->type = type;
4061         work->wpa_s = wpa_s;
4062         work->cb = cb;
4063         work->ctx = ctx;
4064
4065         was_empty = dl_list_empty(&wpa_s->radio->work);
4066         if (next)
4067                 dl_list_add(&wpa_s->radio->work, &work->list);
4068         else
4069                 dl_list_add_tail(&wpa_s->radio->work, &work->list);
4070         if (was_empty) {
4071                 wpa_dbg(wpa_s, MSG_DEBUG, "First radio work item in the queue - schedule start immediately");
4072                 radio_work_check_next(wpa_s);
4073         }
4074
4075         return 0;
4076 }
4077
4078
4079 /**
4080  * radio_work_done - Indicate that a radio work item has been completed
4081  * @work: Completed work
4082  *
4083  * This function is called once the callback function registered with
4084  * radio_add_work() has completed its work.
4085  */
4086 void radio_work_done(struct wpa_radio_work *work)
4087 {
4088         struct wpa_supplicant *wpa_s = work->wpa_s;
4089         struct os_reltime now, diff;
4090         unsigned int started = work->started;
4091
4092         os_get_reltime(&now);
4093         os_reltime_sub(&now, &work->time, &diff);
4094         wpa_dbg(wpa_s, MSG_DEBUG, "Radio work '%s'@%p %s in %ld.%06ld seconds",
4095                 work->type, work, started ? "done" : "canceled",
4096                 diff.sec, diff.usec);
4097         radio_work_free(work);
4098         if (started)
4099                 radio_work_check_next(wpa_s);
4100 }
4101
4102
4103 struct wpa_radio_work *
4104 radio_work_pending(struct wpa_supplicant *wpa_s, const char *type)
4105 {
4106         struct wpa_radio_work *work;
4107         struct wpa_radio *radio = wpa_s->radio;
4108
4109         dl_list_for_each(work, &radio->work, struct wpa_radio_work, list) {
4110                 if (work->wpa_s == wpa_s && os_strcmp(work->type, type) == 0)
4111                         return work;
4112         }
4113
4114         return NULL;
4115 }
4116
4117
4118 static int wpas_init_driver(struct wpa_supplicant *wpa_s,
4119                             struct wpa_interface *iface)
4120 {
4121         const char *ifname, *driver, *rn;
4122
4123         driver = iface->driver;
4124 next_driver:
4125         if (wpa_supplicant_set_driver(wpa_s, driver) < 0)
4126                 return -1;
4127
4128         wpa_s->drv_priv = wpa_drv_init(wpa_s, wpa_s->ifname);
4129         if (wpa_s->drv_priv == NULL) {
4130                 const char *pos;
4131                 pos = driver ? os_strchr(driver, ',') : NULL;
4132                 if (pos) {
4133                         wpa_dbg(wpa_s, MSG_DEBUG, "Failed to initialize "
4134                                 "driver interface - try next driver wrapper");
4135                         driver = pos + 1;
4136                         goto next_driver;
4137                 }
4138                 wpa_msg(wpa_s, MSG_ERROR, "Failed to initialize driver "
4139                         "interface");
4140                 return -1;
4141         }
4142         if (wpa_drv_set_param(wpa_s, wpa_s->conf->driver_param) < 0) {
4143                 wpa_msg(wpa_s, MSG_ERROR, "Driver interface rejected "
4144                         "driver_param '%s'", wpa_s->conf->driver_param);
4145                 return -1;
4146         }
4147
4148         ifname = wpa_drv_get_ifname(wpa_s);
4149         if (ifname && os_strcmp(ifname, wpa_s->ifname) != 0) {
4150                 wpa_dbg(wpa_s, MSG_DEBUG, "Driver interface replaced "
4151                         "interface name with '%s'", ifname);
4152                 os_strlcpy(wpa_s->ifname, ifname, sizeof(wpa_s->ifname));
4153         }
4154
4155         rn = wpa_driver_get_radio_name(wpa_s);
4156         if (rn && rn[0] == '\0')
4157                 rn = NULL;
4158
4159         wpa_s->radio = radio_add_interface(wpa_s, rn);
4160         if (wpa_s->radio == NULL)
4161                 return -1;
4162
4163         return 0;
4164 }
4165
4166
4167 static int wpa_supplicant_init_iface(struct wpa_supplicant *wpa_s,
4168                                      struct wpa_interface *iface)
4169 {
4170         struct wpa_driver_capa capa;
4171         int capa_res;
4172
4173         wpa_printf(MSG_DEBUG, "Initializing interface '%s' conf '%s' driver "
4174                    "'%s' ctrl_interface '%s' bridge '%s'", iface->ifname,
4175                    iface->confname ? iface->confname : "N/A",
4176                    iface->driver ? iface->driver : "default",
4177                    iface->ctrl_interface ? iface->ctrl_interface : "N/A",
4178                    iface->bridge_ifname ? iface->bridge_ifname : "N/A");
4179
4180         if (iface->confname) {
4181 #ifdef CONFIG_BACKEND_FILE
4182                 wpa_s->confname = os_rel2abs_path(iface->confname);
4183                 if (wpa_s->confname == NULL) {
4184                         wpa_printf(MSG_ERROR, "Failed to get absolute path "
4185                                    "for configuration file '%s'.",
4186                                    iface->confname);
4187                         return -1;
4188                 }
4189                 wpa_printf(MSG_DEBUG, "Configuration file '%s' -> '%s'",
4190                            iface->confname, wpa_s->confname);
4191 #else /* CONFIG_BACKEND_FILE */
4192                 wpa_s->confname = os_strdup(iface->confname);
4193 #endif /* CONFIG_BACKEND_FILE */
4194                 wpa_s->conf = wpa_config_read(wpa_s->confname, NULL);
4195                 if (wpa_s->conf == NULL) {
4196                         wpa_printf(MSG_ERROR, "Failed to read or parse "
4197                                    "configuration '%s'.", wpa_s->confname);
4198                         return -1;
4199                 }
4200                 wpa_s->confanother = os_rel2abs_path(iface->confanother);
4201                 wpa_config_read(wpa_s->confanother, wpa_s->conf);
4202
4203                 /*
4204                  * Override ctrl_interface and driver_param if set on command
4205                  * line.
4206                  */
4207                 if (iface->ctrl_interface) {
4208                         os_free(wpa_s->conf->ctrl_interface);
4209                         wpa_s->conf->ctrl_interface =
4210                                 os_strdup(iface->ctrl_interface);
4211                 }
4212
4213                 if (iface->driver_param) {
4214                         os_free(wpa_s->conf->driver_param);
4215                         wpa_s->conf->driver_param =
4216                                 os_strdup(iface->driver_param);
4217                 }
4218
4219                 if (iface->p2p_mgmt && !iface->ctrl_interface) {
4220                         os_free(wpa_s->conf->ctrl_interface);
4221                         wpa_s->conf->ctrl_interface = NULL;
4222                 }
4223         } else
4224                 wpa_s->conf = wpa_config_alloc_empty(iface->ctrl_interface,
4225                                                      iface->driver_param);
4226
4227         if (wpa_s->conf == NULL) {
4228                 wpa_printf(MSG_ERROR, "\nNo configuration found.");
4229                 return -1;
4230         }
4231
4232         if (iface->ifname == NULL) {
4233                 wpa_printf(MSG_ERROR, "\nInterface name is required.");
4234                 return -1;
4235         }
4236         if (os_strlen(iface->ifname) >= sizeof(wpa_s->ifname)) {
4237                 wpa_printf(MSG_ERROR, "\nToo long interface name '%s'.",
4238                            iface->ifname);
4239                 return -1;
4240         }
4241         os_strlcpy(wpa_s->ifname, iface->ifname, sizeof(wpa_s->ifname));
4242
4243         if (iface->bridge_ifname) {
4244                 if (os_strlen(iface->bridge_ifname) >=
4245                     sizeof(wpa_s->bridge_ifname)) {
4246                         wpa_printf(MSG_ERROR, "\nToo long bridge interface "
4247                                    "name '%s'.", iface->bridge_ifname);
4248                         return -1;
4249                 }
4250                 os_strlcpy(wpa_s->bridge_ifname, iface->bridge_ifname,
4251                            sizeof(wpa_s->bridge_ifname));
4252         }
4253
4254         /* RSNA Supplicant Key Management - INITIALIZE */
4255         eapol_sm_notify_portEnabled(wpa_s->eapol, FALSE);
4256         eapol_sm_notify_portValid(wpa_s->eapol, FALSE);
4257
4258         /* Initialize driver interface and register driver event handler before
4259          * L2 receive handler so that association events are processed before
4260          * EAPOL-Key packets if both become available for the same select()
4261          * call. */
4262         if (wpas_init_driver(wpa_s, iface) < 0)
4263                 return -1;
4264
4265         if (wpa_supplicant_init_wpa(wpa_s) < 0)
4266                 return -1;
4267
4268         wpa_sm_set_ifname(wpa_s->wpa, wpa_s->ifname,
4269                           wpa_s->bridge_ifname[0] ? wpa_s->bridge_ifname :
4270                           NULL);
4271         wpa_sm_set_fast_reauth(wpa_s->wpa, wpa_s->conf->fast_reauth);
4272
4273         if (wpa_s->conf->dot11RSNAConfigPMKLifetime &&
4274             wpa_sm_set_param(wpa_s->wpa, RSNA_PMK_LIFETIME,
4275                              wpa_s->conf->dot11RSNAConfigPMKLifetime)) {
4276                 wpa_msg(wpa_s, MSG_ERROR, "Invalid WPA parameter value for "
4277                         "dot11RSNAConfigPMKLifetime");
4278                 return -1;
4279         }
4280
4281         if (wpa_s->conf->dot11RSNAConfigPMKReauthThreshold &&
4282             wpa_sm_set_param(wpa_s->wpa, RSNA_PMK_REAUTH_THRESHOLD,
4283                              wpa_s->conf->dot11RSNAConfigPMKReauthThreshold)) {
4284                 wpa_msg(wpa_s, MSG_ERROR, "Invalid WPA parameter value for "
4285                         "dot11RSNAConfigPMKReauthThreshold");
4286                 return -1;
4287         }
4288
4289         if (wpa_s->conf->dot11RSNAConfigSATimeout &&
4290             wpa_sm_set_param(wpa_s->wpa, RSNA_SA_TIMEOUT,
4291                              wpa_s->conf->dot11RSNAConfigSATimeout)) {
4292                 wpa_msg(wpa_s, MSG_ERROR, "Invalid WPA parameter value for "
4293                         "dot11RSNAConfigSATimeout");
4294                 return -1;
4295         }
4296
4297         wpa_s->hw.modes = wpa_drv_get_hw_feature_data(wpa_s,
4298                                                       &wpa_s->hw.num_modes,
4299                                                       &wpa_s->hw.flags);
4300         if (wpa_s->hw.modes) {
4301                 u16 i;
4302
4303                 for (i = 0; i < wpa_s->hw.num_modes; i++) {
4304                         if (wpa_s->hw.modes[i].vht_capab) {
4305                                 wpa_s->hw_capab = CAPAB_VHT;
4306                                 break;
4307                         }
4308
4309                         if (wpa_s->hw.modes[i].ht_capab &
4310                             HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET)
4311                                 wpa_s->hw_capab = CAPAB_HT40;
4312                         else if (wpa_s->hw.modes[i].ht_capab &&
4313                                  wpa_s->hw_capab == CAPAB_NO_HT_VHT)
4314                                 wpa_s->hw_capab = CAPAB_HT;
4315                 }
4316         }
4317
4318         capa_res = wpa_drv_get_capa(wpa_s, &capa);
4319         if (capa_res == 0) {
4320                 wpa_s->drv_capa_known = 1;
4321                 wpa_s->drv_flags = capa.flags;
4322                 wpa_s->drv_enc = capa.enc;
4323                 wpa_s->drv_smps_modes = capa.smps_modes;
4324                 wpa_s->drv_rrm_flags = capa.rrm_flags;
4325                 wpa_s->probe_resp_offloads = capa.probe_resp_offloads;
4326                 wpa_s->max_scan_ssids = capa.max_scan_ssids;
4327                 wpa_s->max_sched_scan_ssids = capa.max_sched_scan_ssids;
4328                 wpa_s->sched_scan_supported = capa.sched_scan_supported;
4329                 wpa_s->max_match_sets = capa.max_match_sets;
4330                 wpa_s->max_remain_on_chan = capa.max_remain_on_chan;
4331                 wpa_s->max_stations = capa.max_stations;
4332                 wpa_s->extended_capa = capa.extended_capa;
4333                 wpa_s->extended_capa_mask = capa.extended_capa_mask;
4334                 wpa_s->extended_capa_len = capa.extended_capa_len;
4335                 wpa_s->num_multichan_concurrent =
4336                         capa.num_multichan_concurrent;
4337                 wpa_s->wmm_ac_supported = capa.wmm_ac_supported;
4338
4339                 if (capa.mac_addr_rand_scan_supported)
4340                         wpa_s->mac_addr_rand_supported |= MAC_ADDR_RAND_SCAN;
4341                 if (wpa_s->sched_scan_supported &&
4342                     capa.mac_addr_rand_sched_scan_supported)
4343                         wpa_s->mac_addr_rand_supported |=
4344                                 (MAC_ADDR_RAND_SCHED_SCAN | MAC_ADDR_RAND_PNO);
4345         }
4346         if (wpa_s->max_remain_on_chan == 0)
4347                 wpa_s->max_remain_on_chan = 1000;
4348
4349         /*
4350          * Only take p2p_mgmt parameters when P2P Device is supported.
4351          * Doing it here as it determines whether l2_packet_init() will be done
4352          * during wpa_supplicant_driver_init().
4353          */
4354         if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_DEDICATED_P2P_DEVICE)
4355                 wpa_s->p2p_mgmt = iface->p2p_mgmt;
4356         else
4357                 iface->p2p_mgmt = 1;
4358
4359         if (wpa_s->num_multichan_concurrent == 0)
4360                 wpa_s->num_multichan_concurrent = 1;
4361
4362         if (wpa_supplicant_driver_init(wpa_s) < 0)
4363                 return -1;
4364
4365 #ifdef CONFIG_TDLS
4366         if ((!iface->p2p_mgmt ||
4367              !(wpa_s->drv_flags &
4368                WPA_DRIVER_FLAGS_DEDICATED_P2P_DEVICE)) &&
4369             wpa_tdls_init(wpa_s->wpa))
4370                 return -1;
4371 #endif /* CONFIG_TDLS */
4372
4373         if (wpa_s->conf->country[0] && wpa_s->conf->country[1] &&
4374             wpa_drv_set_country(wpa_s, wpa_s->conf->country)) {
4375                 wpa_dbg(wpa_s, MSG_DEBUG, "Failed to set country");
4376                 return -1;
4377         }
4378
4379 #ifdef CONFIG_FST
4380         if (wpa_s->conf->fst_group_id) {
4381                 struct fst_iface_cfg cfg;
4382                 struct fst_wpa_obj iface_obj;
4383
4384                 fst_wpa_supplicant_fill_iface_obj(wpa_s, &iface_obj);
4385                 os_strlcpy(cfg.group_id, wpa_s->conf->fst_group_id,
4386                            sizeof(cfg.group_id));
4387                 cfg.priority = wpa_s->conf->fst_priority;
4388                 cfg.llt = wpa_s->conf->fst_llt;
4389
4390                 wpa_s->fst = fst_attach(wpa_s->ifname, wpa_s->own_addr,
4391                                         &iface_obj, &cfg);
4392                 if (!wpa_s->fst) {
4393                         wpa_msg(wpa_s, MSG_ERROR,
4394                                 "FST: Cannot attach iface %s to group %s",
4395                                 wpa_s->ifname, cfg.group_id);
4396                         return -1;
4397                 }
4398         }
4399 #endif /* CONFIG_FST */
4400
4401         if (wpas_wps_init(wpa_s))
4402                 return -1;
4403
4404         if (wpa_supplicant_init_eapol(wpa_s) < 0)
4405                 return -1;
4406         wpa_sm_set_eapol(wpa_s->wpa, wpa_s->eapol);
4407
4408         wpa_s->ctrl_iface = wpa_supplicant_ctrl_iface_init(wpa_s);
4409         if (wpa_s->ctrl_iface == NULL) {
4410                 wpa_printf(MSG_ERROR,
4411                            "Failed to initialize control interface '%s'.\n"
4412                            "You may have another wpa_supplicant process "
4413                            "already running or the file was\n"
4414                            "left by an unclean termination of wpa_supplicant "
4415                            "in which case you will need\n"
4416                            "to manually remove this file before starting "
4417                            "wpa_supplicant again.\n",
4418                            wpa_s->conf->ctrl_interface);
4419                 return -1;
4420         }
4421
4422         wpa_s->gas = gas_query_init(wpa_s);
4423         if (wpa_s->gas == NULL) {
4424                 wpa_printf(MSG_ERROR, "Failed to initialize GAS query");
4425                 return -1;
4426         }
4427
4428         if (iface->p2p_mgmt && wpas_p2p_init(wpa_s->global, wpa_s) < 0) {
4429                 wpa_msg(wpa_s, MSG_ERROR, "Failed to init P2P");
4430                 return -1;
4431         }
4432
4433         if (wpa_bss_init(wpa_s) < 0)
4434                 return -1;
4435
4436         /*
4437          * Set Wake-on-WLAN triggers, if configured.
4438          * Note: We don't restore/remove the triggers on shutdown (it doesn't
4439          * have effect anyway when the interface is down).
4440          */
4441         if (capa_res == 0 && wpas_set_wowlan_triggers(wpa_s, &capa) < 0)
4442                 return -1;
4443
4444 #ifdef CONFIG_EAP_PROXY
4445 {
4446         size_t len;
4447         wpa_s->mnc_len = eapol_sm_get_eap_proxy_imsi(wpa_s->eapol, wpa_s->imsi,
4448                                                      &len);
4449         if (wpa_s->mnc_len > 0) {
4450                 wpa_s->imsi[len] = '\0';
4451                 wpa_printf(MSG_DEBUG, "eap_proxy: IMSI %s (MNC length %d)",
4452                            wpa_s->imsi, wpa_s->mnc_len);
4453         } else {
4454                 wpa_printf(MSG_DEBUG, "eap_proxy: IMSI not available");
4455         }
4456 }
4457 #endif /* CONFIG_EAP_PROXY */
4458
4459         if (pcsc_reader_init(wpa_s) < 0)
4460                 return -1;
4461
4462         if (wpas_init_ext_pw(wpa_s) < 0)
4463                 return -1;
4464
4465         wpas_rrm_reset(wpa_s);
4466
4467         return 0;
4468 }
4469
4470
4471 static void wpa_supplicant_deinit_iface(struct wpa_supplicant *wpa_s,
4472                                         int notify, int terminate)
4473 {
4474         struct wpa_global *global = wpa_s->global;
4475         struct wpa_supplicant *iface, *prev;
4476
4477         if (wpa_s == wpa_s->parent)
4478                 wpas_p2p_group_remove(wpa_s, "*");
4479
4480         iface = global->ifaces;
4481         while (iface) {
4482                 if (iface == wpa_s || iface->parent != wpa_s) {
4483                         iface = iface->next;
4484                         continue;
4485                 }
4486                 wpa_printf(MSG_DEBUG,
4487                            "Remove remaining child interface %s from parent %s",
4488                            iface->ifname, wpa_s->ifname);
4489                 prev = iface;
4490                 iface = iface->next;
4491                 wpa_supplicant_remove_iface(global, prev, terminate);
4492         }
4493
4494         wpa_s->disconnected = 1;
4495         if (wpa_s->drv_priv) {
4496                 wpa_supplicant_deauthenticate(wpa_s,
4497                                               WLAN_REASON_DEAUTH_LEAVING);
4498
4499                 wpa_drv_set_countermeasures(wpa_s, 0);
4500                 wpa_clear_keys(wpa_s, NULL);
4501         }
4502
4503         wpa_supplicant_cleanup(wpa_s);
4504         wpas_p2p_deinit_iface(wpa_s);
4505
4506         wpas_ctrl_radio_work_flush(wpa_s);
4507         radio_remove_interface(wpa_s);
4508
4509 #ifdef CONFIG_FST
4510         if (wpa_s->fst) {
4511                 fst_detach(wpa_s->fst);
4512                 wpa_s->fst = NULL;
4513         }
4514         if (wpa_s->received_mb_ies) {
4515                 wpabuf_free(wpa_s->received_mb_ies);
4516                 wpa_s->received_mb_ies = NULL;
4517         }
4518 #endif /* CONFIG_FST */
4519
4520         if (wpa_s->drv_priv)
4521                 wpa_drv_deinit(wpa_s);
4522
4523         if (notify)
4524                 wpas_notify_iface_removed(wpa_s);
4525
4526         if (terminate)
4527                 wpa_msg(wpa_s, MSG_INFO, WPA_EVENT_TERMINATING);
4528
4529         if (wpa_s->ctrl_iface) {
4530                 wpa_supplicant_ctrl_iface_deinit(wpa_s->ctrl_iface);
4531                 wpa_s->ctrl_iface = NULL;
4532         }
4533
4534 #ifdef CONFIG_MESH
4535         if (wpa_s->ifmsh) {
4536                 wpa_supplicant_mesh_iface_deinit(wpa_s, wpa_s->ifmsh);
4537                 wpa_s->ifmsh = NULL;
4538         }
4539 #endif /* CONFIG_MESH */
4540
4541         if (wpa_s->conf != NULL) {
4542                 wpa_config_free(wpa_s->conf);
4543                 wpa_s->conf = NULL;
4544         }
4545
4546         os_free(wpa_s->ssids_from_scan_req);
4547
4548         os_free(wpa_s);
4549 }
4550
4551
4552 /**
4553  * wpa_supplicant_add_iface - Add a new network interface
4554  * @global: Pointer to global data from wpa_supplicant_init()
4555  * @iface: Interface configuration options
4556  * @parent: Parent interface or %NULL to assign new interface as parent
4557  * Returns: Pointer to the created interface or %NULL on failure
4558  *
4559  * This function is used to add new network interfaces for %wpa_supplicant.
4560  * This can be called before wpa_supplicant_run() to add interfaces before the
4561  * main event loop has been started. In addition, new interfaces can be added
4562  * dynamically while %wpa_supplicant is already running. This could happen,
4563  * e.g., when a hotplug network adapter is inserted.
4564  */
4565 struct wpa_supplicant * wpa_supplicant_add_iface(struct wpa_global *global,
4566                                                  struct wpa_interface *iface,
4567                                                  struct wpa_supplicant *parent)
4568 {
4569         struct wpa_supplicant *wpa_s;
4570         struct wpa_interface t_iface;
4571         struct wpa_ssid *ssid;
4572
4573         if (global == NULL || iface == NULL)
4574                 return NULL;
4575
4576         wpa_s = wpa_supplicant_alloc(parent);
4577         if (wpa_s == NULL)
4578                 return NULL;
4579
4580         wpa_s->global = global;
4581
4582         t_iface = *iface;
4583         if (global->params.override_driver) {
4584                 wpa_printf(MSG_DEBUG, "Override interface parameter: driver "
4585                            "('%s' -> '%s')",
4586                            iface->driver, global->params.override_driver);
4587                 t_iface.driver = global->params.override_driver;
4588         }
4589         if (global->params.override_ctrl_interface) {
4590                 wpa_printf(MSG_DEBUG, "Override interface parameter: "
4591                            "ctrl_interface ('%s' -> '%s')",
4592                            iface->ctrl_interface,
4593                            global->params.override_ctrl_interface);
4594                 t_iface.ctrl_interface =
4595                         global->params.override_ctrl_interface;
4596         }
4597         if (wpa_supplicant_init_iface(wpa_s, &t_iface)) {
4598                 wpa_printf(MSG_DEBUG, "Failed to add interface %s",
4599                            iface->ifname);
4600                 wpa_supplicant_deinit_iface(wpa_s, 0, 0);
4601                 return NULL;
4602         }
4603
4604         if (iface->p2p_mgmt == 0) {
4605                 /* Notify the control interfaces about new iface */
4606                 if (wpas_notify_iface_added(wpa_s)) {
4607                         wpa_supplicant_deinit_iface(wpa_s, 1, 0);
4608                         return NULL;
4609                 }
4610
4611                 for (ssid = wpa_s->conf->ssid; ssid; ssid = ssid->next)
4612                         wpas_notify_network_added(wpa_s, ssid);
4613         }
4614
4615         wpa_s->next = global->ifaces;
4616         global->ifaces = wpa_s;
4617
4618         wpa_dbg(wpa_s, MSG_DEBUG, "Added interface %s", wpa_s->ifname);
4619         wpa_supplicant_set_state(wpa_s, WPA_DISCONNECTED);
4620
4621 #ifdef CONFIG_P2P
4622         if (wpa_s->global->p2p == NULL &&
4623             !wpa_s->global->p2p_disabled && !wpa_s->conf->p2p_disabled &&
4624             (wpa_s->drv_flags & WPA_DRIVER_FLAGS_DEDICATED_P2P_DEVICE) &&
4625             wpas_p2p_add_p2pdev_interface(
4626                     wpa_s, wpa_s->global->params.conf_p2p_dev) < 0) {
4627                 wpa_printf(MSG_INFO,
4628                            "P2P: Failed to enable P2P Device interface");
4629                 /* Try to continue without. P2P will be disabled. */
4630         }
4631 #endif /* CONFIG_P2P */
4632
4633         return wpa_s;
4634 }
4635
4636
4637 /**
4638  * wpa_supplicant_remove_iface - Remove a network interface
4639  * @global: Pointer to global data from wpa_supplicant_init()
4640  * @wpa_s: Pointer to the network interface to be removed
4641  * Returns: 0 if interface was removed, -1 if interface was not found
4642  *
4643  * This function can be used to dynamically remove network interfaces from
4644  * %wpa_supplicant, e.g., when a hotplug network adapter is ejected. In
4645  * addition, this function is used to remove all remaining interfaces when
4646  * %wpa_supplicant is terminated.
4647  */
4648 int wpa_supplicant_remove_iface(struct wpa_global *global,
4649                                 struct wpa_supplicant *wpa_s,
4650                                 int terminate)
4651 {
4652         struct wpa_supplicant *prev;
4653 #ifdef CONFIG_MESH
4654         unsigned int mesh_if_created = wpa_s->mesh_if_created;
4655         char *ifname = NULL;
4656 #endif /* CONFIG_MESH */
4657
4658         /* Remove interface from the global list of interfaces */
4659         prev = global->ifaces;
4660         if (prev == wpa_s) {
4661                 global->ifaces = wpa_s->next;
4662         } else {
4663                 while (prev && prev->next != wpa_s)
4664                         prev = prev->next;
4665                 if (prev == NULL)
4666                         return -1;
4667                 prev->next = wpa_s->next;
4668         }
4669
4670         wpa_dbg(wpa_s, MSG_DEBUG, "Removing interface %s", wpa_s->ifname);
4671
4672 #ifdef CONFIG_MESH
4673         if (mesh_if_created) {
4674                 ifname = os_strdup(wpa_s->ifname);
4675                 if (ifname == NULL) {
4676                         wpa_dbg(wpa_s, MSG_ERROR,
4677                                 "mesh: Failed to malloc ifname");
4678                         return -1;
4679                 }
4680         }
4681 #endif /* CONFIG_MESH */
4682
4683         if (global->p2p_group_formation == wpa_s)
4684                 global->p2p_group_formation = NULL;
4685         if (global->p2p_invite_group == wpa_s)
4686                 global->p2p_invite_group = NULL;
4687         wpa_supplicant_deinit_iface(wpa_s, 1, terminate);
4688
4689 #ifdef CONFIG_MESH
4690         if (mesh_if_created) {
4691                 wpa_drv_if_remove(global->ifaces, WPA_IF_MESH, ifname);
4692                 os_free(ifname);
4693         }
4694 #endif /* CONFIG_MESH */
4695
4696         return 0;
4697 }
4698
4699
4700 /**
4701  * wpa_supplicant_get_eap_mode - Get the current EAP mode
4702  * @wpa_s: Pointer to the network interface
4703  * Returns: Pointer to the eap mode or the string "UNKNOWN" if not found
4704  */
4705 const char * wpa_supplicant_get_eap_mode(struct wpa_supplicant *wpa_s)
4706 {
4707         const char *eapol_method;
4708
4709         if (wpa_key_mgmt_wpa_ieee8021x(wpa_s->key_mgmt) == 0 &&
4710             wpa_s->key_mgmt != WPA_KEY_MGMT_IEEE8021X_NO_WPA) {
4711                 return "NO-EAP";
4712         }
4713
4714         eapol_method = eapol_sm_get_method_name(wpa_s->eapol);
4715         if (eapol_method == NULL)
4716                 return "UNKNOWN-EAP";
4717
4718         return eapol_method;
4719 }
4720
4721
4722 /**
4723  * wpa_supplicant_get_iface - Get a new network interface
4724  * @global: Pointer to global data from wpa_supplicant_init()
4725  * @ifname: Interface name
4726  * Returns: Pointer to the interface or %NULL if not found
4727  */
4728 struct wpa_supplicant * wpa_supplicant_get_iface(struct wpa_global *global,
4729                                                  const char *ifname)
4730 {
4731         struct wpa_supplicant *wpa_s;
4732
4733         for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) {
4734                 if (os_strcmp(wpa_s->ifname, ifname) == 0)
4735                         return wpa_s;
4736         }
4737         return NULL;
4738 }
4739
4740
4741 #ifndef CONFIG_NO_WPA_MSG
4742 static const char * wpa_supplicant_msg_ifname_cb(void *ctx)
4743 {
4744         struct wpa_supplicant *wpa_s = ctx;
4745         if (wpa_s == NULL)
4746                 return NULL;
4747         return wpa_s->ifname;
4748 }
4749 #endif /* CONFIG_NO_WPA_MSG */
4750
4751
4752 #ifndef WPA_SUPPLICANT_CLEANUP_INTERVAL
4753 #define WPA_SUPPLICANT_CLEANUP_INTERVAL 10
4754 #endif /* WPA_SUPPLICANT_CLEANUP_INTERVAL */
4755
4756 /* Periodic cleanup tasks */
4757 static void wpas_periodic(void *eloop_ctx, void *timeout_ctx)
4758 {
4759         struct wpa_global *global = eloop_ctx;
4760         struct wpa_supplicant *wpa_s;
4761
4762         eloop_register_timeout(WPA_SUPPLICANT_CLEANUP_INTERVAL, 0,
4763                                wpas_periodic, global, NULL);
4764
4765 #ifdef CONFIG_P2P
4766         if (global->p2p)
4767                 p2p_expire_peers(global->p2p);
4768 #endif /* CONFIG_P2P */
4769
4770         for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) {
4771                 wpa_bss_flush_by_age(wpa_s, wpa_s->conf->bss_expiration_age);
4772 #ifdef CONFIG_AP
4773                 ap_periodic(wpa_s);
4774 #endif /* CONFIG_AP */
4775         }
4776 }
4777
4778
4779 /**
4780  * wpa_supplicant_init - Initialize %wpa_supplicant
4781  * @params: Parameters for %wpa_supplicant
4782  * Returns: Pointer to global %wpa_supplicant data, or %NULL on failure
4783  *
4784  * This function is used to initialize %wpa_supplicant. After successful
4785  * initialization, the returned data pointer can be used to add and remove
4786  * network interfaces, and eventually, to deinitialize %wpa_supplicant.
4787  */
4788 struct wpa_global * wpa_supplicant_init(struct wpa_params *params)
4789 {
4790         struct wpa_global *global;
4791         int ret, i;
4792
4793         if (params == NULL)
4794                 return NULL;
4795
4796 #ifdef CONFIG_DRIVER_NDIS
4797         {
4798                 void driver_ndis_init_ops(void);
4799                 driver_ndis_init_ops();
4800         }
4801 #endif /* CONFIG_DRIVER_NDIS */
4802
4803 #ifndef CONFIG_NO_WPA_MSG
4804         wpa_msg_register_ifname_cb(wpa_supplicant_msg_ifname_cb);
4805 #endif /* CONFIG_NO_WPA_MSG */
4806
4807         if (params->wpa_debug_file_path)
4808                 wpa_debug_open_file(params->wpa_debug_file_path);
4809         else
4810                 wpa_debug_setup_stdout();
4811         if (params->wpa_debug_syslog)
4812                 wpa_debug_open_syslog();
4813         if (params->wpa_debug_tracing) {
4814                 ret = wpa_debug_open_linux_tracing();
4815                 if (ret) {
4816                         wpa_printf(MSG_ERROR,
4817                                    "Failed to enable trace logging");
4818                         return NULL;
4819                 }
4820         }
4821
4822         ret = eap_register_methods();
4823         if (ret) {
4824                 wpa_printf(MSG_ERROR, "Failed to register EAP methods");
4825                 if (ret == -2)
4826                         wpa_printf(MSG_ERROR, "Two or more EAP methods used "
4827                                    "the same EAP type.");
4828                 return NULL;
4829         }
4830
4831         global = os_zalloc(sizeof(*global));
4832         if (global == NULL)
4833                 return NULL;
4834         dl_list_init(&global->p2p_srv_bonjour);
4835         dl_list_init(&global->p2p_srv_upnp);
4836         global->params.daemonize = params->daemonize;
4837         global->params.wait_for_monitor = params->wait_for_monitor;
4838         global->params.dbus_ctrl_interface = params->dbus_ctrl_interface;
4839         if (params->pid_file)
4840                 global->params.pid_file = os_strdup(params->pid_file);
4841         if (params->ctrl_interface)
4842                 global->params.ctrl_interface =
4843                         os_strdup(params->ctrl_interface);
4844         if (params->ctrl_interface_group)
4845                 global->params.ctrl_interface_group =
4846                         os_strdup(params->ctrl_interface_group);
4847         if (params->override_driver)
4848                 global->params.override_driver =
4849                         os_strdup(params->override_driver);
4850         if (params->override_ctrl_interface)
4851                 global->params.override_ctrl_interface =
4852                         os_strdup(params->override_ctrl_interface);
4853 #ifdef CONFIG_P2P
4854         if (params->conf_p2p_dev)
4855                 global->params.conf_p2p_dev =
4856                         os_strdup(params->conf_p2p_dev);
4857 #endif /* CONFIG_P2P */
4858         wpa_debug_level = global->params.wpa_debug_level =
4859                 params->wpa_debug_level;
4860         wpa_debug_show_keys = global->params.wpa_debug_show_keys =
4861                 params->wpa_debug_show_keys;
4862         wpa_debug_timestamp = global->params.wpa_debug_timestamp =
4863                 params->wpa_debug_timestamp;
4864
4865         wpa_printf(MSG_DEBUG, "wpa_supplicant v" VERSION_STR);
4866
4867         if (eloop_init()) {
4868                 wpa_printf(MSG_ERROR, "Failed to initialize event loop");
4869                 wpa_supplicant_deinit(global);
4870                 return NULL;
4871         }
4872
4873         random_init(params->entropy_file);
4874
4875         global->ctrl_iface = wpa_supplicant_global_ctrl_iface_init(global);
4876         if (global->ctrl_iface == NULL) {
4877                 wpa_supplicant_deinit(global);
4878                 return NULL;
4879         }
4880
4881         if (wpas_notify_supplicant_initialized(global)) {
4882                 wpa_supplicant_deinit(global);
4883                 return NULL;
4884         }
4885
4886         for (i = 0; wpa_drivers[i]; i++)
4887                 global->drv_count++;
4888         if (global->drv_count == 0) {
4889                 wpa_printf(MSG_ERROR, "No drivers enabled");
4890                 wpa_supplicant_deinit(global);
4891                 return NULL;
4892         }
4893         global->drv_priv = os_calloc(global->drv_count, sizeof(void *));
4894         if (global->drv_priv == NULL) {
4895                 wpa_supplicant_deinit(global);
4896                 return NULL;
4897         }
4898
4899 #ifdef CONFIG_WIFI_DISPLAY
4900         if (wifi_display_init(global) < 0) {
4901                 wpa_printf(MSG_ERROR, "Failed to initialize Wi-Fi Display");
4902                 wpa_supplicant_deinit(global);
4903                 return NULL;
4904         }
4905 #endif /* CONFIG_WIFI_DISPLAY */
4906
4907         eloop_register_timeout(WPA_SUPPLICANT_CLEANUP_INTERVAL, 0,
4908                                wpas_periodic, global, NULL);
4909
4910         return global;
4911 }
4912
4913
4914 /**
4915  * wpa_supplicant_run - Run the %wpa_supplicant main event loop
4916  * @global: Pointer to global data from wpa_supplicant_init()
4917  * Returns: 0 after successful event loop run, -1 on failure
4918  *
4919  * This function starts the main event loop and continues running as long as
4920  * there are any remaining events. In most cases, this function is running as
4921  * long as the %wpa_supplicant process in still in use.
4922  */
4923 int wpa_supplicant_run(struct wpa_global *global)
4924 {
4925         struct wpa_supplicant *wpa_s;
4926
4927         if (global->params.daemonize &&
4928             wpa_supplicant_daemon(global->params.pid_file))
4929                 return -1;
4930
4931         if (global->params.wait_for_monitor) {
4932                 for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next)
4933                         if (wpa_s->ctrl_iface)
4934                                 wpa_supplicant_ctrl_iface_wait(
4935                                         wpa_s->ctrl_iface);
4936         }
4937
4938         eloop_register_signal_terminate(wpa_supplicant_terminate, global);
4939         eloop_register_signal_reconfig(wpa_supplicant_reconfig, global);
4940
4941         eloop_run();
4942
4943         return 0;
4944 }
4945
4946
4947 /**
4948  * wpa_supplicant_deinit - Deinitialize %wpa_supplicant
4949  * @global: Pointer to global data from wpa_supplicant_init()
4950  *
4951  * This function is called to deinitialize %wpa_supplicant and to free all
4952  * allocated resources. Remaining network interfaces will also be removed.
4953  */
4954 void wpa_supplicant_deinit(struct wpa_global *global)
4955 {
4956         int i;
4957
4958         if (global == NULL)
4959                 return;
4960
4961         eloop_cancel_timeout(wpas_periodic, global, NULL);
4962
4963 #ifdef CONFIG_WIFI_DISPLAY
4964         wifi_display_deinit(global);
4965 #endif /* CONFIG_WIFI_DISPLAY */
4966
4967         while (global->ifaces)
4968                 wpa_supplicant_remove_iface(global, global->ifaces, 1);
4969
4970         if (global->ctrl_iface)
4971                 wpa_supplicant_global_ctrl_iface_deinit(global->ctrl_iface);
4972
4973         wpas_notify_supplicant_deinitialized(global);
4974
4975         eap_peer_unregister_methods();
4976 #ifdef CONFIG_AP
4977         eap_server_unregister_methods();
4978 #endif /* CONFIG_AP */
4979
4980         for (i = 0; wpa_drivers[i] && global->drv_priv; i++) {
4981                 if (!global->drv_priv[i])
4982                         continue;
4983                 wpa_drivers[i]->global_deinit(global->drv_priv[i]);
4984         }
4985         os_free(global->drv_priv);
4986
4987         random_deinit();
4988
4989         eloop_destroy();
4990
4991         if (global->params.pid_file) {
4992                 os_daemonize_terminate(global->params.pid_file);
4993                 os_free(global->params.pid_file);
4994         }
4995         os_free(global->params.ctrl_interface);
4996         os_free(global->params.ctrl_interface_group);
4997         os_free(global->params.override_driver);
4998         os_free(global->params.override_ctrl_interface);
4999 #ifdef CONFIG_P2P
5000         os_free(global->params.conf_p2p_dev);
5001 #endif /* CONFIG_P2P */
5002
5003         os_free(global->p2p_disallow_freq.range);
5004         os_free(global->p2p_go_avoid_freq.range);
5005         os_free(global->add_psk);
5006
5007         os_free(global);
5008         wpa_debug_close_syslog();
5009         wpa_debug_close_file();
5010         wpa_debug_close_linux_tracing();
5011 }
5012
5013
5014 void wpa_supplicant_update_config(struct wpa_supplicant *wpa_s)
5015 {
5016         if ((wpa_s->conf->changed_parameters & CFG_CHANGED_COUNTRY) &&
5017             wpa_s->conf->country[0] && wpa_s->conf->country[1]) {
5018                 char country[3];
5019                 country[0] = wpa_s->conf->country[0];
5020                 country[1] = wpa_s->conf->country[1];
5021                 country[2] = '\0';
5022                 if (wpa_drv_set_country(wpa_s, country) < 0) {
5023                         wpa_printf(MSG_ERROR, "Failed to set country code "
5024                                    "'%s'", country);
5025                 }
5026         }
5027
5028         if (wpa_s->conf->changed_parameters & CFG_CHANGED_EXT_PW_BACKEND)
5029                 wpas_init_ext_pw(wpa_s);
5030
5031 #ifdef CONFIG_WPS
5032         wpas_wps_update_config(wpa_s);
5033 #endif /* CONFIG_WPS */
5034         wpas_p2p_update_config(wpa_s);
5035         wpa_s->conf->changed_parameters = 0;
5036 }
5037
5038
5039 void add_freq(int *freqs, int *num_freqs, int freq)
5040 {
5041         int i;
5042
5043         for (i = 0; i < *num_freqs; i++) {
5044                 if (freqs[i] == freq)
5045                         return;
5046         }
5047
5048         freqs[*num_freqs] = freq;
5049         (*num_freqs)++;
5050 }
5051
5052
5053 static int * get_bss_freqs_in_ess(struct wpa_supplicant *wpa_s)
5054 {
5055         struct wpa_bss *bss, *cbss;
5056         const int max_freqs = 10;
5057         int *freqs;
5058         int num_freqs = 0;
5059
5060         freqs = os_calloc(max_freqs + 1, sizeof(int));
5061         if (freqs == NULL)
5062                 return NULL;
5063
5064         cbss = wpa_s->current_bss;
5065
5066         dl_list_for_each(bss, &wpa_s->bss, struct wpa_bss, list) {
5067                 if (bss == cbss)
5068                         continue;
5069                 if (bss->ssid_len == cbss->ssid_len &&
5070                     os_memcmp(bss->ssid, cbss->ssid, bss->ssid_len) == 0 &&
5071                     wpa_blacklist_get(wpa_s, bss->bssid) == NULL) {
5072                         add_freq(freqs, &num_freqs, bss->freq);
5073                         if (num_freqs == max_freqs)
5074                                 break;
5075                 }
5076         }
5077
5078         if (num_freqs == 0) {
5079                 os_free(freqs);
5080                 freqs = NULL;
5081         }
5082
5083         return freqs;
5084 }
5085
5086
5087 void wpas_connection_failed(struct wpa_supplicant *wpa_s, const u8 *bssid)
5088 {
5089         int timeout;
5090         int count;
5091         int *freqs = NULL;
5092
5093         wpas_connect_work_done(wpa_s);
5094
5095         /*
5096          * Remove possible authentication timeout since the connection failed.
5097          */
5098         eloop_cancel_timeout(wpa_supplicant_timeout, wpa_s, NULL);
5099
5100         /*
5101          * There is no point in blacklisting the AP if this event is
5102          * generated based on local request to disconnect.
5103          */
5104         if (wpa_s->own_disconnect_req) {
5105                 wpa_s->own_disconnect_req = 0;
5106                 wpa_dbg(wpa_s, MSG_DEBUG,
5107                         "Ignore connection failure due to local request to disconnect");
5108                 return;
5109         }
5110         if (wpa_s->disconnected) {
5111                 wpa_dbg(wpa_s, MSG_DEBUG, "Ignore connection failure "
5112                         "indication since interface has been put into "
5113                         "disconnected state");
5114                 return;
5115         }
5116
5117         /*
5118          * Add the failed BSSID into the blacklist and speed up next scan
5119          * attempt if there could be other APs that could accept association.
5120          * The current blacklist count indicates how many times we have tried
5121          * connecting to this AP and multiple attempts mean that other APs are
5122          * either not available or has already been tried, so that we can start
5123          * increasing the delay here to avoid constant scanning.
5124          */
5125         count = wpa_blacklist_add(wpa_s, bssid);
5126         if (count == 1 && wpa_s->current_bss) {
5127                 /*
5128                  * This BSS was not in the blacklist before. If there is
5129                  * another BSS available for the same ESS, we should try that
5130                  * next. Otherwise, we may as well try this one once more
5131                  * before allowing other, likely worse, ESSes to be considered.
5132                  */
5133                 freqs = get_bss_freqs_in_ess(wpa_s);
5134                 if (freqs) {
5135                         wpa_dbg(wpa_s, MSG_DEBUG, "Another BSS in this ESS "
5136                                 "has been seen; try it next");
5137                         wpa_blacklist_add(wpa_s, bssid);
5138                         /*
5139                          * On the next scan, go through only the known channels
5140                          * used in this ESS based on previous scans to speed up
5141                          * common load balancing use case.
5142                          */
5143                         os_free(wpa_s->next_scan_freqs);
5144                         wpa_s->next_scan_freqs = freqs;
5145                 }
5146         }
5147
5148         /*
5149          * Add previous failure count in case the temporary blacklist was
5150          * cleared due to no other BSSes being available.
5151          */
5152         count += wpa_s->extra_blacklist_count;
5153
5154         if (count > 3 && wpa_s->current_ssid) {
5155                 wpa_printf(MSG_DEBUG, "Continuous association failures - "
5156                            "consider temporary network disabling");
5157                 wpas_auth_failed(wpa_s, "CONN_FAILED");
5158         }
5159
5160         switch (count) {
5161         case 1:
5162                 timeout = 100;
5163                 break;
5164         case 2:
5165                 timeout = 500;
5166                 break;
5167         case 3:
5168                 timeout = 1000;
5169                 break;
5170         case 4:
5171                 timeout = 5000;
5172                 break;
5173         default:
5174                 timeout = 10000;
5175                 break;
5176         }
5177
5178         wpa_dbg(wpa_s, MSG_DEBUG, "Blacklist count %d --> request scan in %d "
5179                 "ms", count, timeout);
5180
5181         /*
5182          * TODO: if more than one possible AP is available in scan results,
5183          * could try the other ones before requesting a new scan.
5184          */
5185         wpa_supplicant_req_scan(wpa_s, timeout / 1000,
5186                                 1000 * (timeout % 1000));
5187 }
5188
5189
5190 int wpas_driver_bss_selection(struct wpa_supplicant *wpa_s)
5191 {
5192         return wpa_s->conf->ap_scan == 2 ||
5193                 (wpa_s->drv_flags & WPA_DRIVER_FLAGS_BSS_SELECTION);
5194 }
5195
5196
5197 #if defined(CONFIG_CTRL_IFACE) || defined(CONFIG_CTRL_IFACE_DBUS_NEW)
5198 int wpa_supplicant_ctrl_iface_ctrl_rsp_handle(struct wpa_supplicant *wpa_s,
5199                                               struct wpa_ssid *ssid,
5200                                               const char *field,
5201                                               const char *value)
5202 {
5203 #ifdef IEEE8021X_EAPOL
5204         struct eap_peer_config *eap = &ssid->eap;
5205
5206         wpa_printf(MSG_DEBUG, "CTRL_IFACE: response handle field=%s", field);
5207         wpa_hexdump_ascii_key(MSG_DEBUG, "CTRL_IFACE: response value",
5208                               (const u8 *) value, os_strlen(value));
5209
5210         switch (wpa_supplicant_ctrl_req_from_string(field)) {
5211         case WPA_CTRL_REQ_EAP_IDENTITY:
5212                 os_free(eap->identity);
5213                 eap->identity = (u8 *) os_strdup(value);
5214                 eap->identity_len = os_strlen(value);
5215                 eap->pending_req_identity = 0;
5216                 if (ssid == wpa_s->current_ssid)
5217                         wpa_s->reassociate = 1;
5218                 break;
5219         case WPA_CTRL_REQ_EAP_PASSWORD:
5220                 bin_clear_free(eap->password, eap->password_len);
5221                 eap->password = (u8 *) os_strdup(value);
5222                 eap->password_len = os_strlen(value);
5223                 eap->pending_req_password = 0;
5224                 if (ssid == wpa_s->current_ssid)
5225                         wpa_s->reassociate = 1;
5226                 break;
5227         case WPA_CTRL_REQ_EAP_NEW_PASSWORD:
5228                 bin_clear_free(eap->new_password, eap->new_password_len);
5229                 eap->new_password = (u8 *) os_strdup(value);
5230                 eap->new_password_len = os_strlen(value);
5231                 eap->pending_req_new_password = 0;
5232                 if (ssid == wpa_s->current_ssid)
5233                         wpa_s->reassociate = 1;
5234                 break;
5235         case WPA_CTRL_REQ_EAP_PIN:
5236                 str_clear_free(eap->pin);
5237                 eap->pin = os_strdup(value);
5238                 eap->pending_req_pin = 0;
5239                 if (ssid == wpa_s->current_ssid)
5240                         wpa_s->reassociate = 1;
5241                 break;
5242         case WPA_CTRL_REQ_EAP_OTP:
5243                 bin_clear_free(eap->otp, eap->otp_len);
5244                 eap->otp = (u8 *) os_strdup(value);
5245                 eap->otp_len = os_strlen(value);
5246                 os_free(eap->pending_req_otp);
5247                 eap->pending_req_otp = NULL;
5248                 eap->pending_req_otp_len = 0;
5249                 break;
5250         case WPA_CTRL_REQ_EAP_PASSPHRASE:
5251                 str_clear_free(eap->private_key_passwd);
5252                 eap->private_key_passwd = os_strdup(value);
5253                 eap->pending_req_passphrase = 0;
5254                 if (ssid == wpa_s->current_ssid)
5255                         wpa_s->reassociate = 1;
5256                 break;
5257         case WPA_CTRL_REQ_SIM:
5258                 str_clear_free(eap->external_sim_resp);
5259                 eap->external_sim_resp = os_strdup(value);
5260                 break;
5261         case WPA_CTRL_REQ_PSK_PASSPHRASE:
5262                 if (wpa_config_set(ssid, "psk", value, 0) < 0)
5263                         return -1;
5264                 ssid->mem_only_psk = 1;
5265                 if (ssid->passphrase)
5266                         wpa_config_update_psk(ssid);
5267                 if (wpa_s->wpa_state == WPA_SCANNING && !wpa_s->scanning)
5268                         wpa_supplicant_req_scan(wpa_s, 0, 0);
5269                 break;
5270         default:
5271                 wpa_printf(MSG_DEBUG, "CTRL_IFACE: Unknown field '%s'", field);
5272                 return -1;
5273         }
5274
5275         return 0;
5276 #else /* IEEE8021X_EAPOL */
5277         wpa_printf(MSG_DEBUG, "CTRL_IFACE: IEEE 802.1X not included");
5278         return -1;
5279 #endif /* IEEE8021X_EAPOL */
5280 }
5281 #endif /* CONFIG_CTRL_IFACE || CONFIG_CTRL_IFACE_DBUS_NEW */
5282
5283
5284 int wpas_network_disabled(struct wpa_supplicant *wpa_s, struct wpa_ssid *ssid)
5285 {
5286         int i;
5287         unsigned int drv_enc;
5288
5289         if (wpa_s->p2p_mgmt)
5290                 return 1; /* no normal network profiles on p2p_mgmt interface */
5291
5292         if (ssid == NULL)
5293                 return 1;
5294
5295         if (ssid->disabled)
5296                 return 1;
5297
5298         if (wpa_s->drv_capa_known)
5299                 drv_enc = wpa_s->drv_enc;
5300         else
5301                 drv_enc = (unsigned int) -1;
5302
5303         for (i = 0; i < NUM_WEP_KEYS; i++) {
5304                 size_t len = ssid->wep_key_len[i];
5305                 if (len == 0)
5306                         continue;
5307                 if (len == 5 && (drv_enc & WPA_DRIVER_CAPA_ENC_WEP40))
5308                         continue;
5309                 if (len == 13 && (drv_enc & WPA_DRIVER_CAPA_ENC_WEP104))
5310                         continue;
5311                 if (len == 16 && (drv_enc & WPA_DRIVER_CAPA_ENC_WEP128))
5312                         continue;
5313                 return 1; /* invalid WEP key */
5314         }
5315
5316         if (wpa_key_mgmt_wpa_psk(ssid->key_mgmt) && !ssid->psk_set &&
5317             (!ssid->passphrase || ssid->ssid_len != 0) && !ssid->ext_psk &&
5318             !ssid->mem_only_psk)
5319                 return 1;
5320
5321         return 0;
5322 }
5323
5324
5325 int wpas_get_ssid_pmf(struct wpa_supplicant *wpa_s, struct wpa_ssid *ssid)
5326 {
5327 #ifdef CONFIG_IEEE80211W
5328         if (ssid == NULL || ssid->ieee80211w == MGMT_FRAME_PROTECTION_DEFAULT) {
5329                 if (wpa_s->conf->pmf == MGMT_FRAME_PROTECTION_OPTIONAL &&
5330                     !(wpa_s->drv_enc & WPA_DRIVER_CAPA_ENC_BIP)) {
5331                         /*
5332                          * Driver does not support BIP -- ignore pmf=1 default
5333                          * since the connection with PMF would fail and the
5334                          * configuration does not require PMF to be enabled.
5335                          */
5336                         return NO_MGMT_FRAME_PROTECTION;
5337                 }
5338
5339                 return wpa_s->conf->pmf;
5340         }
5341
5342         return ssid->ieee80211w;
5343 #else /* CONFIG_IEEE80211W */
5344         return NO_MGMT_FRAME_PROTECTION;
5345 #endif /* CONFIG_IEEE80211W */
5346 }
5347
5348
5349 int wpas_is_p2p_prioritized(struct wpa_supplicant *wpa_s)
5350 {
5351         if (wpa_s->global->conc_pref == WPA_CONC_PREF_P2P)
5352                 return 1;
5353         if (wpa_s->global->conc_pref == WPA_CONC_PREF_STA)
5354                 return 0;
5355         return -1;
5356 }
5357
5358
5359 void wpas_auth_failed(struct wpa_supplicant *wpa_s, char *reason)
5360 {
5361         struct wpa_ssid *ssid = wpa_s->current_ssid;
5362         int dur;
5363         struct os_reltime now;
5364
5365         if (ssid == NULL) {
5366                 wpa_printf(MSG_DEBUG, "Authentication failure but no known "
5367                            "SSID block");
5368                 return;
5369         }
5370
5371         if (ssid->key_mgmt == WPA_KEY_MGMT_WPS)
5372                 return;
5373
5374         ssid->auth_failures++;
5375
5376 #ifdef CONFIG_P2P
5377         if (ssid->p2p_group &&
5378             (wpa_s->p2p_in_provisioning || wpa_s->show_group_started)) {
5379                 /*
5380                  * Skip the wait time since there is a short timeout on the
5381                  * connection to a P2P group.
5382                  */
5383                 return;
5384         }
5385 #endif /* CONFIG_P2P */
5386
5387         if (ssid->auth_failures > 50)
5388                 dur = 300;
5389         else if (ssid->auth_failures > 10)
5390                 dur = 120;
5391         else if (ssid->auth_failures > 5)
5392                 dur = 90;
5393         else if (ssid->auth_failures > 3)
5394                 dur = 60;
5395         else if (ssid->auth_failures > 2)
5396                 dur = 30;
5397         else if (ssid->auth_failures > 1)
5398                 dur = 20;
5399         else
5400                 dur = 10;
5401
5402         if (ssid->auth_failures > 1 &&
5403             wpa_key_mgmt_wpa_ieee8021x(ssid->key_mgmt))
5404                 dur += os_random() % (ssid->auth_failures * 10);
5405
5406         os_get_reltime(&now);
5407         if (now.sec + dur <= ssid->disabled_until.sec)
5408                 return;
5409
5410         ssid->disabled_until.sec = now.sec + dur;
5411
5412         wpa_msg(wpa_s, MSG_INFO, WPA_EVENT_TEMP_DISABLED
5413                 "id=%d ssid=\"%s\" auth_failures=%u duration=%d reason=%s",
5414                 ssid->id, wpa_ssid_txt(ssid->ssid, ssid->ssid_len),
5415                 ssid->auth_failures, dur, reason);
5416 }
5417
5418
5419 void wpas_clear_temp_disabled(struct wpa_supplicant *wpa_s,
5420                               struct wpa_ssid *ssid, int clear_failures)
5421 {
5422         if (ssid == NULL)
5423                 return;
5424
5425         if (ssid->disabled_until.sec) {
5426                 wpa_msg(wpa_s, MSG_INFO, WPA_EVENT_REENABLED
5427                         "id=%d ssid=\"%s\"",
5428                         ssid->id, wpa_ssid_txt(ssid->ssid, ssid->ssid_len));
5429         }
5430         ssid->disabled_until.sec = 0;
5431         ssid->disabled_until.usec = 0;
5432         if (clear_failures)
5433                 ssid->auth_failures = 0;
5434 }
5435
5436
5437 int disallowed_bssid(struct wpa_supplicant *wpa_s, const u8 *bssid)
5438 {
5439         size_t i;
5440
5441         if (wpa_s->disallow_aps_bssid == NULL)
5442                 return 0;
5443
5444         for (i = 0; i < wpa_s->disallow_aps_bssid_count; i++) {
5445                 if (os_memcmp(wpa_s->disallow_aps_bssid + i * ETH_ALEN,
5446                               bssid, ETH_ALEN) == 0)
5447                         return 1;
5448         }
5449
5450         return 0;
5451 }
5452
5453
5454 int disallowed_ssid(struct wpa_supplicant *wpa_s, const u8 *ssid,
5455                     size_t ssid_len)
5456 {
5457         size_t i;
5458
5459         if (wpa_s->disallow_aps_ssid == NULL || ssid == NULL)
5460                 return 0;
5461
5462         for (i = 0; i < wpa_s->disallow_aps_ssid_count; i++) {
5463                 struct wpa_ssid_value *s = &wpa_s->disallow_aps_ssid[i];
5464                 if (ssid_len == s->ssid_len &&
5465                     os_memcmp(ssid, s->ssid, ssid_len) == 0)
5466                         return 1;
5467         }
5468
5469         return 0;
5470 }
5471
5472
5473 /**
5474  * wpas_request_connection - Request a new connection
5475  * @wpa_s: Pointer to the network interface
5476  *
5477  * This function is used to request a new connection to be found. It will mark
5478  * the interface to allow reassociation and request a new scan to find a
5479  * suitable network to connect to.
5480  */
5481 void wpas_request_connection(struct wpa_supplicant *wpa_s)
5482 {
5483         wpa_s->normal_scans = 0;
5484         wpa_s->scan_req = NORMAL_SCAN_REQ;
5485         wpa_supplicant_reinit_autoscan(wpa_s);
5486         wpa_s->extra_blacklist_count = 0;
5487         wpa_s->disconnected = 0;
5488         wpa_s->reassociate = 1;
5489
5490         if (wpa_supplicant_fast_associate(wpa_s) != 1)
5491                 wpa_supplicant_req_scan(wpa_s, 0, 0);
5492         else
5493                 wpa_s->reattach = 0;
5494 }
5495
5496
5497 void dump_freq_data(struct wpa_supplicant *wpa_s, const char *title,
5498                     struct wpa_used_freq_data *freqs_data,
5499                     unsigned int len)
5500 {
5501         unsigned int i;
5502
5503         wpa_dbg(wpa_s, MSG_DEBUG, "Shared frequencies (len=%u): %s",
5504                 len, title);
5505         for (i = 0; i < len; i++) {
5506                 struct wpa_used_freq_data *cur = &freqs_data[i];
5507                 wpa_dbg(wpa_s, MSG_DEBUG, "freq[%u]: %d, flags=0x%X",
5508                         i, cur->freq, cur->flags);
5509         }
5510 }
5511
5512
5513 /*
5514  * Find the operating frequencies of any of the virtual interfaces that
5515  * are using the same radio as the current interface, and in addition, get
5516  * information about the interface types that are using the frequency.
5517  */
5518 int get_shared_radio_freqs_data(struct wpa_supplicant *wpa_s,
5519                                 struct wpa_used_freq_data *freqs_data,
5520                                 unsigned int len)
5521 {
5522         struct wpa_supplicant *ifs;
5523         u8 bssid[ETH_ALEN];
5524         int freq;
5525         unsigned int idx = 0, i;
5526
5527         wpa_dbg(wpa_s, MSG_DEBUG,
5528                 "Determining shared radio frequencies (max len %u)", len);
5529         os_memset(freqs_data, 0, sizeof(struct wpa_used_freq_data) * len);
5530
5531         dl_list_for_each(ifs, &wpa_s->radio->ifaces, struct wpa_supplicant,
5532                          radio_list) {
5533                 if (idx == len)
5534                         break;
5535
5536                 if (ifs->current_ssid == NULL || ifs->assoc_freq == 0)
5537                         continue;
5538
5539                 if (ifs->current_ssid->mode == WPAS_MODE_AP ||
5540                     ifs->current_ssid->mode == WPAS_MODE_P2P_GO)
5541                         freq = ifs->current_ssid->frequency;
5542                 else if (wpa_drv_get_bssid(ifs, bssid) == 0)
5543                         freq = ifs->assoc_freq;
5544                 else
5545                         continue;
5546
5547                 /* Hold only distinct freqs */
5548                 for (i = 0; i < idx; i++)
5549                         if (freqs_data[i].freq == freq)
5550                                 break;
5551
5552                 if (i == idx)
5553                         freqs_data[idx++].freq = freq;
5554
5555                 if (ifs->current_ssid->mode == WPAS_MODE_INFRA) {
5556                         freqs_data[i].flags = ifs->current_ssid->p2p_group ?
5557                                 WPA_FREQ_USED_BY_P2P_CLIENT :
5558                                 WPA_FREQ_USED_BY_INFRA_STATION;
5559                 }
5560         }
5561
5562         dump_freq_data(wpa_s, "completed iteration", freqs_data, idx);
5563         return idx;
5564 }
5565
5566
5567 /*
5568  * Find the operating frequencies of any of the virtual interfaces that
5569  * are using the same radio as the current interface.
5570  */
5571 int get_shared_radio_freqs(struct wpa_supplicant *wpa_s,
5572                            int *freq_array, unsigned int len)
5573 {
5574         struct wpa_used_freq_data *freqs_data;
5575         int num, i;
5576
5577         os_memset(freq_array, 0, sizeof(int) * len);
5578
5579         freqs_data = os_calloc(len, sizeof(struct wpa_used_freq_data));
5580         if (!freqs_data)
5581                 return -1;
5582
5583         num = get_shared_radio_freqs_data(wpa_s, freqs_data, len);
5584         for (i = 0; i < num; i++)
5585                 freq_array[i] = freqs_data[i].freq;
5586
5587         os_free(freqs_data);
5588
5589         return num;
5590 }
5591
5592
5593 static void wpas_rrm_neighbor_rep_timeout_handler(void *data, void *user_ctx)
5594 {
5595         struct rrm_data *rrm = data;
5596
5597         if (!rrm->notify_neighbor_rep) {
5598                 wpa_printf(MSG_ERROR,
5599                            "RRM: Unexpected neighbor report timeout");
5600                 return;
5601         }
5602
5603         wpa_printf(MSG_DEBUG, "RRM: Notifying neighbor report - NONE");
5604         rrm->notify_neighbor_rep(rrm->neighbor_rep_cb_ctx, NULL);
5605
5606         rrm->notify_neighbor_rep = NULL;
5607         rrm->neighbor_rep_cb_ctx = NULL;
5608 }
5609
5610
5611 /*
5612  * wpas_rrm_reset - Clear and reset all RRM data in wpa_supplicant
5613  * @wpa_s: Pointer to wpa_supplicant
5614  */
5615 void wpas_rrm_reset(struct wpa_supplicant *wpa_s)
5616 {
5617         wpa_s->rrm.rrm_used = 0;
5618
5619         eloop_cancel_timeout(wpas_rrm_neighbor_rep_timeout_handler, &wpa_s->rrm,
5620                              NULL);
5621         if (wpa_s->rrm.notify_neighbor_rep)
5622                 wpas_rrm_neighbor_rep_timeout_handler(&wpa_s->rrm, NULL);
5623         wpa_s->rrm.next_neighbor_rep_token = 1;
5624 }
5625
5626
5627 /*
5628  * wpas_rrm_process_neighbor_rep - Handle incoming neighbor report
5629  * @wpa_s: Pointer to wpa_supplicant
5630  * @report: Neighbor report buffer, prefixed by a 1-byte dialog token
5631  * @report_len: Length of neighbor report buffer
5632  */
5633 void wpas_rrm_process_neighbor_rep(struct wpa_supplicant *wpa_s,
5634                                    const u8 *report, size_t report_len)
5635 {
5636         struct wpabuf *neighbor_rep;
5637
5638         wpa_hexdump(MSG_DEBUG, "RRM: New Neighbor Report", report, report_len);
5639         if (report_len < 1)
5640                 return;
5641
5642         if (report[0] != wpa_s->rrm.next_neighbor_rep_token - 1) {
5643                 wpa_printf(MSG_DEBUG,
5644                            "RRM: Discarding neighbor report with token %d (expected %d)",
5645                            report[0], wpa_s->rrm.next_neighbor_rep_token - 1);
5646                 return;
5647         }
5648
5649         eloop_cancel_timeout(wpas_rrm_neighbor_rep_timeout_handler, &wpa_s->rrm,
5650                              NULL);
5651
5652         if (!wpa_s->rrm.notify_neighbor_rep) {
5653                 wpa_printf(MSG_ERROR, "RRM: Unexpected neighbor report");
5654                 return;
5655         }
5656
5657         /* skipping the first byte, which is only an id (dialog token) */
5658         neighbor_rep = wpabuf_alloc(report_len - 1);
5659         if (neighbor_rep == NULL)
5660                 return;
5661         wpabuf_put_data(neighbor_rep, report + 1, report_len - 1);
5662         wpa_printf(MSG_DEBUG, "RRM: Notifying neighbor report (token = %d)",
5663                    report[0]);
5664         wpa_s->rrm.notify_neighbor_rep(wpa_s->rrm.neighbor_rep_cb_ctx,
5665                                        neighbor_rep);
5666         wpa_s->rrm.notify_neighbor_rep = NULL;
5667         wpa_s->rrm.neighbor_rep_cb_ctx = NULL;
5668 }
5669
5670
5671 #if defined(__CYGWIN__) || defined(CONFIG_NATIVE_WINDOWS)
5672 /* Workaround different, undefined for Windows, error codes used here */
5673 #define ENOTCONN -1
5674 #define EOPNOTSUPP -1
5675 #define ECANCELED -1
5676 #endif
5677
5678 /**
5679  * wpas_rrm_send_neighbor_rep_request - Request a neighbor report from our AP
5680  * @wpa_s: Pointer to wpa_supplicant
5681  * @ssid: if not null, this is sent in the request. Otherwise, no SSID IE
5682  *        is sent in the request.
5683  * @cb: Callback function to be called once the requested report arrives, or
5684  *      timed out after RRM_NEIGHBOR_REPORT_TIMEOUT seconds.
5685  *      In the former case, 'neighbor_rep' is a newly allocated wpabuf, and it's
5686  *      the requester's responsibility to free it.
5687  *      In the latter case NULL will be sent in 'neighbor_rep'.
5688  * @cb_ctx: Context value to send the callback function
5689  * Returns: 0 in case of success, negative error code otherwise
5690  *
5691  * In case there is a previous request which has not been answered yet, the
5692  * new request fails. The caller may retry after RRM_NEIGHBOR_REPORT_TIMEOUT.
5693  * Request must contain a callback function.
5694  */
5695 int wpas_rrm_send_neighbor_rep_request(struct wpa_supplicant *wpa_s,
5696                                        const struct wpa_ssid *ssid,
5697                                        void (*cb)(void *ctx,
5698                                                   struct wpabuf *neighbor_rep),
5699                                        void *cb_ctx)
5700 {
5701         struct wpabuf *buf;
5702         const u8 *rrm_ie;
5703
5704         if (wpa_s->wpa_state != WPA_COMPLETED || wpa_s->current_ssid == NULL) {
5705                 wpa_printf(MSG_DEBUG, "RRM: No connection, no RRM.");
5706                 return -ENOTCONN;
5707         }
5708
5709         if (!wpa_s->rrm.rrm_used) {
5710                 wpa_printf(MSG_DEBUG, "RRM: No RRM in current connection.");
5711                 return -EOPNOTSUPP;
5712         }
5713
5714         rrm_ie = wpa_bss_get_ie(wpa_s->current_bss,
5715                                 WLAN_EID_RRM_ENABLED_CAPABILITIES);
5716         if (!rrm_ie || !(wpa_s->current_bss->caps & IEEE80211_CAP_RRM) ||
5717             !(rrm_ie[2] & WLAN_RRM_CAPS_NEIGHBOR_REPORT)) {
5718                 wpa_printf(MSG_DEBUG,
5719                            "RRM: No network support for Neighbor Report.");
5720                 return -EOPNOTSUPP;
5721         }
5722
5723         if (!cb) {
5724                 wpa_printf(MSG_DEBUG,
5725                            "RRM: Neighbor Report request must provide a callback.");
5726                 return -EINVAL;
5727         }
5728
5729         /* Refuse if there's a live request */
5730         if (wpa_s->rrm.notify_neighbor_rep) {
5731                 wpa_printf(MSG_DEBUG,
5732                            "RRM: Currently handling previous Neighbor Report.");
5733                 return -EBUSY;
5734         }
5735
5736         /* 3 = action category + action code + dialog token */
5737         buf = wpabuf_alloc(3 + (ssid ? 2 + ssid->ssid_len : 0));
5738         if (buf == NULL) {
5739                 wpa_printf(MSG_DEBUG,
5740                            "RRM: Failed to allocate Neighbor Report Request");
5741                 return -ENOMEM;
5742         }
5743
5744         wpa_printf(MSG_DEBUG, "RRM: Neighbor report request (for %s), token=%d",
5745                    (ssid ? wpa_ssid_txt(ssid->ssid, ssid->ssid_len) : ""),
5746                    wpa_s->rrm.next_neighbor_rep_token);
5747
5748         wpabuf_put_u8(buf, WLAN_ACTION_RADIO_MEASUREMENT);
5749         wpabuf_put_u8(buf, WLAN_RRM_NEIGHBOR_REPORT_REQUEST);
5750         wpabuf_put_u8(buf, wpa_s->rrm.next_neighbor_rep_token);
5751         if (ssid) {
5752                 wpabuf_put_u8(buf, WLAN_EID_SSID);
5753                 wpabuf_put_u8(buf, ssid->ssid_len);
5754                 wpabuf_put_data(buf, ssid->ssid, ssid->ssid_len);
5755         }
5756
5757         wpa_s->rrm.next_neighbor_rep_token++;
5758
5759         if (wpa_drv_send_action(wpa_s, wpa_s->assoc_freq, 0, wpa_s->bssid,
5760                                 wpa_s->own_addr, wpa_s->bssid,
5761                                 wpabuf_head(buf), wpabuf_len(buf), 0) < 0) {
5762                 wpa_printf(MSG_DEBUG,
5763                            "RRM: Failed to send Neighbor Report Request");
5764                 wpabuf_free(buf);
5765                 return -ECANCELED;
5766         }
5767
5768         wpa_s->rrm.neighbor_rep_cb_ctx = cb_ctx;
5769         wpa_s->rrm.notify_neighbor_rep = cb;
5770         eloop_register_timeout(RRM_NEIGHBOR_REPORT_TIMEOUT, 0,
5771                                wpas_rrm_neighbor_rep_timeout_handler,
5772                                &wpa_s->rrm, NULL);
5773
5774         wpabuf_free(buf);
5775         return 0;
5776 }
5777
5778
5779 void wpas_rrm_handle_link_measurement_request(struct wpa_supplicant *wpa_s,
5780                                               const u8 *src,
5781                                               const u8 *frame, size_t len,
5782                                               int rssi)
5783 {
5784         struct wpabuf *buf;
5785         const struct rrm_link_measurement_request *req;
5786         struct rrm_link_measurement_report report;
5787
5788         if (wpa_s->wpa_state != WPA_COMPLETED) {
5789                 wpa_printf(MSG_INFO,
5790                            "RRM: Ignoring link measurement request. Not associated");
5791                 return;
5792         }
5793
5794         if (!wpa_s->rrm.rrm_used) {
5795                 wpa_printf(MSG_INFO,
5796                            "RRM: Ignoring link measurement request. Not RRM network");
5797                 return;
5798         }
5799
5800         if (!(wpa_s->drv_rrm_flags & WPA_DRIVER_FLAGS_TX_POWER_INSERTION)) {
5801                 wpa_printf(MSG_INFO,
5802                            "RRM: Measurement report failed. TX power insertion not supported");
5803                 return;
5804         }
5805
5806         req = (const struct rrm_link_measurement_request *) frame;
5807         if (len < sizeof(*req)) {
5808                 wpa_printf(MSG_INFO,
5809                            "RRM: Link measurement report failed. Request too short");
5810                 return;
5811         }
5812
5813         os_memset(&report, 0, sizeof(report));
5814         report.tpc.eid = WLAN_EID_TPC_REPORT;
5815         report.tpc.len = 2;
5816         report.rsni = 255; /* 255 indicates that RSNI is not available */
5817         report.dialog_token = req->dialog_token;
5818
5819         /*
5820          * It's possible to estimate RCPI based on RSSI in dBm. This
5821          * calculation will not reflect the correct value for high rates,
5822          * but it's good enough for Action frames which are transmitted
5823          * with up to 24 Mbps rates.
5824          */
5825         if (!rssi)
5826                 report.rcpi = 255; /* not available */
5827         else if (rssi < -110)
5828                 report.rcpi = 0;
5829         else if (rssi > 0)
5830                 report.rcpi = 220;
5831         else
5832                 report.rcpi = (rssi + 110) * 2;
5833
5834         /* action_category + action_code */
5835         buf = wpabuf_alloc(2 + sizeof(report));
5836         if (buf == NULL) {
5837                 wpa_printf(MSG_ERROR,
5838                            "RRM: Link measurement report failed. Buffer allocation failed");
5839                 return;
5840         }
5841
5842         wpabuf_put_u8(buf, WLAN_ACTION_RADIO_MEASUREMENT);
5843         wpabuf_put_u8(buf, WLAN_RRM_LINK_MEASUREMENT_REPORT);
5844         wpabuf_put_data(buf, &report, sizeof(report));
5845         wpa_hexdump(MSG_DEBUG, "RRM: Link measurement report:",
5846                     wpabuf_head(buf), wpabuf_len(buf));
5847
5848         if (wpa_drv_send_action(wpa_s, wpa_s->assoc_freq, 0, src,
5849                                 wpa_s->own_addr, wpa_s->bssid,
5850                                 wpabuf_head(buf), wpabuf_len(buf), 0)) {
5851                 wpa_printf(MSG_ERROR,
5852                            "RRM: Link measurement report failed. Send action failed");
5853         }
5854         wpabuf_free(buf);
5855 }