889f81e12fb47a1175ba8bd38fb7c9de8ea00658
[libeap.git] / hostapd / hostapd.c
1 /*
2  * hostapd / Initialization and configuration
3  * Copyright (c) 2002-2008, Jouni Malinen <j@w1.fi>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation.
8  *
9  * Alternatively, this software may be distributed under the terms of BSD
10  * license.
11  *
12  * See README and COPYING for more details.
13  */
14
15 #include "includes.h"
16 #ifndef CONFIG_NATIVE_WINDOWS
17 #include <syslog.h>
18 #endif /* CONFIG_NATIVE_WINDOWS */
19
20 #include "eloop.h"
21 #include "hostapd.h"
22 #include "ieee802_1x.h"
23 #include "ieee802_11.h"
24 #include "beacon.h"
25 #include "hw_features.h"
26 #include "accounting.h"
27 #include "eapol_sm.h"
28 #include "iapp.h"
29 #include "ap.h"
30 #include "ieee802_11_auth.h"
31 #include "ap_list.h"
32 #include "sta_info.h"
33 #include "driver.h"
34 #include "radius/radius_client.h"
35 #include "radius/radius_server.h"
36 #include "wpa.h"
37 #include "preauth.h"
38 #include "wme.h"
39 #include "vlan_init.h"
40 #include "ctrl_iface.h"
41 #include "tls.h"
42 #include "eap_server/eap_sim_db.h"
43 #include "eap_server/eap.h"
44 #include "eap_server/tncs.h"
45 #include "version.h"
46 #include "l2_packet/l2_packet.h"
47
48
49 static int hostapd_radius_get_eap_user(void *ctx, const u8 *identity,
50                                        size_t identity_len, int phase2,
51                                        struct eap_user *user);
52
53 struct hapd_interfaces {
54         size_t count;
55         struct hostapd_iface **iface;
56 };
57
58 unsigned char rfc1042_header[6] = { 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 };
59
60
61 extern int wpa_debug_level;
62 extern int wpa_debug_show_keys;
63 extern int wpa_debug_timestamp;
64
65
66 static void hostapd_logger_cb(void *ctx, const u8 *addr, unsigned int module,
67                               int level, const char *txt, size_t len)
68 {
69         struct hostapd_data *hapd = ctx;
70         char *format, *module_str;
71         int maxlen;
72         int conf_syslog_level, conf_stdout_level;
73         unsigned int conf_syslog, conf_stdout;
74
75         maxlen = len + 100;
76         format = os_malloc(maxlen);
77         if (!format)
78                 return;
79
80         if (hapd && hapd->conf) {
81                 conf_syslog_level = hapd->conf->logger_syslog_level;
82                 conf_stdout_level = hapd->conf->logger_stdout_level;
83                 conf_syslog = hapd->conf->logger_syslog;
84                 conf_stdout = hapd->conf->logger_stdout;
85         } else {
86                 conf_syslog_level = conf_stdout_level = 0;
87                 conf_syslog = conf_stdout = (unsigned int) -1;
88         }
89
90         switch (module) {
91         case HOSTAPD_MODULE_IEEE80211:
92                 module_str = "IEEE 802.11";
93                 break;
94         case HOSTAPD_MODULE_IEEE8021X:
95                 module_str = "IEEE 802.1X";
96                 break;
97         case HOSTAPD_MODULE_RADIUS:
98                 module_str = "RADIUS";
99                 break;
100         case HOSTAPD_MODULE_WPA:
101                 module_str = "WPA";
102                 break;
103         case HOSTAPD_MODULE_DRIVER:
104                 module_str = "DRIVER";
105                 break;
106         case HOSTAPD_MODULE_IAPP:
107                 module_str = "IAPP";
108                 break;
109         case HOSTAPD_MODULE_MLME:
110                 module_str = "MLME";
111                 break;
112         default:
113                 module_str = NULL;
114                 break;
115         }
116
117         if (hapd && hapd->conf && addr)
118                 os_snprintf(format, maxlen, "%s: STA " MACSTR "%s%s: %s",
119                             hapd->conf->iface, MAC2STR(addr),
120                             module_str ? " " : "", module_str, txt);
121         else if (hapd && hapd->conf)
122                 os_snprintf(format, maxlen, "%s:%s%s %s",
123                             hapd->conf->iface, module_str ? " " : "",
124                             module_str, txt);
125         else if (addr)
126                 os_snprintf(format, maxlen, "STA " MACSTR "%s%s: %s",
127                             MAC2STR(addr), module_str ? " " : "",
128                             module_str, txt);
129         else
130                 os_snprintf(format, maxlen, "%s%s%s",
131                             module_str, module_str ? ": " : "", txt);
132
133         if ((conf_stdout & module) && level >= conf_stdout_level) {
134                 wpa_debug_print_timestamp();
135                 printf("%s\n", format);
136         }
137
138 #ifndef CONFIG_NATIVE_WINDOWS
139         if ((conf_syslog & module) && level >= conf_syslog_level) {
140                 int priority;
141                 switch (level) {
142                 case HOSTAPD_LEVEL_DEBUG_VERBOSE:
143                 case HOSTAPD_LEVEL_DEBUG:
144                         priority = LOG_DEBUG;
145                         break;
146                 case HOSTAPD_LEVEL_INFO:
147                         priority = LOG_INFO;
148                         break;
149                 case HOSTAPD_LEVEL_NOTICE:
150                         priority = LOG_NOTICE;
151                         break;
152                 case HOSTAPD_LEVEL_WARNING:
153                         priority = LOG_WARNING;
154                         break;
155                 default:
156                         priority = LOG_INFO;
157                         break;
158                 }
159                 syslog(priority, "%s", format);
160         }
161 #endif /* CONFIG_NATIVE_WINDOWS */
162
163         os_free(format);
164 }
165
166
167 static void hostapd_deauth_all_stas(struct hostapd_data *hapd)
168 {
169         u8 addr[ETH_ALEN];
170
171         /* New Prism2.5/3 STA firmware versions seem to have issues with this
172          * broadcast deauth frame. This gets the firmware in odd state where
173          * nothing works correctly, so let's skip sending this for the hostap
174          * driver. */
175
176         if (hapd->driver && os_strcmp(hapd->driver->name, "hostap") != 0) {
177                 os_memset(addr, 0xff, ETH_ALEN);
178                 hostapd_sta_deauth(hapd, addr,
179                                    WLAN_REASON_PREV_AUTH_NOT_VALID);
180         }
181 }
182
183
184 /**
185  * hostapd_prune_associations - Remove extraneous associations
186  * @hapd: Pointer to BSS data for the most recent association
187  * @sta: Pointer to the associated STA data
188  *
189  * This function looks through all radios and BSS's for previous
190  * (stale) associations of STA. If any are found they are removed.
191  */
192 static void hostapd_prune_associations(struct hostapd_data *hapd,
193                                        struct sta_info *sta)
194 {
195         struct sta_info *osta;
196         struct hostapd_data *ohapd;
197         size_t i, j;
198         struct hapd_interfaces *interfaces = eloop_get_user_data();
199
200         for (i = 0; i < interfaces->count; i++) {
201                 for (j = 0; j < interfaces->iface[i]->num_bss; j++) {
202                         ohapd = interfaces->iface[i]->bss[j];
203                         if (ohapd == hapd)
204                                 continue;
205                         osta = ap_get_sta(ohapd, sta->addr);
206                         if (!osta)
207                                 continue;
208
209                         ap_sta_disassociate(ohapd, osta,
210                                             WLAN_REASON_UNSPECIFIED);
211                 }
212         }
213 }
214
215
216 /**
217  * hostapd_new_assoc_sta - Notify that a new station associated with the AP
218  * @hapd: Pointer to BSS data
219  * @sta: Pointer to the associated STA data
220  * @reassoc: 1 to indicate this was a re-association; 0 = first association
221  *
222  * This function will be called whenever a station associates with the AP. It
223  * can be called for ieee802_11.c for drivers that export MLME to hostapd and
224  * from driver_*.c for drivers that take care of management frames (IEEE 802.11
225  * authentication and association) internally.
226  */
227 void hostapd_new_assoc_sta(struct hostapd_data *hapd, struct sta_info *sta,
228                            int reassoc)
229 {
230         if (hapd->tkip_countermeasures) {
231                 hostapd_sta_deauth(hapd, sta->addr,
232                                    WLAN_REASON_MICHAEL_MIC_FAILURE);
233                 return;
234         }
235
236         hostapd_prune_associations(hapd, sta);
237
238         /* IEEE 802.11F (IAPP) */
239         if (hapd->conf->ieee802_11f)
240                 iapp_new_station(hapd->iapp, sta);
241
242         /* Start accounting here, if IEEE 802.1X and WPA are not used.
243          * IEEE 802.1X/WPA code will start accounting after the station has
244          * been authorized. */
245         if (!hapd->conf->ieee802_1x && !hapd->conf->wpa)
246                 accounting_sta_start(hapd, sta);
247
248         hostapd_wme_sta_config(hapd, sta);
249
250         /* Start IEEE 802.1X authentication process for new stations */
251         ieee802_1x_new_station(hapd, sta);
252         if (reassoc) {
253                 if (sta->auth_alg != WLAN_AUTH_FT)
254                         wpa_auth_sm_event(sta->wpa_sm, WPA_REAUTH);
255         } else
256                 wpa_auth_sta_associated(hapd->wpa_auth, sta->wpa_sm);
257 }
258
259
260 #ifdef EAP_SERVER
261 static int hostapd_sim_db_cb_sta(struct hostapd_data *hapd,
262                                  struct sta_info *sta, void *ctx)
263 {
264         if (eapol_auth_eap_pending_cb(sta->eapol_sm, ctx) == 0)
265                 return 1;
266         return 0;
267 }
268
269
270 static void hostapd_sim_db_cb(void *ctx, void *session_ctx)
271 {
272         struct hostapd_data *hapd = ctx;
273         if (ap_for_each_sta(hapd, hostapd_sim_db_cb_sta, session_ctx) == 0)
274                 radius_server_eap_pending_cb(hapd->radius_srv, session_ctx);
275 }
276 #endif /* EAP_SERVER */
277
278
279 static void handle_term(int sig, void *eloop_ctx, void *signal_ctx)
280 {
281         printf("Signal %d received - terminating\n", sig);
282         eloop_terminate();
283 }
284
285
286 static void hostapd_wpa_auth_conf(struct hostapd_bss_config *conf,
287                                   struct wpa_auth_config *wconf)
288 {
289         wconf->wpa = conf->wpa;
290         wconf->wpa_key_mgmt = conf->wpa_key_mgmt;
291         wconf->wpa_pairwise = conf->wpa_pairwise;
292         wconf->wpa_group = conf->wpa_group;
293         wconf->wpa_group_rekey = conf->wpa_group_rekey;
294         wconf->wpa_strict_rekey = conf->wpa_strict_rekey;
295         wconf->wpa_gmk_rekey = conf->wpa_gmk_rekey;
296         wconf->wpa_ptk_rekey = conf->wpa_ptk_rekey;
297         wconf->rsn_pairwise = conf->rsn_pairwise;
298         wconf->rsn_preauth = conf->rsn_preauth;
299         wconf->eapol_version = conf->eapol_version;
300         wconf->peerkey = conf->peerkey;
301         wconf->wme_enabled = conf->wme_enabled;
302         wconf->okc = conf->okc;
303 #ifdef CONFIG_IEEE80211W
304         wconf->ieee80211w = conf->ieee80211w;
305 #endif /* CONFIG_IEEE80211W */
306 #ifdef CONFIG_IEEE80211R
307         wconf->ssid_len = conf->ssid.ssid_len;
308         if (wconf->ssid_len > SSID_LEN)
309                 wconf->ssid_len = SSID_LEN;
310         os_memcpy(wconf->ssid, conf->ssid.ssid, wconf->ssid_len);
311         os_memcpy(wconf->mobility_domain, conf->mobility_domain,
312                   MOBILITY_DOMAIN_ID_LEN);
313         if (conf->nas_identifier &&
314             os_strlen(conf->nas_identifier) <= FT_R0KH_ID_MAX_LEN) {
315                 wconf->r0_key_holder_len = os_strlen(conf->nas_identifier);
316                 os_memcpy(wconf->r0_key_holder, conf->nas_identifier,
317                           wconf->r0_key_holder_len);
318         }
319         os_memcpy(wconf->r1_key_holder, conf->r1_key_holder, FT_R1KH_ID_LEN);
320         wconf->r0_key_lifetime = conf->r0_key_lifetime;
321         wconf->reassociation_deadline = conf->reassociation_deadline;
322         wconf->r0kh_list = conf->r0kh_list;
323         wconf->r1kh_list = conf->r1kh_list;
324         wconf->pmk_r1_push = conf->pmk_r1_push;
325 #endif /* CONFIG_IEEE80211R */
326 }
327
328
329 #ifndef CONFIG_NATIVE_WINDOWS
330 static void handle_reload(int sig, void *eloop_ctx, void *signal_ctx)
331 {
332         struct hapd_interfaces *hapds = (struct hapd_interfaces *) eloop_ctx;
333         struct hostapd_config *newconf;
334         size_t i;
335         struct wpa_auth_config wpa_auth_conf;
336
337         printf("Signal %d received - reloading configuration\n", sig);
338
339         for (i = 0; i < hapds->count; i++) {
340                 struct hostapd_data *hapd = hapds->iface[i]->bss[0];
341                 newconf = hostapd_config_read(hapds->iface[i]->config_fname);
342                 if (newconf == NULL) {
343                         printf("Failed to read new configuration file - "
344                                "continuing with old.\n");
345                         continue;
346                 }
347                 /* TODO: update dynamic data based on changed configuration
348                  * items (e.g., open/close sockets, remove stations added to
349                  * deny list, etc.) */
350                 radius_client_flush(hapd->radius, 0);
351                 hostapd_config_free(hapd->iconf);
352
353                 hostapd_wpa_auth_conf(&newconf->bss[0], &wpa_auth_conf);
354                 wpa_reconfig(hapd->wpa_auth, &wpa_auth_conf);
355
356                 hapd->iconf = newconf;
357                 hapd->conf = &newconf->bss[0];
358                 hapds->iface[i]->conf = newconf;
359
360                 if (hostapd_setup_wpa_psk(hapd->conf)) {
361                         wpa_printf(MSG_ERROR, "Failed to re-configure WPA PSK "
362                                    "after reloading configuration");
363                 }
364         }
365 }
366
367
368 #ifdef HOSTAPD_DUMP_STATE
369 static void hostapd_dump_state(struct hostapd_data *hapd)
370 {
371         FILE *f;
372         time_t now;
373         struct sta_info *sta;
374         int i;
375         char *buf;
376
377         if (!hapd->conf->dump_log_name) {
378                 printf("Dump file not defined - ignoring dump request\n");
379                 return;
380         }
381
382         printf("Dumping hostapd state to '%s'\n", hapd->conf->dump_log_name);
383         f = fopen(hapd->conf->dump_log_name, "w");
384         if (f == NULL) {
385                 printf("Could not open dump file '%s' for writing.\n",
386                        hapd->conf->dump_log_name);
387                 return;
388         }
389
390         time(&now);
391         fprintf(f, "hostapd state dump - %s", ctime(&now));
392         fprintf(f, "num_sta=%d num_sta_non_erp=%d "
393                 "num_sta_no_short_slot_time=%d\n"
394                 "num_sta_no_short_preamble=%d\n",
395                 hapd->num_sta, hapd->iface->num_sta_non_erp,
396                 hapd->iface->num_sta_no_short_slot_time,
397                 hapd->iface->num_sta_no_short_preamble);
398
399         for (sta = hapd->sta_list; sta != NULL; sta = sta->next) {
400                 fprintf(f, "\nSTA=" MACSTR "\n", MAC2STR(sta->addr));
401
402                 fprintf(f,
403                         "  AID=%d flags=0x%x %s%s%s%s%s%s%s%s%s%s%s%s\n"
404                         "  capability=0x%x listen_interval=%d\n",
405                         sta->aid,
406                         sta->flags,
407                         (sta->flags & WLAN_STA_AUTH ? "[AUTH]" : ""),
408                         (sta->flags & WLAN_STA_ASSOC ? "[ASSOC]" : ""),
409                         (sta->flags & WLAN_STA_PS ? "[PS]" : ""),
410                         (sta->flags & WLAN_STA_TIM ? "[TIM]" : ""),
411                         (sta->flags & WLAN_STA_PERM ? "[PERM]" : ""),
412                         (sta->flags & WLAN_STA_AUTHORIZED ? "[AUTHORIZED]" :
413                          ""),
414                         (sta->flags & WLAN_STA_PENDING_POLL ? "[PENDING_POLL" :
415                          ""),
416                         (sta->flags & WLAN_STA_SHORT_PREAMBLE ?
417                          "[SHORT_PREAMBLE]" : ""),
418                         (sta->flags & WLAN_STA_PREAUTH ? "[PREAUTH]" : ""),
419                         (sta->flags & WLAN_STA_WME ? "[WME]" : ""),
420                         (sta->flags & WLAN_STA_MFP ? "[MFP]" : ""),
421                         (sta->flags & WLAN_STA_NONERP ? "[NonERP]" : ""),
422                         sta->capability,
423                         sta->listen_interval);
424
425                 fprintf(f, "  supported_rates=");
426                 for (i = 0; i < sta->supported_rates_len; i++)
427                         fprintf(f, "%02x ", sta->supported_rates[i]);
428                 fprintf(f, "\n");
429
430                 fprintf(f,
431                         "  timeout_next=%s\n",
432                         (sta->timeout_next == STA_NULLFUNC ? "NULLFUNC POLL" :
433                          (sta->timeout_next == STA_DISASSOC ? "DISASSOC" :
434                           "DEAUTH")));
435
436                 ieee802_1x_dump_state(f, "  ", sta);
437         }
438
439         buf = os_malloc(4096);
440         if (buf) {
441                 int count = radius_client_get_mib(hapd->radius, buf, 4096);
442                 if (count < 0)
443                         count = 0;
444                 else if (count > 4095)
445                         count = 4095;
446                 buf[count] = '\0';
447                 fprintf(f, "%s", buf);
448
449                 count = radius_server_get_mib(hapd->radius_srv, buf, 4096);
450                 if (count < 0)
451                         count = 0;
452                 else if (count > 4095)
453                         count = 4095;
454                 buf[count] = '\0';
455                 fprintf(f, "%s", buf);
456                 os_free(buf);
457         }
458         fclose(f);
459 }
460 #endif /* HOSTAPD_DUMP_STATE */
461
462
463 static void handle_dump_state(int sig, void *eloop_ctx, void *signal_ctx)
464 {
465 #ifdef HOSTAPD_DUMP_STATE
466         struct hapd_interfaces *hapds = (struct hapd_interfaces *) eloop_ctx;
467         size_t i, j;
468
469         for (i = 0; i < hapds->count; i++) {
470                 struct hostapd_iface *hapd_iface = hapds->iface[i];
471                 for (j = 0; j < hapd_iface->num_bss; j++)
472                         hostapd_dump_state(hapd_iface->bss[j]);
473         }
474 #endif /* HOSTAPD_DUMP_STATE */
475 }
476 #endif /* CONFIG_NATIVE_WINDOWS */
477
478 static void hostapd_broadcast_key_clear_iface(struct hostapd_data *hapd,
479                                               char *ifname)
480 {
481         int i;
482
483         for (i = 0; i < NUM_WEP_KEYS; i++) {
484                 if (hostapd_set_encryption(ifname, hapd, "none", NULL, i, NULL,
485                                            0, i == 0 ? 1 : 0)) {
486                         printf("Failed to clear default encryption keys "
487                                "(ifname=%s keyidx=%d)\n", ifname, i);
488                 }
489         }
490 }
491
492
493 static int hostapd_broadcast_wep_clear(struct hostapd_data *hapd)
494 {
495         hostapd_broadcast_key_clear_iface(hapd, hapd->conf->iface);
496         return 0;
497 }
498
499
500 static int hostapd_broadcast_wep_set(struct hostapd_data *hapd)
501 {
502         int errors = 0, idx;
503         struct hostapd_ssid *ssid = &hapd->conf->ssid;
504
505         idx = ssid->wep.idx;
506         if (ssid->wep.default_len &&
507             hostapd_set_encryption(hapd->conf->iface,
508                                    hapd, "WEP", NULL, idx,
509                                    ssid->wep.key[idx],
510                                    ssid->wep.len[idx],
511                                    idx == ssid->wep.idx)) {
512                 printf("Could not set WEP encryption.\n");
513                 errors++;
514         }
515
516         if (ssid->dyn_vlan_keys) {
517                 size_t i;
518                 for (i = 0; i <= ssid->max_dyn_vlan_keys; i++) {
519                         const char *ifname;
520                         struct hostapd_wep_keys *key = ssid->dyn_vlan_keys[i];
521                         if (key == NULL)
522                                 continue;
523                         ifname = hostapd_get_vlan_id_ifname(hapd->conf->vlan,
524                                                             i);
525                         if (ifname == NULL)
526                                 continue;
527
528                         idx = key->idx;
529                         if (hostapd_set_encryption(ifname, hapd, "WEP", NULL,
530                                                    idx, key->key[idx],
531                                                    key->len[idx],
532                                                    idx == key->idx)) {
533                                 printf("Could not set dynamic VLAN WEP "
534                                        "encryption.\n");
535                                 errors++;
536                         }
537                 }
538         }
539
540         return errors;
541 }
542
543 /**
544  * hostapd_cleanup - Per-BSS cleanup (deinitialization)
545  * @hapd: Pointer to BSS data
546  *
547  * This function is used to free all per-BSS data structures and resources.
548  * This gets called in a loop for each BSS between calls to
549  * hostapd_cleanup_iface_pre() and hostapd_cleanup_iface() when an interface
550  * is deinitialized. Most of the modules that are initialized in
551  * hostapd_setup_bss() are deinitialized here.
552  */
553 static void hostapd_cleanup(struct hostapd_data *hapd)
554 {
555         hostapd_ctrl_iface_deinit(hapd);
556
557         os_free(hapd->default_wep_key);
558         hapd->default_wep_key = NULL;
559         iapp_deinit(hapd->iapp);
560         hapd->iapp = NULL;
561         accounting_deinit(hapd);
562         rsn_preauth_iface_deinit(hapd);
563         if (hapd->wpa_auth) {
564                 wpa_deinit(hapd->wpa_auth);
565                 hapd->wpa_auth = NULL;
566
567                 if (hostapd_set_privacy(hapd, 0)) {
568                         wpa_printf(MSG_DEBUG, "Could not disable "
569                                    "PrivacyInvoked for interface %s",
570                                    hapd->conf->iface);
571                 }
572
573                 if (hostapd_set_generic_elem(hapd, (u8 *) "", 0)) {
574                         wpa_printf(MSG_DEBUG, "Could not remove generic "
575                                    "information element from interface %s",
576                                    hapd->conf->iface);
577                 }
578         }
579         ieee802_1x_deinit(hapd);
580         vlan_deinit(hapd);
581         hostapd_acl_deinit(hapd);
582         radius_client_deinit(hapd->radius);
583         hapd->radius = NULL;
584         radius_server_deinit(hapd->radius_srv);
585         hapd->radius_srv = NULL;
586
587 #ifdef CONFIG_IEEE80211R
588         l2_packet_deinit(hapd->l2);
589 #endif /* CONFIG_IEEE80211R */
590
591         hostapd_wireless_event_deinit(hapd);
592
593 #ifdef EAP_TLS_FUNCS
594         if (hapd->ssl_ctx) {
595                 tls_deinit(hapd->ssl_ctx);
596                 hapd->ssl_ctx = NULL;
597         }
598 #endif /* EAP_TLS_FUNCS */
599
600 #ifdef EAP_SERVER
601         if (hapd->eap_sim_db_priv) {
602                 eap_sim_db_deinit(hapd->eap_sim_db_priv);
603                 hapd->eap_sim_db_priv = NULL;
604         }
605 #endif /* EAP_SERVER */
606
607         if (hapd->interface_added &&
608             hostapd_bss_remove(hapd, hapd->conf->iface)) {
609                 printf("Failed to remove BSS interface %s\n",
610                        hapd->conf->iface);
611         }
612 }
613
614
615 /**
616  * hostapd_cleanup_iface_pre - Preliminary per-interface cleanup
617  * @iface: Pointer to interface data
618  *
619  * This function is called before per-BSS data structures are deinitialized
620  * with hostapd_cleanup().
621  */
622 static void hostapd_cleanup_iface_pre(struct hostapd_iface *iface)
623 {
624 }
625
626
627 /**
628  * hostapd_cleanup_iface - Complete per-interface cleanup
629  * @iface: Pointer to interface data
630  *
631  * This function is called after per-BSS data structures are deinitialized
632  * with hostapd_cleanup().
633  */
634 static void hostapd_cleanup_iface(struct hostapd_iface *iface)
635 {
636         hostapd_free_hw_features(iface->hw_features, iface->num_hw_features);
637         iface->hw_features = NULL;
638         os_free(iface->current_rates);
639         iface->current_rates = NULL;
640         ap_list_deinit(iface);
641         hostapd_config_free(iface->conf);
642         iface->conf = NULL;
643
644         os_free(iface->config_fname);
645         os_free(iface->bss);
646         os_free(iface);
647 }
648
649
650 static int hostapd_setup_encryption(char *iface, struct hostapd_data *hapd)
651 {
652         int i;
653
654         hostapd_broadcast_wep_set(hapd);
655
656         if (hapd->conf->ssid.wep.default_len)
657                 return 0;
658
659         for (i = 0; i < 4; i++) {
660                 if (hapd->conf->ssid.wep.key[i] &&
661                     hostapd_set_encryption(iface, hapd, "WEP", NULL,
662                                            i, hapd->conf->ssid.wep.key[i],
663                                            hapd->conf->ssid.wep.len[i],
664                                            i == hapd->conf->ssid.wep.idx)) {
665                         printf("Could not set WEP encryption.\n");
666                         return -1;
667                 }
668                 if (hapd->conf->ssid.wep.key[i] &&
669                     i == hapd->conf->ssid.wep.idx)
670                         hostapd_set_privacy(hapd, 1);
671         }
672
673         return 0;
674 }
675
676
677 static int hostapd_flush_old_stations(struct hostapd_data *hapd)
678 {
679         int ret = 0;
680
681         if (hostapd_drv_none(hapd))
682                 return 0;
683
684         wpa_printf(MSG_DEBUG, "Flushing old station entries");
685         if (hostapd_flush(hapd)) {
686                 printf("Could not connect to kernel driver.\n");
687                 ret = -1;
688         }
689         wpa_printf(MSG_DEBUG, "Deauthenticate all stations");
690         hostapd_deauth_all_stas(hapd);
691
692         return ret;
693 }
694
695
696 static void hostapd_wpa_auth_logger(void *ctx, const u8 *addr,
697                                     logger_level level, const char *txt)
698 {
699         struct hostapd_data *hapd = ctx;
700         int hlevel;
701
702         switch (level) {
703         case LOGGER_WARNING:
704                 hlevel = HOSTAPD_LEVEL_WARNING;
705                 break;
706         case LOGGER_INFO:
707                 hlevel = HOSTAPD_LEVEL_INFO;
708                 break;
709         case LOGGER_DEBUG:
710         default:
711                 hlevel = HOSTAPD_LEVEL_DEBUG;
712                 break;
713         }
714
715         hostapd_logger(hapd, addr, HOSTAPD_MODULE_WPA, hlevel, "%s", txt);
716 }
717
718
719 static void hostapd_wpa_auth_disconnect(void *ctx, const u8 *addr,
720                                         u16 reason)
721 {
722         struct hostapd_data *hapd = ctx;
723         struct sta_info *sta;
724
725         wpa_printf(MSG_DEBUG, "%s: WPA authenticator requests disconnect: "
726                    "STA " MACSTR " reason %d",
727                    __func__, MAC2STR(addr), reason);
728
729         sta = ap_get_sta(hapd, addr);
730         hostapd_sta_deauth(hapd, addr, reason);
731         if (sta == NULL)
732                 return;
733         sta->flags &= ~(WLAN_STA_AUTH | WLAN_STA_ASSOC | WLAN_STA_AUTHORIZED);
734         eloop_cancel_timeout(ap_handle_timer, hapd, sta);
735         eloop_register_timeout(0, 0, ap_handle_timer, hapd, sta);
736         sta->timeout_next = STA_REMOVE;
737 }
738
739
740 static void hostapd_wpa_auth_mic_failure_report(void *ctx, const u8 *addr)
741 {
742         struct hostapd_data *hapd = ctx;
743         ieee80211_michael_mic_failure(hapd, addr, 0);
744 }
745
746
747 static void hostapd_wpa_auth_set_eapol(void *ctx, const u8 *addr,
748                                        wpa_eapol_variable var, int value)
749 {
750         struct hostapd_data *hapd = ctx;
751         struct sta_info *sta = ap_get_sta(hapd, addr);
752         if (sta == NULL)
753                 return;
754         switch (var) {
755         case WPA_EAPOL_portEnabled:
756                 ieee802_1x_notify_port_enabled(sta->eapol_sm, value);
757                 break;
758         case WPA_EAPOL_portValid:
759                 ieee802_1x_notify_port_valid(sta->eapol_sm, value);
760                 break;
761         case WPA_EAPOL_authorized:
762                 ieee802_1x_set_sta_authorized(hapd, sta, value);
763                 break;
764         case WPA_EAPOL_portControl_Auto:
765                 if (sta->eapol_sm)
766                         sta->eapol_sm->portControl = Auto;
767                 break;
768         case WPA_EAPOL_keyRun:
769                 if (sta->eapol_sm)
770                         sta->eapol_sm->keyRun = value ? TRUE : FALSE;
771                 break;
772         case WPA_EAPOL_keyAvailable:
773                 if (sta->eapol_sm)
774                         sta->eapol_sm->eap_if->eapKeyAvailable =
775                                 value ? TRUE : FALSE;
776                 break;
777         case WPA_EAPOL_keyDone:
778                 if (sta->eapol_sm)
779                         sta->eapol_sm->keyDone = value ? TRUE : FALSE;
780                 break;
781         case WPA_EAPOL_inc_EapolFramesTx:
782                 if (sta->eapol_sm)
783                         sta->eapol_sm->dot1xAuthEapolFramesTx++;
784                 break;
785         }
786 }
787
788
789 static int hostapd_wpa_auth_get_eapol(void *ctx, const u8 *addr,
790                                       wpa_eapol_variable var)
791 {
792         struct hostapd_data *hapd = ctx;
793         struct sta_info *sta = ap_get_sta(hapd, addr);
794         if (sta == NULL || sta->eapol_sm == NULL)
795                 return -1;
796         switch (var) {
797         case WPA_EAPOL_keyRun:
798                 return sta->eapol_sm->keyRun;
799         case WPA_EAPOL_keyAvailable:
800                 return sta->eapol_sm->eap_if->eapKeyAvailable;
801         default:
802                 return -1;
803         }
804 }
805
806
807 static const u8 * hostapd_wpa_auth_get_psk(void *ctx, const u8 *addr,
808                                            const u8 *prev_psk)
809 {
810         struct hostapd_data *hapd = ctx;
811         return hostapd_get_psk(hapd->conf, addr, prev_psk);
812 }
813
814
815 static int hostapd_wpa_auth_get_msk(void *ctx, const u8 *addr, u8 *msk,
816                                     size_t *len)
817 {
818         struct hostapd_data *hapd = ctx;
819         const u8 *key;
820         size_t keylen;
821         struct sta_info *sta;
822
823         sta = ap_get_sta(hapd, addr);
824         if (sta == NULL)
825                 return -1;
826
827         key = ieee802_1x_get_key(sta->eapol_sm, &keylen);
828         if (key == NULL)
829                 return -1;
830
831         if (keylen > *len)
832                 keylen = *len;
833         os_memcpy(msk, key, keylen);
834         *len = keylen;
835
836         return 0;
837 }
838
839
840 static int hostapd_wpa_auth_set_key(void *ctx, int vlan_id, const char *alg,
841                                     const u8 *addr, int idx, u8 *key,
842                                     size_t key_len)
843 {
844         struct hostapd_data *hapd = ctx;
845         const char *ifname = hapd->conf->iface;
846
847         if (vlan_id > 0) {
848                 ifname = hostapd_get_vlan_id_ifname(hapd->conf->vlan, vlan_id);
849                 if (ifname == NULL)
850                         return -1;
851         }
852
853         return hostapd_set_encryption(ifname, hapd, alg, addr, idx,
854                                       key, key_len, 1);
855 }
856
857
858 static int hostapd_wpa_auth_get_seqnum(void *ctx, const u8 *addr, int idx,
859                                        u8 *seq)
860 {
861         struct hostapd_data *hapd = ctx;
862         return hostapd_get_seqnum(hapd->conf->iface, hapd, addr, idx, seq);
863 }
864
865
866 static int hostapd_wpa_auth_get_seqnum_igtk(void *ctx, const u8 *addr, int idx,
867                                             u8 *seq)
868 {
869         struct hostapd_data *hapd = ctx;
870         return hostapd_get_seqnum_igtk(hapd->conf->iface, hapd, addr, idx,
871                                        seq);
872 }
873
874
875 static int hostapd_wpa_auth_send_eapol(void *ctx, const u8 *addr,
876                                        const u8 *data, size_t data_len,
877                                        int encrypt)
878 {
879         struct hostapd_data *hapd = ctx;
880         return hostapd_send_eapol(hapd, addr, data, data_len, encrypt);
881 }
882
883
884 static int hostapd_wpa_auth_for_each_sta(
885         void *ctx, int (*cb)(struct wpa_state_machine *sm, void *ctx),
886         void *cb_ctx)
887 {
888         struct hostapd_data *hapd = ctx;
889         struct sta_info *sta;
890
891         for (sta = hapd->sta_list; sta; sta = sta->next) {
892                 if (sta->wpa_sm && cb(sta->wpa_sm, cb_ctx))
893                         return 1;
894         }
895         return 0;
896 }
897
898
899 static int hostapd_wpa_auth_for_each_auth(
900         void *ctx, int (*cb)(struct wpa_authenticator *sm, void *ctx),
901         void *cb_ctx)
902 {
903         struct hostapd_data *ohapd;
904         size_t i, j;
905         struct hapd_interfaces *interfaces = eloop_get_user_data();
906
907         for (i = 0; i < interfaces->count; i++) {
908                 for (j = 0; j < interfaces->iface[i]->num_bss; j++) {
909                         ohapd = interfaces->iface[i]->bss[j];
910                         if (cb(ohapd->wpa_auth, cb_ctx))
911                                 return 1;
912                 }
913         }
914
915         return 0;
916 }
917
918
919 static int hostapd_wpa_auth_send_ether(void *ctx, const u8 *dst, u16 proto,
920                                        const u8 *data, size_t data_len)
921 {
922         struct hostapd_data *hapd = ctx;
923
924         if (hapd->driver && hapd->driver->send_ether)
925                 return hapd->driver->send_ether(hapd->drv_priv, dst,
926                                                 hapd->own_addr, proto,
927                                                 data, data_len);
928         if (hapd->l2 == NULL)
929                 return -1;
930         return l2_packet_send(hapd->l2, dst, proto, data, data_len);
931 }
932
933
934 #ifdef CONFIG_IEEE80211R
935
936 static int hostapd_wpa_auth_send_ft_action(void *ctx, const u8 *dst,
937                                            const u8 *data, size_t data_len)
938 {
939         struct hostapd_data *hapd = ctx;
940         int res;
941         struct ieee80211_mgmt *m;
942         size_t mlen;
943         struct sta_info *sta;
944
945         sta = ap_get_sta(hapd, dst);
946         if (sta == NULL || sta->wpa_sm == NULL)
947                 return -1;
948
949         m = os_zalloc(sizeof(*m) + data_len);
950         if (m == NULL)
951                 return -1;
952         mlen = ((u8 *) &m->u - (u8 *) m) + data_len;
953         m->frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
954                                         WLAN_FC_STYPE_ACTION);
955         os_memcpy(m->da, dst, ETH_ALEN);
956         os_memcpy(m->sa, hapd->own_addr, ETH_ALEN);
957         os_memcpy(m->bssid, hapd->own_addr, ETH_ALEN);
958         os_memcpy(&m->u, data, data_len);
959
960         res = hostapd_send_mgmt_frame(hapd, (u8 *) m, mlen, 0);
961         os_free(m);
962         return res;
963 }
964
965
966 static struct wpa_state_machine *
967 hostapd_wpa_auth_add_sta(void *ctx, const u8 *sta_addr)
968 {
969         struct hostapd_data *hapd = ctx;
970         struct sta_info *sta;
971
972         sta = ap_sta_add(hapd, sta_addr);
973         if (sta == NULL)
974                 return NULL;
975         if (sta->wpa_sm)
976                 return sta->wpa_sm;
977
978         sta->wpa_sm = wpa_auth_sta_init(hapd->wpa_auth, sta->addr);
979         if (sta->wpa_sm == NULL) {
980                 ap_free_sta(hapd, sta);
981                 return NULL;
982         }
983         sta->auth_alg = WLAN_AUTH_FT;
984
985         return sta->wpa_sm;
986 }
987
988
989 static void hostapd_rrb_receive(void *ctx, const u8 *src_addr, const u8 *buf,
990                                 size_t len)
991 {
992         struct hostapd_data *hapd = ctx;
993         wpa_ft_rrb_rx(hapd->wpa_auth, src_addr, buf, len);
994 }
995
996 #endif /* CONFIG_IEEE80211R */
997
998
999 /**
1000  * hostapd_validate_bssid_configuration - Validate BSSID configuration
1001  * @iface: Pointer to interface data
1002  * Returns: 0 on success, -1 on failure
1003  *
1004  * This function is used to validate that the configured BSSIDs are valid.
1005  */
1006 static int hostapd_validate_bssid_configuration(struct hostapd_iface *iface)
1007 {
1008         u8 mask[ETH_ALEN] = { 0 };
1009         struct hostapd_data *hapd = iface->bss[0];
1010         unsigned int i = iface->conf->num_bss, bits = 0, j;
1011         int res;
1012
1013         if (hostapd_drv_none(hapd))
1014                 return 0;
1015
1016         /* Generate BSSID mask that is large enough to cover the BSSIDs. */
1017
1018         /* Determine the bits necessary to cover the number of BSSIDs. */
1019         for (i--; i; i >>= 1)
1020                 bits++;
1021
1022         /* Determine the bits necessary to any configured BSSIDs,
1023            if they are higher than the number of BSSIDs. */
1024         for (j = 0; j < iface->conf->num_bss; j++) {
1025                 if (hostapd_mac_comp_empty(iface->conf->bss[j].bssid) == 0)
1026                         continue;
1027
1028                 for (i = 0; i < ETH_ALEN; i++) {
1029                         mask[i] |=
1030                                 iface->conf->bss[j].bssid[i] ^
1031                                 hapd->own_addr[i];
1032                 }
1033         }
1034
1035         for (i = 0; i < ETH_ALEN && mask[i] == 0; i++)
1036                 ;
1037         j = 0;
1038         if (i < ETH_ALEN) {
1039                 j = (5 - i) * 8;
1040
1041                 while (mask[i] != 0) {
1042                         mask[i] >>= 1;
1043                         j++;
1044                 }
1045         }
1046
1047         if (bits < j)
1048                 bits = j;
1049
1050         if (bits > 40)
1051                 return -1;
1052
1053         os_memset(mask, 0xff, ETH_ALEN);
1054         j = bits / 8;
1055         for (i = 5; i > 5 - j; i--)
1056                 mask[i] = 0;
1057         j = bits % 8;
1058         while (j--)
1059                 mask[i] <<= 1;
1060
1061         wpa_printf(MSG_DEBUG, "BSS count %lu, BSSID mask " MACSTR " (%d bits)",
1062                    (unsigned long) iface->conf->num_bss, MAC2STR(mask), bits);
1063
1064         res = hostapd_valid_bss_mask(hapd, hapd->own_addr, mask);
1065         if (res == 0)
1066                 return 0;
1067
1068         if (res < 0) {
1069                 printf("Driver did not accept BSSID mask " MACSTR " for start "
1070                        "address " MACSTR ".\n",
1071                        MAC2STR(mask), MAC2STR(hapd->own_addr));
1072                 return -1;
1073         }
1074
1075         for (i = 0; i < ETH_ALEN; i++) {
1076                 if ((hapd->own_addr[i] & mask[i]) != hapd->own_addr[i]) {
1077                         printf("Invalid BSSID mask " MACSTR " for start "
1078                                "address " MACSTR ".\n"
1079                                "Start address must be the first address in the"
1080                                " block (i.e., addr AND mask == addr).\n",
1081                                MAC2STR(mask), MAC2STR(hapd->own_addr));
1082                         return -1;
1083                 }
1084         }
1085
1086         return 0;
1087 }
1088
1089
1090 static int mac_in_conf(struct hostapd_config *conf, const void *a)
1091 {
1092         size_t i;
1093
1094         for (i = 0; i < conf->num_bss; i++) {
1095                 if (hostapd_mac_comp(conf->bss[i].bssid, a) == 0) {
1096                         return 1;
1097                 }
1098         }
1099
1100         return 0;
1101 }
1102
1103
1104 static int hostapd_setup_wpa(struct hostapd_data *hapd)
1105 {
1106         struct wpa_auth_config _conf;
1107         struct wpa_auth_callbacks cb;
1108         const u8 *wpa_ie;
1109         size_t wpa_ie_len;
1110
1111         hostapd_wpa_auth_conf(hapd->conf, &_conf);
1112         os_memset(&cb, 0, sizeof(cb));
1113         cb.ctx = hapd;
1114         cb.logger = hostapd_wpa_auth_logger;
1115         cb.disconnect = hostapd_wpa_auth_disconnect;
1116         cb.mic_failure_report = hostapd_wpa_auth_mic_failure_report;
1117         cb.set_eapol = hostapd_wpa_auth_set_eapol;
1118         cb.get_eapol = hostapd_wpa_auth_get_eapol;
1119         cb.get_psk = hostapd_wpa_auth_get_psk;
1120         cb.get_msk = hostapd_wpa_auth_get_msk;
1121         cb.set_key = hostapd_wpa_auth_set_key;
1122         cb.get_seqnum = hostapd_wpa_auth_get_seqnum;
1123         cb.get_seqnum_igtk = hostapd_wpa_auth_get_seqnum_igtk;
1124         cb.send_eapol = hostapd_wpa_auth_send_eapol;
1125         cb.for_each_sta = hostapd_wpa_auth_for_each_sta;
1126         cb.for_each_auth = hostapd_wpa_auth_for_each_auth;
1127         cb.send_ether = hostapd_wpa_auth_send_ether;
1128 #ifdef CONFIG_IEEE80211R
1129         cb.send_ft_action = hostapd_wpa_auth_send_ft_action;
1130         cb.add_sta = hostapd_wpa_auth_add_sta;
1131 #endif /* CONFIG_IEEE80211R */
1132         hapd->wpa_auth = wpa_init(hapd->own_addr, &_conf, &cb);
1133         if (hapd->wpa_auth == NULL) {
1134                 printf("WPA initialization failed.\n");
1135                 return -1;
1136         }
1137
1138         if (hostapd_set_privacy(hapd, 1)) {
1139                 wpa_printf(MSG_ERROR, "Could not set PrivacyInvoked "
1140                            "for interface %s", hapd->conf->iface);
1141                 return -1;
1142         }
1143
1144         wpa_ie = wpa_auth_get_wpa_ie(hapd->wpa_auth, &wpa_ie_len);
1145         if (hostapd_set_generic_elem(hapd, wpa_ie, wpa_ie_len)) {
1146                 wpa_printf(MSG_ERROR, "Failed to configure WPA IE for "
1147                            "the kernel driver.");
1148                 return -1;
1149         }
1150
1151         if (rsn_preauth_iface_init(hapd)) {
1152                 printf("Initialization of RSN pre-authentication "
1153                        "failed.\n");
1154                 return -1;
1155         }
1156
1157         return 0;
1158
1159 }
1160
1161
1162 static int hostapd_setup_radius_srv(struct hostapd_data *hapd,
1163                                     struct hostapd_bss_config *conf)
1164 {
1165         struct radius_server_conf srv;
1166         os_memset(&srv, 0, sizeof(srv));
1167         srv.client_file = conf->radius_server_clients;
1168         srv.auth_port = conf->radius_server_auth_port;
1169         srv.conf_ctx = conf;
1170         srv.eap_sim_db_priv = hapd->eap_sim_db_priv;
1171         srv.ssl_ctx = hapd->ssl_ctx;
1172         srv.pac_opaque_encr_key = conf->pac_opaque_encr_key;
1173         srv.eap_fast_a_id = conf->eap_fast_a_id;
1174         srv.eap_fast_a_id_len = conf->eap_fast_a_id_len;
1175         srv.eap_fast_a_id_info = conf->eap_fast_a_id_info;
1176         srv.eap_fast_prov = conf->eap_fast_prov;
1177         srv.pac_key_lifetime = conf->pac_key_lifetime;
1178         srv.pac_key_refresh_time = conf->pac_key_refresh_time;
1179         srv.eap_sim_aka_result_ind = conf->eap_sim_aka_result_ind;
1180         srv.tnc = conf->tnc;
1181         srv.ipv6 = conf->radius_server_ipv6;
1182         srv.get_eap_user = hostapd_radius_get_eap_user;
1183
1184         hapd->radius_srv = radius_server_init(&srv);
1185         if (hapd->radius_srv == NULL) {
1186                 printf("RADIUS server initialization failed.\n");
1187                 return -1;
1188         }
1189
1190         return 0;
1191 }
1192
1193
1194 /**
1195  * hostapd_setup_bss - Per-BSS setup (initialization)
1196  * @hapd: Pointer to BSS data
1197  * @first: Whether this BSS is the first BSS of an interface
1198  *
1199  * This function is used to initialize all per-BSS data structures and
1200  * resources. This gets called in a loop for each BSS when an interface is
1201  * initialized. Most of the modules that are initialized here will be
1202  * deinitialized in hostapd_cleanup().
1203  */
1204 static int hostapd_setup_bss(struct hostapd_data *hapd, int first)
1205 {
1206         struct hostapd_bss_config *conf = hapd->conf;
1207         u8 ssid[HOSTAPD_MAX_SSID_LEN + 1];
1208         int ssid_len, set_ssid;
1209
1210         if (!first) {
1211                 if (hostapd_mac_comp_empty(hapd->conf->bssid) == 0) {
1212                         /* Allocate the next available BSSID. */
1213                         do {
1214                                 inc_byte_array(hapd->own_addr, ETH_ALEN);
1215                         } while (mac_in_conf(hapd->iconf, hapd->own_addr));
1216                 } else {
1217                         /* Allocate the configured BSSID. */
1218                         os_memcpy(hapd->own_addr, hapd->conf->bssid, ETH_ALEN);
1219
1220                         if (hostapd_mac_comp(hapd->own_addr,
1221                                              hapd->iface->bss[0]->own_addr) ==
1222                             0) {
1223                                 printf("BSS '%s' may not have BSSID "
1224                                        "set to the MAC address of the radio\n",
1225                                        hapd->conf->iface);
1226                                 return -1;
1227                         }
1228                 }
1229
1230                 hapd->interface_added = 1;
1231                 if (hostapd_bss_add(hapd->iface->bss[0], hapd->conf->iface,
1232                                     hapd->own_addr)) {
1233                         printf("Failed to add BSS (BSSID=" MACSTR ")\n",
1234                                MAC2STR(hapd->own_addr));
1235                         return -1;
1236                 }
1237         }
1238
1239         /*
1240          * Fetch the SSID from the system and use it or,
1241          * if one was specified in the config file, verify they
1242          * match.
1243          */
1244         ssid_len = hostapd_get_ssid(hapd, ssid, sizeof(ssid));
1245         if (ssid_len < 0) {
1246                 printf("Could not read SSID from system\n");
1247                 return -1;
1248         }
1249         if (conf->ssid.ssid_set) {
1250                 /*
1251                  * If SSID is specified in the config file and it differs
1252                  * from what is being used then force installation of the
1253                  * new SSID.
1254                  */
1255                 set_ssid = (conf->ssid.ssid_len != (size_t) ssid_len ||
1256                             os_memcmp(conf->ssid.ssid, ssid, ssid_len) != 0);
1257         } else {
1258                 /*
1259                  * No SSID in the config file; just use the one we got
1260                  * from the system.
1261                  */
1262                 set_ssid = 0;
1263                 conf->ssid.ssid_len = ssid_len;
1264                 os_memcpy(conf->ssid.ssid, ssid, conf->ssid.ssid_len);
1265                 conf->ssid.ssid[conf->ssid.ssid_len] = '\0';
1266         }
1267
1268         if (!hostapd_drv_none(hapd)) {
1269                 printf("Using interface %s with hwaddr " MACSTR
1270                        " and ssid '%s'\n",
1271                        hapd->conf->iface, MAC2STR(hapd->own_addr),
1272                        hapd->conf->ssid.ssid);
1273         }
1274
1275         if (hostapd_setup_wpa_psk(conf)) {
1276                 printf("WPA-PSK setup failed.\n");
1277                 return -1;
1278         }
1279
1280         /* Set flag for whether SSID is broadcast in beacons */
1281         if (hostapd_set_broadcast_ssid(hapd,
1282                                        !!hapd->conf->ignore_broadcast_ssid)) {
1283                 printf("Could not set broadcast SSID flag for kernel "
1284                        "driver\n");
1285                 return -1;
1286         }
1287
1288         if (hostapd_set_dtim_period(hapd, hapd->conf->dtim_period)) {
1289                 printf("Could not set DTIM period for kernel driver\n");
1290                 return -1;
1291         }
1292
1293         /* Set SSID for the kernel driver (to be used in beacon and probe
1294          * response frames) */
1295         if (set_ssid && hostapd_set_ssid(hapd, (u8 *) conf->ssid.ssid,
1296                                          conf->ssid.ssid_len)) {
1297                 printf("Could not set SSID for kernel driver\n");
1298                 return -1;
1299         }
1300
1301         if (wpa_debug_level == MSG_MSGDUMP)
1302                 conf->radius->msg_dumps = 1;
1303         hapd->radius = radius_client_init(hapd, conf->radius);
1304         if (hapd->radius == NULL) {
1305                 printf("RADIUS client initialization failed.\n");
1306                 return -1;
1307         }
1308
1309         if (hostapd_acl_init(hapd)) {
1310                 printf("ACL initialization failed.\n");
1311                 return -1;
1312         }
1313
1314         if (ieee802_1x_init(hapd)) {
1315                 printf("IEEE 802.1X initialization failed.\n");
1316                 return -1;
1317         }
1318
1319         if (hapd->conf->wpa && hostapd_setup_wpa(hapd))
1320                 return -1;
1321
1322         if (accounting_init(hapd)) {
1323                 printf("Accounting initialization failed.\n");
1324                 return -1;
1325         }
1326
1327         if (hapd->conf->ieee802_11f &&
1328             (hapd->iapp = iapp_init(hapd, hapd->conf->iapp_iface)) == NULL) {
1329                 printf("IEEE 802.11F (IAPP) initialization failed.\n");
1330                 return -1;
1331         }
1332
1333         if (hostapd_ctrl_iface_init(hapd)) {
1334                 printf("Failed to setup control interface\n");
1335                 return -1;
1336         }
1337
1338         if (!hostapd_drv_none(hapd) && vlan_init(hapd)) {
1339                 printf("VLAN initialization failed.\n");
1340                 return -1;
1341         }
1342
1343 #ifdef CONFIG_IEEE80211R
1344         if (!hostapd_drv_none(hapd)) {
1345                 hapd->l2 = l2_packet_init(hapd->conf->iface, NULL, ETH_P_RRB,
1346                                           hostapd_rrb_receive, hapd, 0);
1347                 if (hapd->l2 == NULL &&
1348                     (hapd->driver == NULL ||
1349                      hapd->driver->send_ether == NULL)) {
1350                         printf("Failed to open l2_packet interface\n");
1351                         return -1;
1352                 }
1353         }
1354 #endif /* CONFIG_IEEE80211R */
1355
1356         ieee802_11_set_beacon(hapd);
1357
1358         if (conf->radius_server_clients &&
1359             hostapd_setup_radius_srv(hapd, conf))
1360                 return -1;
1361
1362         return 0;
1363 }
1364
1365
1366 static void hostapd_tx_queue_params(struct hostapd_iface *iface)
1367 {
1368         struct hostapd_data *hapd = iface->bss[0];
1369         int i;
1370         struct hostapd_tx_queue_params *p;
1371
1372         for (i = 0; i < NUM_TX_QUEUES; i++) {
1373                 p = &iface->conf->tx_queue[i];
1374
1375                 if (!p->configured)
1376                         continue;
1377
1378                 if (hostapd_set_tx_queue_params(hapd, i, p->aifs, p->cwmin,
1379                                                 p->cwmax, p->burst)) {
1380                         printf("Failed to set TX queue parameters for queue %d"
1381                                ".\n", i);
1382                         /* Continue anyway */
1383                 }
1384         }
1385 }
1386
1387
1388 /**
1389  * setup_interface2 - Setup (initialize) an interface (part 2)
1390  * @iface: Pointer to interface data.
1391  * Returns: 0 on success; -1 on failure.
1392  *
1393  * Flushes old stations, sets the channel, DFS parameters, encryption,
1394  * beacons, and WDS links based on the configuration.
1395  */
1396 static int setup_interface2(struct hostapd_iface *iface)
1397 {
1398         struct hostapd_data *hapd = iface->bss[0];
1399         int freq;
1400         size_t j;
1401         int ret = 0;
1402         u8 *prev_addr;
1403
1404         hostapd_flush_old_stations(hapd);
1405         hostapd_set_privacy(hapd, 0);
1406
1407         if (hapd->iconf->channel) {
1408                 freq = hostapd_hw_get_freq(hapd, hapd->iconf->channel);
1409                 printf("Mode: %s  Channel: %d  Frequency: %d MHz\n",
1410                        hostapd_hw_mode_txt(hapd->iconf->hw_mode),
1411                        hapd->iconf->channel, freq);
1412
1413                 if (hostapd_set_freq(hapd, hapd->iconf->hw_mode, freq)) {
1414                         printf("Could not set channel for kernel driver\n");
1415                         return -1;
1416                 }
1417         }
1418
1419         hostapd_broadcast_wep_clear(hapd);
1420         if (hostapd_setup_encryption(hapd->conf->iface, hapd))
1421                 return -1;
1422
1423         hostapd_set_beacon_int(hapd, hapd->iconf->beacon_int);
1424         ieee802_11_set_beacon(hapd);
1425
1426         if (hapd->iconf->rts_threshold > -1 &&
1427             hostapd_set_rts(hapd, hapd->iconf->rts_threshold)) {
1428                 printf("Could not set RTS threshold for kernel driver\n");
1429                 return -1;
1430         }
1431
1432         if (hapd->iconf->fragm_threshold > -1 &&
1433             hostapd_set_frag(hapd, hapd->iconf->fragm_threshold)) {
1434                 printf("Could not set fragmentation threshold for kernel "
1435                        "driver\n");
1436                 return -1;
1437         }
1438
1439         prev_addr = hapd->own_addr;
1440
1441         for (j = 0; j < iface->num_bss; j++) {
1442                 hapd = iface->bss[j];
1443                 if (j)
1444                         os_memcpy(hapd->own_addr, prev_addr, ETH_ALEN);
1445                 if (hostapd_setup_bss(hapd, j == 0))
1446                         return -1;
1447                 if (hostapd_mac_comp_empty(hapd->conf->bssid) == 0)
1448                         prev_addr = hapd->own_addr;
1449         }
1450
1451         hostapd_tx_queue_params(iface);
1452
1453         ap_list_init(iface);
1454
1455         if (hostapd_driver_commit(hapd) < 0) {
1456                 wpa_printf(MSG_ERROR, "%s: Failed to commit driver "
1457                            "configuration", __func__);
1458                 return -1;
1459         }
1460
1461         return ret;
1462 }
1463
1464
1465 static void setup_interface_start(void *eloop_data, void *user_ctx);
1466 static void setup_interface2_handler(void *eloop_data, void *user_ctx);
1467
1468 /**
1469  * setup_interface_finalize - Finish setup interface & call the callback
1470  * @iface: Pointer to interface data.
1471  * @status: Status of the setup interface (0 on success; -1 on failure).
1472  * Returns: 0 on success; -1 on failure (e.g., was not in progress).
1473  */
1474 static int setup_interface_finalize(struct hostapd_iface *iface, int status)
1475 {
1476         hostapd_iface_cb cb;
1477
1478         if (!iface->setup_cb)
1479                 return -1;
1480         
1481         eloop_cancel_timeout(setup_interface_start, iface, NULL);
1482         eloop_cancel_timeout(setup_interface2_handler, iface, NULL);
1483         hostapd_select_hw_mode_stop(iface);
1484
1485         cb = iface->setup_cb;
1486
1487         iface->setup_cb = NULL;
1488
1489         cb(iface, status);
1490
1491         return 0;
1492 }
1493
1494
1495 /**
1496  * setup_interface2_wrapper - Wrapper for setup_interface2()
1497  * @iface: Pointer to interface data.
1498  * @status: Status of the hw mode select.
1499  *
1500  * Wrapper for setup_interface2() to calls finalize function upon completion.
1501  */
1502 static void setup_interface2_wrapper(struct hostapd_iface *iface, int status)
1503 {
1504         int ret = status;
1505         if (ret)
1506                 printf("Could not select hw_mode and channel. (%d)\n", ret);
1507         else
1508                 ret = setup_interface2(iface);
1509
1510         setup_interface_finalize(iface, ret);
1511 }
1512
1513
1514 /**
1515  * setup_interface2_handler - Used for immediate call of setup_interface2
1516  * @eloop_data: Stores the struct hostapd_iface * for the interface.
1517  * @user_ctx: Unused.
1518  */
1519 static void setup_interface2_handler(void *eloop_data, void *user_ctx)
1520 {
1521         struct hostapd_iface *iface = eloop_data;
1522
1523         setup_interface2_wrapper(iface, 0);
1524 }
1525
1526
1527 static int hostapd_radius_get_eap_user(void *ctx, const u8 *identity,
1528                                        size_t identity_len, int phase2,
1529                                        struct eap_user *user)
1530 {
1531         const struct hostapd_eap_user *eap_user;
1532         int i, count;
1533
1534         eap_user = hostapd_get_eap_user(ctx, identity, identity_len, phase2);
1535         if (eap_user == NULL)
1536                 return -1;
1537
1538         if (user == NULL)
1539                 return 0;
1540
1541         os_memset(user, 0, sizeof(*user));
1542         count = EAP_USER_MAX_METHODS;
1543         if (count > EAP_MAX_METHODS)
1544                 count = EAP_MAX_METHODS;
1545         for (i = 0; i < count; i++) {
1546                 user->methods[i].vendor = eap_user->methods[i].vendor;
1547                 user->methods[i].method = eap_user->methods[i].method;
1548         }
1549
1550         if (eap_user->password) {
1551                 user->password = os_malloc(eap_user->password_len);
1552                 if (user->password == NULL)
1553                         return -1;
1554                 os_memcpy(user->password, eap_user->password,
1555                           eap_user->password_len);
1556                 user->password_len = eap_user->password_len;
1557                 user->password_hash = eap_user->password_hash;
1558         }
1559         user->force_version = eap_user->force_version;
1560         user->ttls_auth = eap_user->ttls_auth;
1561
1562         return 0;
1563 }
1564
1565
1566 /**
1567  * setup_interface1 - Setup (initialize) an interface (part 1)
1568  * @iface: Pointer to interface data
1569  * Returns: 0 on success, -1 on failure
1570  *
1571  * Initializes the driver interface, validates the configuration,
1572  * and sets driver parameters based on the configuration.
1573  * Schedules setup_interface2() to be called immediately or after
1574  * hardware mode setup takes place. 
1575  */
1576 static int setup_interface1(struct hostapd_iface *iface)
1577 {
1578         struct hostapd_data *hapd = iface->bss[0];
1579         struct hostapd_bss_config *conf = hapd->conf;
1580         size_t i;
1581         char country[4];
1582         u8 *b = conf->bssid;
1583
1584         /*
1585          * Initialize the driver interface and make sure that all BSSes get
1586          * configured with a pointer to this driver interface.
1587          */
1588         if (b[0] | b[1] | b[2] | b[3] | b[4] | b[5]) {
1589                 hapd->drv_priv = hostapd_driver_init_bssid(hapd, b);
1590         } else {
1591                 hapd->drv_priv = hostapd_driver_init(hapd);
1592         }
1593
1594         if (hapd->drv_priv == NULL) {
1595                 printf("%s driver initialization failed.\n",
1596                         hapd->driver ? hapd->driver->name : "Unknown");
1597                 hapd->driver = NULL;
1598                 return -1;
1599         }
1600         for (i = 0; i < iface->num_bss; i++) {
1601                 iface->bss[i]->driver = hapd->driver;
1602                 iface->bss[i]->drv_priv = hapd->drv_priv;
1603         }
1604
1605         if (hostapd_validate_bssid_configuration(iface))
1606                 return -1;
1607
1608 #ifdef CONFIG_IEEE80211N
1609         SET_2BIT_LE16(&iface->ht_op_mode,
1610                       HT_INFO_OPERATION_MODE_OP_MODE_OFFSET,
1611                       OP_MODE_PURE);
1612 #endif /* CONFIG_IEEE80211N */
1613
1614         os_memcpy(country, hapd->iconf->country, 3);
1615         country[3] = '\0';
1616         if (hostapd_set_country(hapd, country) < 0) {
1617                 printf("Failed to set country code\n");
1618                 return -1;
1619         }
1620
1621         if (hapd->iconf->ieee80211d || hapd->iconf->ieee80211h) {
1622                 if (hostapd_set_ieee80211d(hapd, 1) < 0) {
1623                         printf("Failed to set ieee80211d (%d)\n",
1624                                hapd->iconf->ieee80211d);
1625                         return -1;
1626                 }
1627         }
1628
1629         if (hapd->iconf->bridge_packets != INTERNAL_BRIDGE_DO_NOT_CONTROL &&
1630             hostapd_set_internal_bridge(hapd, hapd->iconf->bridge_packets)) {
1631                 printf("Failed to set bridge_packets for kernel driver\n");
1632                 return -1;
1633         }
1634
1635         /* TODO: merge with hostapd_driver_init() ? */
1636         if (hostapd_wireless_event_init(hapd) < 0)
1637                 return -1;
1638
1639         if (hostapd_get_hw_features(iface)) {
1640                 /* Not all drivers support this yet, so continue without hw
1641                  * feature data. */
1642         } else {
1643                 return hostapd_select_hw_mode_start(iface,
1644                                                     setup_interface2_wrapper);
1645         }
1646
1647         eloop_register_timeout(0, 0, setup_interface2_handler, iface, NULL);
1648         return 0;
1649 }
1650
1651
1652 /**
1653  * setup_interface_start - Handler to start setup interface
1654  * @eloop_data: Stores the struct hostapd_iface * for the interface.
1655  * @user_ctx: Unused.
1656  *
1657  * An eloop handler is used so that all errors can be processed by the
1658  * callback without introducing stack recursion.
1659  */
1660 static void setup_interface_start(void *eloop_data, void *user_ctx)
1661 {
1662         struct hostapd_iface *iface = eloop_data;
1663
1664         int ret;
1665
1666         ret = setup_interface1(iface);
1667         if (ret)
1668                 setup_interface_finalize(iface, ret);
1669 }
1670
1671
1672 /**
1673  * hostapd_setup_interface_start - Start the setup of an interface
1674  * @iface: Pointer to interface data.
1675  * @cb: The function to callback when done.
1676  * Returns:  0 if it starts successfully; cb will be called when done.
1677  *          -1 on failure; cb will not be called.
1678  *
1679  * Initializes the driver interface, validates the configuration,
1680  * and sets driver parameters based on the configuration.
1681  * Flushes old stations, sets the channel, DFS parameters, encryption,
1682  * beacons, and WDS links based on the configuration.
1683  */
1684 int hostapd_setup_interface_start(struct hostapd_iface *iface,
1685                                   hostapd_iface_cb cb)
1686 {
1687         if (iface->setup_cb) {
1688                 wpa_printf(MSG_DEBUG,
1689                            "%s: Interface setup already in progress.\n",
1690                            iface->bss[0]->conf->iface);
1691                 return -1;
1692         }
1693
1694         iface->setup_cb = cb;
1695
1696         eloop_register_timeout(0, 0, setup_interface_start, iface, NULL);
1697
1698         return 0;
1699 }
1700
1701
1702 /**
1703  * hostapd_setup_interace_stop - Stops the setup of an interface
1704  * @iface: Pointer to interface data
1705  * Returns:  0 if successfully stopped;
1706  *          -1 on failure (i.e., was not in progress)
1707  */
1708 int hostapd_setup_interface_stop(struct hostapd_iface *iface)
1709 {
1710         return setup_interface_finalize(iface, -1);
1711 }
1712
1713
1714 static void show_version(void)
1715 {
1716         fprintf(stderr,
1717                 "hostapd v" VERSION_STR "\n"
1718                 "User space daemon for IEEE 802.11 AP management,\n"
1719                 "IEEE 802.1X/WPA/WPA2/EAP/RADIUS Authenticator\n"
1720                 "Copyright (c) 2002-2008, Jouni Malinen <j@w1.fi> "
1721                 "and contributors\n");
1722 }
1723
1724
1725 static void usage(void)
1726 {
1727         show_version();
1728         fprintf(stderr,
1729                 "\n"
1730                 "usage: hostapd [-hdBKtv] [-P <PID file>] "
1731                 "<configuration file(s)>\n"
1732                 "\n"
1733                 "options:\n"
1734                 "   -h   show this usage\n"
1735                 "   -d   show more debug messages (-dd for even more)\n"
1736                 "   -B   run daemon in the background\n"
1737                 "   -P   PID file\n"
1738                 "   -K   include key data in debug messages\n"
1739                 "   -t   include timestamps in some debug messages\n"
1740                 "   -v   show hostapd version\n");
1741
1742         exit(1);
1743 }
1744
1745
1746 /**
1747  * hostapd_alloc_bss_data - Allocate and initialize per-BSS data
1748  * @hapd_iface: Pointer to interface data
1749  * @conf: Pointer to per-interface configuration
1750  * @bss: Pointer to per-BSS configuration for this BSS
1751  * Returns: Pointer to allocated BSS data
1752  *
1753  * This function is used to allocate per-BSS data structure. This data will be
1754  * freed after hostapd_cleanup() is called for it during interface
1755  * deinitialization.
1756  */
1757 static struct hostapd_data *
1758 hostapd_alloc_bss_data(struct hostapd_iface *hapd_iface,
1759                        struct hostapd_config *conf,
1760                        struct hostapd_bss_config *bss)
1761 {
1762         struct hostapd_data *hapd;
1763
1764         hapd = os_zalloc(sizeof(*hapd));
1765         if (hapd == NULL)
1766                 return NULL;
1767
1768         hapd->iconf = conf;
1769         hapd->conf = bss;
1770         hapd->iface = hapd_iface;
1771
1772         if (hapd->conf->individual_wep_key_len > 0) {
1773                 /* use key0 in individual key and key1 in broadcast key */
1774                 hapd->default_wep_key_idx = 1;
1775         }
1776
1777 #ifdef EAP_TLS_FUNCS
1778         if (hapd->conf->eap_server &&
1779             (hapd->conf->ca_cert || hapd->conf->server_cert ||
1780              hapd->conf->dh_file)) {
1781                 struct tls_connection_params params;
1782
1783                 hapd->ssl_ctx = tls_init(NULL);
1784                 if (hapd->ssl_ctx == NULL) {
1785                         printf("Failed to initialize TLS\n");
1786                         goto fail;
1787                 }
1788
1789                 os_memset(&params, 0, sizeof(params));
1790                 params.ca_cert = hapd->conf->ca_cert;
1791                 params.client_cert = hapd->conf->server_cert;
1792                 params.private_key = hapd->conf->private_key;
1793                 params.private_key_passwd = hapd->conf->private_key_passwd;
1794                 params.dh_file = hapd->conf->dh_file;
1795
1796                 if (tls_global_set_params(hapd->ssl_ctx, &params)) {
1797                         printf("Failed to set TLS parameters\n");
1798                         goto fail;
1799                 }
1800
1801                 if (tls_global_set_verify(hapd->ssl_ctx,
1802                                           hapd->conf->check_crl)) {
1803                         printf("Failed to enable check_crl\n");
1804                         goto fail;
1805                 }
1806         }
1807 #endif /* EAP_TLS_FUNCS */
1808
1809 #ifdef EAP_SERVER
1810         if (hapd->conf->eap_sim_db) {
1811                 hapd->eap_sim_db_priv =
1812                         eap_sim_db_init(hapd->conf->eap_sim_db,
1813                                         hostapd_sim_db_cb, hapd);
1814                 if (hapd->eap_sim_db_priv == NULL) {
1815                         printf("Failed to initialize EAP-SIM database "
1816                                "interface\n");
1817                         goto fail;
1818                 }
1819         }
1820 #endif /* EAP_SERVER */
1821
1822         if (hapd->conf->assoc_ap)
1823                 hapd->assoc_ap_state = WAIT_BEACON;
1824
1825         hapd->driver = hapd->iconf->driver;
1826
1827         return hapd;
1828
1829 #if defined(EAP_TLS_FUNCS) || defined(EAP_SERVER)
1830 fail:
1831 #endif
1832         /* TODO: cleanup allocated resources(?) */
1833         os_free(hapd);
1834         return NULL;
1835 }
1836
1837
1838 /**
1839  * hostapd_init - Allocate and initialize per-interface data
1840  * @config_file: Path to the configuration file
1841  * Returns: Pointer to the allocated interface data or %NULL on failure
1842  *
1843  * This function is used to allocate main data structures for per-interface
1844  * data. The allocated data buffer will be freed by calling
1845  * hostapd_cleanup_iface().
1846  */
1847 static struct hostapd_iface * hostapd_init(const char *config_file)
1848 {
1849         struct hostapd_iface *hapd_iface = NULL;
1850         struct hostapd_config *conf = NULL;
1851         struct hostapd_data *hapd;
1852         size_t i;
1853
1854         hapd_iface = os_zalloc(sizeof(*hapd_iface));
1855         if (hapd_iface == NULL)
1856                 goto fail;
1857
1858         hapd_iface->config_fname = os_strdup(config_file);
1859         if (hapd_iface->config_fname == NULL)
1860                 goto fail;
1861
1862         conf = hostapd_config_read(hapd_iface->config_fname);
1863         if (conf == NULL)
1864                 goto fail;
1865         hapd_iface->conf = conf;
1866
1867         hapd_iface->num_bss = conf->num_bss;
1868         hapd_iface->bss = os_zalloc(conf->num_bss *
1869                                     sizeof(struct hostapd_data *));
1870         if (hapd_iface->bss == NULL)
1871                 goto fail;
1872
1873         for (i = 0; i < conf->num_bss; i++) {
1874                 hapd = hapd_iface->bss[i] =
1875                         hostapd_alloc_bss_data(hapd_iface, conf,
1876                                                &conf->bss[i]);
1877                 if (hapd == NULL)
1878                         goto fail;
1879         }
1880
1881         return hapd_iface;
1882
1883 fail:
1884         if (conf)
1885                 hostapd_config_free(conf);
1886         if (hapd_iface) {
1887                 for (i = 0; hapd_iface->bss && i < hapd_iface->num_bss; i++) {
1888                         hapd = hapd_iface->bss[i];
1889                         if (hapd && hapd->ssl_ctx)
1890                                 tls_deinit(hapd->ssl_ctx);
1891                 }
1892
1893                 os_free(hapd_iface->config_fname);
1894                 os_free(hapd_iface->bss);
1895                 os_free(hapd_iface);
1896         }
1897         return NULL;
1898 }
1899
1900
1901 /**
1902  * register_drivers - Register driver interfaces
1903  *
1904  * This function is generated by Makefile (into driver_conf.c) to call all
1905  * configured driver interfaces to register them to core hostapd.
1906  */
1907 void register_drivers(void);
1908
1909
1910 /**
1911  * setup_interface_done - Callback when an interface is done being setup.
1912  * @iface: Pointer to interface data.
1913  * @status: Status of the interface setup (0 on success; -1 on failure).
1914  */
1915 static void setup_interface_done(struct hostapd_iface *iface, int status)
1916 {
1917         if (status) {
1918                 wpa_printf(MSG_DEBUG, "%s: Unable to setup interface.",
1919                            iface->bss[0]->conf->iface);
1920                 eloop_terminate();
1921         } else if (!hostapd_drv_none(iface->bss[0]))
1922                 wpa_printf(MSG_DEBUG, "%s: Setup of interface done.",
1923                            iface->bss[0]->conf->iface);
1924 }
1925
1926
1927 int main(int argc, char *argv[])
1928 {
1929         struct hapd_interfaces interfaces;
1930         int ret = 1, k;
1931         size_t i, j;
1932         int c, debug = 0, daemonize = 0, tnc = 0;
1933         const char *pid_file = NULL;
1934
1935         hostapd_logger_register_cb(hostapd_logger_cb);
1936
1937         for (;;) {
1938                 c = getopt(argc, argv, "BdhKP:tv");
1939                 if (c < 0)
1940                         break;
1941                 switch (c) {
1942                 case 'h':
1943                         usage();
1944                         break;
1945                 case 'd':
1946                         debug++;
1947                         if (wpa_debug_level > 0)
1948                                 wpa_debug_level--;
1949                         break;
1950                 case 'B':
1951                         daemonize++;
1952                         break;
1953                 case 'K':
1954                         wpa_debug_show_keys++;
1955                         break;
1956                 case 'P':
1957                         pid_file = optarg;
1958                         break;
1959                 case 't':
1960                         wpa_debug_timestamp++;
1961                         break;
1962                 case 'v':
1963                         show_version();
1964                         exit(1);
1965                         break;
1966
1967                 default:
1968                         usage();
1969                         break;
1970                 }
1971         }
1972
1973         if (optind == argc)
1974                 usage();
1975
1976         if (eap_server_register_methods()) {
1977                 wpa_printf(MSG_ERROR, "Failed to register EAP methods");
1978                 return -1;
1979         }
1980
1981         interfaces.count = argc - optind;
1982
1983         interfaces.iface = os_malloc(interfaces.count *
1984                                      sizeof(struct hostapd_iface *));
1985         if (interfaces.iface == NULL) {
1986                 wpa_printf(MSG_ERROR, "malloc failed\n");
1987                 return -1;
1988         }
1989
1990         if (eloop_init(&interfaces)) {
1991                 wpa_printf(MSG_ERROR, "Failed to initialize event loop");
1992                 return -1;
1993         }
1994
1995 #ifndef CONFIG_NATIVE_WINDOWS
1996         eloop_register_signal(SIGHUP, handle_reload, NULL);
1997         eloop_register_signal(SIGUSR1, handle_dump_state, NULL);
1998 #endif /* CONFIG_NATIVE_WINDOWS */
1999         eloop_register_signal_terminate(handle_term, NULL);
2000
2001         /* Initialize interfaces */
2002         for (i = 0; i < interfaces.count; i++) {
2003                 printf("Configuration file: %s\n", argv[optind + i]);
2004                 interfaces.iface[i] = hostapd_init(argv[optind + i]);
2005                 if (!interfaces.iface[i])
2006                         goto out;
2007                 for (k = 0; k < debug; k++) {
2008                         if (interfaces.iface[i]->bss[0]->conf->
2009                             logger_stdout_level > 0)
2010                                 interfaces.iface[i]->bss[0]->conf->
2011                                         logger_stdout_level--;
2012                 }
2013
2014                 ret = hostapd_setup_interface_start(interfaces.iface[i],
2015                                                     setup_interface_done);
2016                 if (ret)
2017                         goto out;
2018
2019                 for (k = 0; k < (int) interfaces.iface[i]->num_bss; k++) {
2020                         if (interfaces.iface[i]->bss[0]->conf->tnc)
2021                                 tnc++;
2022                 }
2023         }
2024
2025 #ifdef EAP_TNC
2026         if (tnc && tncs_global_init() < 0) {
2027                 wpa_printf(MSG_ERROR, "Failed to initialize TNCS");
2028                 goto out;
2029         }
2030 #endif /* EAP_TNC */
2031
2032         if (daemonize && os_daemonize(pid_file)) {
2033                 perror("daemon");
2034                 goto out;
2035         }
2036
2037 #ifndef CONFIG_NATIVE_WINDOWS
2038         openlog("hostapd", 0, LOG_DAEMON);
2039 #endif /* CONFIG_NATIVE_WINDOWS */
2040
2041         eloop_run();
2042
2043         /* Disconnect associated stations from all interfaces and BSSes */
2044         for (i = 0; i < interfaces.count; i++) {
2045                 for (j = 0; j < interfaces.iface[i]->num_bss; j++) {
2046                         struct hostapd_data *hapd =
2047                                 interfaces.iface[i]->bss[j];
2048                         hostapd_free_stas(hapd);
2049                         hostapd_flush_old_stations(hapd);
2050                 }
2051         }
2052
2053         ret = 0;
2054
2055  out:
2056         /* Deinitialize all interfaces */
2057         for (i = 0; i < interfaces.count; i++) {
2058                 if (!interfaces.iface[i])
2059                         continue;
2060                 hostapd_setup_interface_stop(interfaces.iface[i]);
2061                 hostapd_cleanup_iface_pre(interfaces.iface[i]);
2062                 for (j = 0; j < interfaces.iface[i]->num_bss; j++) {
2063                         struct hostapd_data *hapd =
2064                                 interfaces.iface[i]->bss[j];
2065                         hostapd_cleanup(hapd);
2066                         if (j == interfaces.iface[i]->num_bss - 1 &&
2067                             hapd->driver)
2068                                 hostapd_driver_deinit(hapd);
2069                 }
2070                 for (j = 0; j < interfaces.iface[i]->num_bss; j++)
2071                         os_free(interfaces.iface[i]->bss[j]);
2072                 hostapd_cleanup_iface(interfaces.iface[i]);
2073         }
2074         os_free(interfaces.iface);
2075
2076 #ifdef EAP_TNC
2077         tncs_global_deinit();
2078 #endif /* EAP_TNC */
2079
2080         eloop_destroy();
2081
2082 #ifndef CONFIG_NATIVE_WINDOWS
2083         closelog();
2084 #endif /* CONFIG_NATIVE_WINDOWS */
2085
2086         eap_server_unregister_methods();
2087
2088         os_daemonize_terminate(pid_file);
2089
2090         return ret;
2091 }