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