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