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