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