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