wpa_supplicant: Initial Revision 0.8.X

Based on:
commit 0725cc7b7efc434910e89865c42eda7ce61bbf08
Author: Jouni Malinen <j@w1.fi>
Date:   Thu Apr 21 20:41:01 2011 +0300

    Enable CONFIG_DRIVER_NL80211=y in the default configuration

    nl80211 should be preferred over WEXT with any recent Linux
    kernel version.

Change-Id: I26aec5afbbd4f4a1f5fd900912545b6f5050de64
Signed-off-by: Dmitry Shmidt <dimitrysh@google.com>
diff --git a/src/radius/.gitignore b/src/radius/.gitignore
new file mode 100644
index 0000000..a89a1f9
--- /dev/null
+++ b/src/radius/.gitignore
@@ -0,0 +1 @@
+libradius.a
diff --git a/src/radius/Makefile b/src/radius/Makefile
new file mode 100644
index 0000000..b199be8
--- /dev/null
+++ b/src/radius/Makefile
@@ -0,0 +1,22 @@
+all: libradius.a
+
+clean:
+	rm -f *~ *.o *.d libradius.a
+
+install:
+	@echo Nothing to be made.
+
+
+include ../lib.rules
+
+CFLAGS += -DCONFIG_IPV6
+
+LIB_OBJS= \
+	radius.o \
+	radius_client.o \
+	radius_server.o
+
+libradius.a: $(LIB_OBJS)
+	$(AR) crT $@ $?
+
+-include $(OBJS:%.o=%.d)
diff --git a/src/radius/radius.c b/src/radius/radius.c
new file mode 100644
index 0000000..70754ef
--- /dev/null
+++ b/src/radius/radius.c
@@ -0,0 +1,1317 @@
+/*
+ * RADIUS message processing
+ * Copyright (c) 2002-2009, Jouni Malinen <j@w1.fi>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ *
+ * Alternatively, this software may be distributed under the terms of BSD
+ * license.
+ *
+ * See README and COPYING for more details.
+ */
+
+#include "utils/includes.h"
+
+#include "utils/common.h"
+#include "utils/wpabuf.h"
+#include "crypto/md5.h"
+#include "crypto/crypto.h"
+#include "radius.h"
+
+
+/**
+ * struct radius_msg - RADIUS message structure for new and parsed messages
+ */
+struct radius_msg {
+	/**
+	 * buf - Allocated buffer for RADIUS message
+	 */
+	struct wpabuf *buf;
+
+	/**
+	 * hdr - Pointer to the RADIUS header in buf
+	 */
+	struct radius_hdr *hdr;
+
+	/**
+	 * attr_pos - Array of indexes to attributes
+	 *
+	 * The values are number of bytes from buf to the beginning of
+	 * struct radius_attr_hdr.
+	 */
+	size_t *attr_pos;
+
+	/**
+	 * attr_size - Total size of the attribute pointer array
+	 */
+	size_t attr_size;
+
+	/**
+	 * attr_used - Total number of attributes in the array
+	 */
+	size_t attr_used;
+};
+
+
+struct radius_hdr * radius_msg_get_hdr(struct radius_msg *msg)
+{
+	return msg->hdr;
+}
+
+
+struct wpabuf * radius_msg_get_buf(struct radius_msg *msg)
+{
+	return msg->buf;
+}
+
+
+static struct radius_attr_hdr *
+radius_get_attr_hdr(struct radius_msg *msg, int idx)
+{
+	return (struct radius_attr_hdr *)
+		(wpabuf_mhead_u8(msg->buf) + msg->attr_pos[idx]);
+}
+
+
+static void radius_msg_set_hdr(struct radius_msg *msg, u8 code, u8 identifier)
+{
+	msg->hdr->code = code;
+	msg->hdr->identifier = identifier;
+}
+
+
+static int radius_msg_initialize(struct radius_msg *msg)
+{
+	msg->attr_pos =
+		os_zalloc(RADIUS_DEFAULT_ATTR_COUNT * sizeof(*msg->attr_pos));
+	if (msg->attr_pos == NULL)
+		return -1;
+
+	msg->attr_size = RADIUS_DEFAULT_ATTR_COUNT;
+	msg->attr_used = 0;
+
+	return 0;
+}
+
+
+/**
+ * radius_msg_new - Create a new RADIUS message
+ * @code: Code for RADIUS header
+ * @identifier: Identifier for RADIUS header
+ * Returns: Context for RADIUS message or %NULL on failure
+ *
+ * The caller is responsible for freeing the returned data with
+ * radius_msg_free().
+ */
+struct radius_msg * radius_msg_new(u8 code, u8 identifier)
+{
+	struct radius_msg *msg;
+
+	msg = os_zalloc(sizeof(*msg));
+	if (msg == NULL)
+		return NULL;
+
+	msg->buf = wpabuf_alloc(RADIUS_DEFAULT_MSG_SIZE);
+	if (msg->buf == NULL || radius_msg_initialize(msg)) {
+		radius_msg_free(msg);
+		return NULL;
+	}
+	msg->hdr = wpabuf_put(msg->buf, sizeof(struct radius_hdr));
+
+	radius_msg_set_hdr(msg, code, identifier);
+
+	return msg;
+}
+
+
+/**
+ * radius_msg_free - Free a RADIUS message
+ * @msg: RADIUS message from radius_msg_new() or radius_msg_parse()
+ */
+void radius_msg_free(struct radius_msg *msg)
+{
+	if (msg == NULL)
+		return;
+
+	wpabuf_free(msg->buf);
+	os_free(msg->attr_pos);
+	os_free(msg);
+}
+
+
+static const char *radius_code_string(u8 code)
+{
+	switch (code) {
+	case RADIUS_CODE_ACCESS_REQUEST: return "Access-Request";
+	case RADIUS_CODE_ACCESS_ACCEPT: return "Access-Accept";
+	case RADIUS_CODE_ACCESS_REJECT: return "Access-Reject";
+	case RADIUS_CODE_ACCOUNTING_REQUEST: return "Accounting-Request";
+	case RADIUS_CODE_ACCOUNTING_RESPONSE: return "Accounting-Response";
+	case RADIUS_CODE_ACCESS_CHALLENGE: return "Access-Challenge";
+	case RADIUS_CODE_STATUS_SERVER: return "Status-Server";
+	case RADIUS_CODE_STATUS_CLIENT: return "Status-Client";
+	case RADIUS_CODE_RESERVED: return "Reserved";
+	default: return "?Unknown?";
+	}
+}
+
+
+struct radius_attr_type {
+	u8 type;
+	char *name;
+	enum {
+		RADIUS_ATTR_UNDIST, RADIUS_ATTR_TEXT, RADIUS_ATTR_IP,
+		RADIUS_ATTR_HEXDUMP, RADIUS_ATTR_INT32, RADIUS_ATTR_IPV6
+	} data_type;
+};
+
+static struct radius_attr_type radius_attrs[] =
+{
+	{ RADIUS_ATTR_USER_NAME, "User-Name", RADIUS_ATTR_TEXT },
+	{ RADIUS_ATTR_USER_PASSWORD, "User-Password", RADIUS_ATTR_UNDIST },
+	{ RADIUS_ATTR_NAS_IP_ADDRESS, "NAS-IP-Address", RADIUS_ATTR_IP },
+	{ RADIUS_ATTR_NAS_PORT, "NAS-Port", RADIUS_ATTR_INT32 },
+	{ RADIUS_ATTR_FRAMED_MTU, "Framed-MTU", RADIUS_ATTR_INT32 },
+	{ RADIUS_ATTR_REPLY_MESSAGE, "Reply-Message", RADIUS_ATTR_TEXT },
+	{ RADIUS_ATTR_STATE, "State", RADIUS_ATTR_UNDIST },
+	{ RADIUS_ATTR_CLASS, "Class", RADIUS_ATTR_UNDIST },
+	{ RADIUS_ATTR_VENDOR_SPECIFIC, "Vendor-Specific", RADIUS_ATTR_UNDIST },
+	{ RADIUS_ATTR_SESSION_TIMEOUT, "Session-Timeout", RADIUS_ATTR_INT32 },
+	{ RADIUS_ATTR_IDLE_TIMEOUT, "Idle-Timeout", RADIUS_ATTR_INT32 },
+	{ RADIUS_ATTR_TERMINATION_ACTION, "Termination-Action",
+	  RADIUS_ATTR_INT32 },
+	{ RADIUS_ATTR_CALLED_STATION_ID, "Called-Station-Id",
+	  RADIUS_ATTR_TEXT },
+	{ RADIUS_ATTR_CALLING_STATION_ID, "Calling-Station-Id",
+	  RADIUS_ATTR_TEXT },
+	{ RADIUS_ATTR_NAS_IDENTIFIER, "NAS-Identifier", RADIUS_ATTR_TEXT },
+	{ RADIUS_ATTR_PROXY_STATE, "Proxy-State", RADIUS_ATTR_UNDIST },
+	{ RADIUS_ATTR_ACCT_STATUS_TYPE, "Acct-Status-Type",
+	  RADIUS_ATTR_INT32 },
+	{ RADIUS_ATTR_ACCT_DELAY_TIME, "Acct-Delay-Time", RADIUS_ATTR_INT32 },
+	{ RADIUS_ATTR_ACCT_INPUT_OCTETS, "Acct-Input-Octets",
+	  RADIUS_ATTR_INT32 },
+	{ RADIUS_ATTR_ACCT_OUTPUT_OCTETS, "Acct-Output-Octets",
+	  RADIUS_ATTR_INT32 },
+	{ RADIUS_ATTR_ACCT_SESSION_ID, "Acct-Session-Id", RADIUS_ATTR_TEXT },
+	{ RADIUS_ATTR_ACCT_AUTHENTIC, "Acct-Authentic", RADIUS_ATTR_INT32 },
+	{ RADIUS_ATTR_ACCT_SESSION_TIME, "Acct-Session-Time",
+	  RADIUS_ATTR_INT32 },
+	{ RADIUS_ATTR_ACCT_INPUT_PACKETS, "Acct-Input-Packets",
+	  RADIUS_ATTR_INT32 },
+	{ RADIUS_ATTR_ACCT_OUTPUT_PACKETS, "Acct-Output-Packets",
+	  RADIUS_ATTR_INT32 },
+	{ RADIUS_ATTR_ACCT_TERMINATE_CAUSE, "Acct-Terminate-Cause",
+	  RADIUS_ATTR_INT32 },
+	{ RADIUS_ATTR_ACCT_MULTI_SESSION_ID, "Acct-Multi-Session-Id",
+	  RADIUS_ATTR_TEXT },
+	{ RADIUS_ATTR_ACCT_LINK_COUNT, "Acct-Link-Count", RADIUS_ATTR_INT32 },
+	{ RADIUS_ATTR_ACCT_INPUT_GIGAWORDS, "Acct-Input-Gigawords", 
+	  RADIUS_ATTR_INT32 },
+	{ RADIUS_ATTR_ACCT_OUTPUT_GIGAWORDS, "Acct-Output-Gigawords",
+	  RADIUS_ATTR_INT32 },
+	{ RADIUS_ATTR_EVENT_TIMESTAMP, "Event-Timestamp",
+	  RADIUS_ATTR_INT32 },
+	{ RADIUS_ATTR_NAS_PORT_TYPE, "NAS-Port-Type", RADIUS_ATTR_INT32 },
+	{ RADIUS_ATTR_TUNNEL_TYPE, "Tunnel-Type", RADIUS_ATTR_HEXDUMP },
+	{ RADIUS_ATTR_TUNNEL_MEDIUM_TYPE, "Tunnel-Medium-Type",
+	  RADIUS_ATTR_HEXDUMP },
+	{ RADIUS_ATTR_CONNECT_INFO, "Connect-Info", RADIUS_ATTR_TEXT },
+	{ RADIUS_ATTR_EAP_MESSAGE, "EAP-Message", RADIUS_ATTR_UNDIST },
+	{ RADIUS_ATTR_MESSAGE_AUTHENTICATOR, "Message-Authenticator",
+	  RADIUS_ATTR_UNDIST },
+	{ RADIUS_ATTR_TUNNEL_PRIVATE_GROUP_ID, "Tunnel-Private-Group-Id",
+	  RADIUS_ATTR_HEXDUMP },
+	{ RADIUS_ATTR_ACCT_INTERIM_INTERVAL, "Acct-Interim-Interval",
+	  RADIUS_ATTR_INT32 },
+	{ RADIUS_ATTR_CHARGEABLE_USER_IDENTITY, "Chargable-User-Identity",
+	  RADIUS_ATTR_TEXT },
+	{ RADIUS_ATTR_NAS_IPV6_ADDRESS, "NAS-IPv6-Address", RADIUS_ATTR_IPV6 },
+};
+#define RADIUS_ATTRS (sizeof(radius_attrs) / sizeof(radius_attrs[0]))
+
+
+static struct radius_attr_type *radius_get_attr_type(u8 type)
+{
+	size_t i;
+
+	for (i = 0; i < RADIUS_ATTRS; i++) {
+		if (type == radius_attrs[i].type)
+			return &radius_attrs[i];
+	}
+
+	return NULL;
+}
+
+
+static void print_char(char c)
+{
+	if (c >= 32 && c < 127)
+		printf("%c", c);
+	else
+		printf("<%02x>", c);
+}
+
+
+static void radius_msg_dump_attr(struct radius_attr_hdr *hdr)
+{
+	struct radius_attr_type *attr;
+	int i, len;
+	unsigned char *pos;
+
+	attr = radius_get_attr_type(hdr->type);
+
+	printf("   Attribute %d (%s) length=%d\n",
+	       hdr->type, attr ? attr->name : "?Unknown?", hdr->length);
+
+	if (attr == NULL)
+		return;
+
+	len = hdr->length - sizeof(struct radius_attr_hdr);
+	pos = (unsigned char *) (hdr + 1);
+
+	switch (attr->data_type) {
+	case RADIUS_ATTR_TEXT:
+		printf("      Value: '");
+		for (i = 0; i < len; i++)
+			print_char(pos[i]);
+		printf("'\n");
+		break;
+
+	case RADIUS_ATTR_IP:
+		if (len == 4) {
+			struct in_addr addr;
+			os_memcpy(&addr, pos, 4);
+			printf("      Value: %s\n", inet_ntoa(addr));
+		} else
+			printf("      Invalid IP address length %d\n", len);
+		break;
+
+#ifdef CONFIG_IPV6
+	case RADIUS_ATTR_IPV6:
+		if (len == 16) {
+			char buf[128];
+			const char *atxt;
+			struct in6_addr *addr = (struct in6_addr *) pos;
+			atxt = inet_ntop(AF_INET6, addr, buf, sizeof(buf));
+			printf("      Value: %s\n", atxt ? atxt : "?");
+		} else
+			printf("      Invalid IPv6 address length %d\n", len);
+		break;
+#endif /* CONFIG_IPV6 */
+
+	case RADIUS_ATTR_HEXDUMP:
+	case RADIUS_ATTR_UNDIST:
+		printf("      Value:");
+		for (i = 0; i < len; i++)
+			printf(" %02x", pos[i]);
+		printf("\n");
+		break;
+
+	case RADIUS_ATTR_INT32:
+		if (len == 4)
+			printf("      Value: %u\n", WPA_GET_BE32(pos));
+		else
+			printf("      Invalid INT32 length %d\n", len);
+		break;
+
+	default:
+		break;
+	}
+}
+
+
+void radius_msg_dump(struct radius_msg *msg)
+{
+	size_t i;
+
+	printf("RADIUS message: code=%d (%s) identifier=%d length=%d\n",
+	       msg->hdr->code, radius_code_string(msg->hdr->code),
+	       msg->hdr->identifier, ntohs(msg->hdr->length));
+
+	for (i = 0; i < msg->attr_used; i++) {
+		struct radius_attr_hdr *attr = radius_get_attr_hdr(msg, i);
+		radius_msg_dump_attr(attr);
+	}
+}
+
+
+int radius_msg_finish(struct radius_msg *msg, const u8 *secret,
+		      size_t secret_len)
+{
+	if (secret) {
+		u8 auth[MD5_MAC_LEN];
+		struct radius_attr_hdr *attr;
+
+		os_memset(auth, 0, MD5_MAC_LEN);
+		attr = radius_msg_add_attr(msg,
+					   RADIUS_ATTR_MESSAGE_AUTHENTICATOR,
+					   auth, MD5_MAC_LEN);
+		if (attr == NULL) {
+			wpa_printf(MSG_WARNING, "RADIUS: Could not add "
+				   "Message-Authenticator");
+			return -1;
+		}
+		msg->hdr->length = htons(wpabuf_len(msg->buf));
+		hmac_md5(secret, secret_len, wpabuf_head(msg->buf),
+			 wpabuf_len(msg->buf), (u8 *) (attr + 1));
+	} else
+		msg->hdr->length = htons(wpabuf_len(msg->buf));
+
+	if (wpabuf_len(msg->buf) > 0xffff) {
+		wpa_printf(MSG_WARNING, "RADIUS: Too long message (%lu)",
+			   (unsigned long) wpabuf_len(msg->buf));
+		return -1;
+	}
+	return 0;
+}
+
+
+int radius_msg_finish_srv(struct radius_msg *msg, const u8 *secret,
+			  size_t secret_len, const u8 *req_authenticator)
+{
+	u8 auth[MD5_MAC_LEN];
+	struct radius_attr_hdr *attr;
+	const u8 *addr[4];
+	size_t len[4];
+
+	os_memset(auth, 0, MD5_MAC_LEN);
+	attr = radius_msg_add_attr(msg, RADIUS_ATTR_MESSAGE_AUTHENTICATOR,
+				   auth, MD5_MAC_LEN);
+	if (attr == NULL) {
+		printf("WARNING: Could not add Message-Authenticator\n");
+		return -1;
+	}
+	msg->hdr->length = htons(wpabuf_len(msg->buf));
+	os_memcpy(msg->hdr->authenticator, req_authenticator,
+		  sizeof(msg->hdr->authenticator));
+	hmac_md5(secret, secret_len, wpabuf_head(msg->buf),
+		 wpabuf_len(msg->buf), (u8 *) (attr + 1));
+
+	/* ResponseAuth = MD5(Code+ID+Length+RequestAuth+Attributes+Secret) */
+	addr[0] = (u8 *) msg->hdr;
+	len[0] = 1 + 1 + 2;
+	addr[1] = req_authenticator;
+	len[1] = MD5_MAC_LEN;
+	addr[2] = wpabuf_head_u8(msg->buf) + sizeof(struct radius_hdr);
+	len[2] = wpabuf_len(msg->buf) - sizeof(struct radius_hdr);
+	addr[3] = secret;
+	len[3] = secret_len;
+	md5_vector(4, addr, len, msg->hdr->authenticator);
+
+	if (wpabuf_len(msg->buf) > 0xffff) {
+		wpa_printf(MSG_WARNING, "RADIUS: Too long message (%lu)",
+			   (unsigned long) wpabuf_len(msg->buf));
+		return -1;
+	}
+	return 0;
+}
+
+
+void radius_msg_finish_acct(struct radius_msg *msg, const u8 *secret,
+			    size_t secret_len)
+{
+	const u8 *addr[2];
+	size_t len[2];
+
+	msg->hdr->length = htons(wpabuf_len(msg->buf));
+	os_memset(msg->hdr->authenticator, 0, MD5_MAC_LEN);
+	addr[0] = wpabuf_head(msg->buf);
+	len[0] = wpabuf_len(msg->buf);
+	addr[1] = secret;
+	len[1] = secret_len;
+	md5_vector(2, addr, len, msg->hdr->authenticator);
+
+	if (wpabuf_len(msg->buf) > 0xffff) {
+		wpa_printf(MSG_WARNING, "RADIUS: Too long messages (%lu)",
+			   (unsigned long) wpabuf_len(msg->buf));
+	}
+}
+
+
+static int radius_msg_add_attr_to_array(struct radius_msg *msg,
+					struct radius_attr_hdr *attr)
+{
+	if (msg->attr_used >= msg->attr_size) {
+		size_t *nattr_pos;
+		int nlen = msg->attr_size * 2;
+
+		nattr_pos = os_realloc(msg->attr_pos,
+				       nlen * sizeof(*msg->attr_pos));
+		if (nattr_pos == NULL)
+			return -1;
+
+		msg->attr_pos = nattr_pos;
+		msg->attr_size = nlen;
+	}
+
+	msg->attr_pos[msg->attr_used++] =
+		(unsigned char *) attr - wpabuf_head_u8(msg->buf);
+
+	return 0;
+}
+
+
+struct radius_attr_hdr *radius_msg_add_attr(struct radius_msg *msg, u8 type,
+					    const u8 *data, size_t data_len)
+{
+	size_t buf_needed;
+	struct radius_attr_hdr *attr;
+
+	if (data_len > RADIUS_MAX_ATTR_LEN) {
+		printf("radius_msg_add_attr: too long attribute (%lu bytes)\n",
+		       (unsigned long) data_len);
+		return NULL;
+	}
+
+	buf_needed = sizeof(*attr) + data_len;
+
+	if (wpabuf_tailroom(msg->buf) < buf_needed) {
+		/* allocate more space for message buffer */
+		if (wpabuf_resize(&msg->buf, buf_needed) < 0)
+			return NULL;
+		msg->hdr = wpabuf_mhead(msg->buf);
+	}
+
+	attr = wpabuf_put(msg->buf, sizeof(struct radius_attr_hdr));
+	attr->type = type;
+	attr->length = sizeof(*attr) + data_len;
+	wpabuf_put_data(msg->buf, data, data_len);
+
+	if (radius_msg_add_attr_to_array(msg, attr))
+		return NULL;
+
+	return attr;
+}
+
+
+/**
+ * radius_msg_parse - Parse a RADIUS message
+ * @data: RADIUS message to be parsed
+ * @len: Length of data buffer in octets
+ * Returns: Parsed RADIUS message or %NULL on failure
+ *
+ * This parses a RADIUS message and makes a copy of its data. The caller is
+ * responsible for freeing the returned data with radius_msg_free().
+ */
+struct radius_msg * radius_msg_parse(const u8 *data, size_t len)
+{
+	struct radius_msg *msg;
+	struct radius_hdr *hdr;
+	struct radius_attr_hdr *attr;
+	size_t msg_len;
+	unsigned char *pos, *end;
+
+	if (data == NULL || len < sizeof(*hdr))
+		return NULL;
+
+	hdr = (struct radius_hdr *) data;
+
+	msg_len = ntohs(hdr->length);
+	if (msg_len < sizeof(*hdr) || msg_len > len) {
+		wpa_printf(MSG_INFO, "RADIUS: Invalid message length");
+		return NULL;
+	}
+
+	if (msg_len < len) {
+		wpa_printf(MSG_DEBUG, "RADIUS: Ignored %lu extra bytes after "
+			   "RADIUS message", (unsigned long) len - msg_len);
+	}
+
+	msg = os_zalloc(sizeof(*msg));
+	if (msg == NULL)
+		return NULL;
+
+	msg->buf = wpabuf_alloc_copy(data, msg_len);
+	if (msg->buf == NULL || radius_msg_initialize(msg)) {
+		radius_msg_free(msg);
+		return NULL;
+	}
+	msg->hdr = wpabuf_mhead(msg->buf);
+
+	/* parse attributes */
+	pos = wpabuf_mhead_u8(msg->buf) + sizeof(struct radius_hdr);
+	end = wpabuf_mhead_u8(msg->buf) + wpabuf_len(msg->buf);
+	while (pos < end) {
+		if ((size_t) (end - pos) < sizeof(*attr))
+			goto fail;
+
+		attr = (struct radius_attr_hdr *) pos;
+
+		if (pos + attr->length > end || attr->length < sizeof(*attr))
+			goto fail;
+
+		/* TODO: check that attr->length is suitable for attr->type */
+
+		if (radius_msg_add_attr_to_array(msg, attr))
+			goto fail;
+
+		pos += attr->length;
+	}
+
+	return msg;
+
+ fail:
+	radius_msg_free(msg);
+	return NULL;
+}
+
+
+int radius_msg_add_eap(struct radius_msg *msg, const u8 *data, size_t data_len)
+{
+	const u8 *pos = data;
+	size_t left = data_len;
+
+	while (left > 0) {
+		int len;
+		if (left > RADIUS_MAX_ATTR_LEN)
+			len = RADIUS_MAX_ATTR_LEN;
+		else
+			len = left;
+
+		if (!radius_msg_add_attr(msg, RADIUS_ATTR_EAP_MESSAGE,
+					 pos, len))
+			return 0;
+
+		pos += len;
+		left -= len;
+	}
+
+	return 1;
+}
+
+
+u8 *radius_msg_get_eap(struct radius_msg *msg, size_t *eap_len)
+{
+	u8 *eap, *pos;
+	size_t len, i;
+	struct radius_attr_hdr *attr;
+
+	if (msg == NULL)
+		return NULL;
+
+	len = 0;
+	for (i = 0; i < msg->attr_used; i++) {
+		attr = radius_get_attr_hdr(msg, i);
+		if (attr->type == RADIUS_ATTR_EAP_MESSAGE)
+			len += attr->length - sizeof(struct radius_attr_hdr);
+	}
+
+	if (len == 0)
+		return NULL;
+
+	eap = os_malloc(len);
+	if (eap == NULL)
+		return NULL;
+
+	pos = eap;
+	for (i = 0; i < msg->attr_used; i++) {
+		attr = radius_get_attr_hdr(msg, i);
+		if (attr->type == RADIUS_ATTR_EAP_MESSAGE) {
+			int flen = attr->length - sizeof(*attr);
+			os_memcpy(pos, attr + 1, flen);
+			pos += flen;
+		}
+	}
+
+	if (eap_len)
+		*eap_len = len;
+
+	return eap;
+}
+
+
+int radius_msg_verify_msg_auth(struct radius_msg *msg, const u8 *secret,
+			       size_t secret_len, const u8 *req_auth)
+{
+	u8 auth[MD5_MAC_LEN], orig[MD5_MAC_LEN];
+	u8 orig_authenticator[16];
+	struct radius_attr_hdr *attr = NULL, *tmp;
+	size_t i;
+
+	for (i = 0; i < msg->attr_used; i++) {
+		tmp = radius_get_attr_hdr(msg, i);
+		if (tmp->type == RADIUS_ATTR_MESSAGE_AUTHENTICATOR) {
+			if (attr != NULL) {
+				printf("Multiple Message-Authenticator "
+				       "attributes in RADIUS message\n");
+				return 1;
+			}
+			attr = tmp;
+		}
+	}
+
+	if (attr == NULL) {
+		printf("No Message-Authenticator attribute found\n");
+		return 1;
+	}
+
+	os_memcpy(orig, attr + 1, MD5_MAC_LEN);
+	os_memset(attr + 1, 0, MD5_MAC_LEN);
+	if (req_auth) {
+		os_memcpy(orig_authenticator, msg->hdr->authenticator,
+			  sizeof(orig_authenticator));
+		os_memcpy(msg->hdr->authenticator, req_auth,
+			  sizeof(msg->hdr->authenticator));
+	}
+	hmac_md5(secret, secret_len, wpabuf_head(msg->buf),
+		 wpabuf_len(msg->buf), auth);
+	os_memcpy(attr + 1, orig, MD5_MAC_LEN);
+	if (req_auth) {
+		os_memcpy(msg->hdr->authenticator, orig_authenticator,
+			  sizeof(orig_authenticator));
+	}
+
+	if (os_memcmp(orig, auth, MD5_MAC_LEN) != 0) {
+		printf("Invalid Message-Authenticator!\n");
+		return 1;
+	}
+
+	return 0;
+}
+
+
+int radius_msg_verify(struct radius_msg *msg, const u8 *secret,
+		      size_t secret_len, struct radius_msg *sent_msg, int auth)
+{
+	const u8 *addr[4];
+	size_t len[4];
+	u8 hash[MD5_MAC_LEN];
+
+	if (sent_msg == NULL) {
+		printf("No matching Access-Request message found\n");
+		return 1;
+	}
+
+	if (auth &&
+	    radius_msg_verify_msg_auth(msg, secret, secret_len,
+				       sent_msg->hdr->authenticator)) {
+		return 1;
+	}
+
+	/* ResponseAuth = MD5(Code+ID+Length+RequestAuth+Attributes+Secret) */
+	addr[0] = (u8 *) msg->hdr;
+	len[0] = 1 + 1 + 2;
+	addr[1] = sent_msg->hdr->authenticator;
+	len[1] = MD5_MAC_LEN;
+	addr[2] = wpabuf_head_u8(msg->buf) + sizeof(struct radius_hdr);
+	len[2] = wpabuf_len(msg->buf) - sizeof(struct radius_hdr);
+	addr[3] = secret;
+	len[3] = secret_len;
+	md5_vector(4, addr, len, hash);
+	if (os_memcmp(hash, msg->hdr->authenticator, MD5_MAC_LEN) != 0) {
+		printf("Response Authenticator invalid!\n");
+		return 1;
+	}
+
+	return 0;
+}
+
+
+int radius_msg_copy_attr(struct radius_msg *dst, struct radius_msg *src,
+			 u8 type)
+{
+	struct radius_attr_hdr *attr;
+	size_t i;
+	int count = 0;
+
+	for (i = 0; i < src->attr_used; i++) {
+		attr = radius_get_attr_hdr(src, i);
+		if (attr->type == type) {
+			if (!radius_msg_add_attr(dst, type, (u8 *) (attr + 1),
+						 attr->length - sizeof(*attr)))
+				return -1;
+			count++;
+		}
+	}
+
+	return count;
+}
+
+
+/* Create Request Authenticator. The value should be unique over the lifetime
+ * of the shared secret between authenticator and authentication server.
+ * Use one-way MD5 hash calculated from current timestamp and some data given
+ * by the caller. */
+void radius_msg_make_authenticator(struct radius_msg *msg,
+				   const u8 *data, size_t len)
+{
+	struct os_time tv;
+	long int l;
+	const u8 *addr[3];
+	size_t elen[3];
+
+	os_get_time(&tv);
+	l = os_random();
+	addr[0] = (u8 *) &tv;
+	elen[0] = sizeof(tv);
+	addr[1] = data;
+	elen[1] = len;
+	addr[2] = (u8 *) &l;
+	elen[2] = sizeof(l);
+	md5_vector(3, addr, elen, msg->hdr->authenticator);
+}
+
+
+/* Get Vendor-specific RADIUS Attribute from a parsed RADIUS message.
+ * Returns the Attribute payload and sets alen to indicate the length of the
+ * payload if a vendor attribute with subtype is found, otherwise returns NULL.
+ * The returned payload is allocated with os_malloc() and caller must free it
+ * by calling os_free().
+ */
+static u8 *radius_msg_get_vendor_attr(struct radius_msg *msg, u32 vendor,
+				      u8 subtype, size_t *alen)
+{
+	u8 *data, *pos;
+	size_t i, len;
+
+	if (msg == NULL)
+		return NULL;
+
+	for (i = 0; i < msg->attr_used; i++) {
+		struct radius_attr_hdr *attr = radius_get_attr_hdr(msg, i);
+		size_t left;
+		u32 vendor_id;
+		struct radius_attr_vendor *vhdr;
+
+		if (attr->type != RADIUS_ATTR_VENDOR_SPECIFIC)
+			continue;
+
+		left = attr->length - sizeof(*attr);
+		if (left < 4)
+			continue;
+
+		pos = (u8 *) (attr + 1);
+
+		os_memcpy(&vendor_id, pos, 4);
+		pos += 4;
+		left -= 4;
+
+		if (ntohl(vendor_id) != vendor)
+			continue;
+
+		while (left >= sizeof(*vhdr)) {
+			vhdr = (struct radius_attr_vendor *) pos;
+			if (vhdr->vendor_length > left ||
+			    vhdr->vendor_length < sizeof(*vhdr)) {
+				left = 0;
+				break;
+			}
+			if (vhdr->vendor_type != subtype) {
+				pos += vhdr->vendor_length;
+				left -= vhdr->vendor_length;
+				continue;
+			}
+
+			len = vhdr->vendor_length - sizeof(*vhdr);
+			data = os_malloc(len);
+			if (data == NULL)
+				return NULL;
+			os_memcpy(data, pos + sizeof(*vhdr), len);
+			if (alen)
+				*alen = len;
+			return data;
+		}
+	}
+
+	return NULL;
+}
+
+
+static u8 * decrypt_ms_key(const u8 *key, size_t len,
+			   const u8 *req_authenticator,
+			   const u8 *secret, size_t secret_len, size_t *reslen)
+{
+	u8 *plain, *ppos, *res;
+	const u8 *pos;
+	size_t left, plen;
+	u8 hash[MD5_MAC_LEN];
+	int i, first = 1;
+	const u8 *addr[3];
+	size_t elen[3];
+
+	/* key: 16-bit salt followed by encrypted key info */
+
+	if (len < 2 + 16)
+		return NULL;
+
+	pos = key + 2;
+	left = len - 2;
+	if (left % 16) {
+		printf("Invalid ms key len %lu\n", (unsigned long) left);
+		return NULL;
+	}
+
+	plen = left;
+	ppos = plain = os_malloc(plen);
+	if (plain == NULL)
+		return NULL;
+	plain[0] = 0;
+
+	while (left > 0) {
+		/* b(1) = MD5(Secret + Request-Authenticator + Salt)
+		 * b(i) = MD5(Secret + c(i - 1)) for i > 1 */
+
+		addr[0] = secret;
+		elen[0] = secret_len;
+		if (first) {
+			addr[1] = req_authenticator;
+			elen[1] = MD5_MAC_LEN;
+			addr[2] = key;
+			elen[2] = 2; /* Salt */
+		} else {
+			addr[1] = pos - MD5_MAC_LEN;
+			elen[1] = MD5_MAC_LEN;
+		}
+		md5_vector(first ? 3 : 2, addr, elen, hash);
+		first = 0;
+
+		for (i = 0; i < MD5_MAC_LEN; i++)
+			*ppos++ = *pos++ ^ hash[i];
+		left -= MD5_MAC_LEN;
+	}
+
+	if (plain[0] == 0 || plain[0] > plen - 1) {
+		printf("Failed to decrypt MPPE key\n");
+		os_free(plain);
+		return NULL;
+	}
+
+	res = os_malloc(plain[0]);
+	if (res == NULL) {
+		os_free(plain);
+		return NULL;
+	}
+	os_memcpy(res, plain + 1, plain[0]);
+	if (reslen)
+		*reslen = plain[0];
+	os_free(plain);
+	return res;
+}
+
+
+static void encrypt_ms_key(const u8 *key, size_t key_len, u16 salt,
+			   const u8 *req_authenticator,
+			   const u8 *secret, size_t secret_len,
+			   u8 *ebuf, size_t *elen)
+{
+	int i, len, first = 1;
+	u8 hash[MD5_MAC_LEN], saltbuf[2], *pos;
+	const u8 *addr[3];
+	size_t _len[3];
+
+	WPA_PUT_BE16(saltbuf, salt);
+
+	len = 1 + key_len;
+	if (len & 0x0f) {
+		len = (len & 0xf0) + 16;
+	}
+	os_memset(ebuf, 0, len);
+	ebuf[0] = key_len;
+	os_memcpy(ebuf + 1, key, key_len);
+
+	*elen = len;
+
+	pos = ebuf;
+	while (len > 0) {
+		/* b(1) = MD5(Secret + Request-Authenticator + Salt)
+		 * b(i) = MD5(Secret + c(i - 1)) for i > 1 */
+		addr[0] = secret;
+		_len[0] = secret_len;
+		if (first) {
+			addr[1] = req_authenticator;
+			_len[1] = MD5_MAC_LEN;
+			addr[2] = saltbuf;
+			_len[2] = sizeof(saltbuf);
+		} else {
+			addr[1] = pos - MD5_MAC_LEN;
+			_len[1] = MD5_MAC_LEN;
+		}
+		md5_vector(first ? 3 : 2, addr, _len, hash);
+		first = 0;
+
+		for (i = 0; i < MD5_MAC_LEN; i++)
+			*pos++ ^= hash[i];
+
+		len -= MD5_MAC_LEN;
+	}
+}
+
+
+struct radius_ms_mppe_keys *
+radius_msg_get_ms_keys(struct radius_msg *msg, struct radius_msg *sent_msg,
+		       const u8 *secret, size_t secret_len)
+{
+	u8 *key;
+	size_t keylen;
+	struct radius_ms_mppe_keys *keys;
+
+	if (msg == NULL || sent_msg == NULL)
+		return NULL;
+
+	keys = os_zalloc(sizeof(*keys));
+	if (keys == NULL)
+		return NULL;
+
+	key = radius_msg_get_vendor_attr(msg, RADIUS_VENDOR_ID_MICROSOFT,
+					 RADIUS_VENDOR_ATTR_MS_MPPE_SEND_KEY,
+					 &keylen);
+	if (key) {
+		keys->send = decrypt_ms_key(key, keylen,
+					    sent_msg->hdr->authenticator,
+					    secret, secret_len,
+					    &keys->send_len);
+		os_free(key);
+	}
+
+	key = radius_msg_get_vendor_attr(msg, RADIUS_VENDOR_ID_MICROSOFT,
+					 RADIUS_VENDOR_ATTR_MS_MPPE_RECV_KEY,
+					 &keylen);
+	if (key) {
+		keys->recv = decrypt_ms_key(key, keylen,
+					    sent_msg->hdr->authenticator,
+					    secret, secret_len,
+					    &keys->recv_len);
+		os_free(key);
+	}
+
+	return keys;
+}
+
+
+struct radius_ms_mppe_keys *
+radius_msg_get_cisco_keys(struct radius_msg *msg, struct radius_msg *sent_msg,
+			  const u8 *secret, size_t secret_len)
+{
+	u8 *key;
+	size_t keylen;
+	struct radius_ms_mppe_keys *keys;
+
+	if (msg == NULL || sent_msg == NULL)
+		return NULL;
+
+	keys = os_zalloc(sizeof(*keys));
+	if (keys == NULL)
+		return NULL;
+
+	key = radius_msg_get_vendor_attr(msg, RADIUS_VENDOR_ID_CISCO,
+					 RADIUS_CISCO_AV_PAIR, &keylen);
+	if (key && keylen == 51 &&
+	    os_memcmp(key, "leap:session-key=", 17) == 0) {
+		keys->recv = decrypt_ms_key(key + 17, keylen - 17,
+					    sent_msg->hdr->authenticator,
+					    secret, secret_len,
+					    &keys->recv_len);
+	}
+	os_free(key);
+
+	return keys;
+}
+
+
+int radius_msg_add_mppe_keys(struct radius_msg *msg,
+			     const u8 *req_authenticator,
+			     const u8 *secret, size_t secret_len,
+			     const u8 *send_key, size_t send_key_len,
+			     const u8 *recv_key, size_t recv_key_len)
+{
+	struct radius_attr_hdr *attr;
+	u32 vendor_id = htonl(RADIUS_VENDOR_ID_MICROSOFT);
+	u8 *buf;
+	struct radius_attr_vendor *vhdr;
+	u8 *pos;
+	size_t elen;
+	int hlen;
+	u16 salt;
+
+	hlen = sizeof(vendor_id) + sizeof(*vhdr) + 2;
+
+	/* MS-MPPE-Send-Key */
+	buf = os_malloc(hlen + send_key_len + 16);
+	if (buf == NULL) {
+		return 0;
+	}
+	pos = buf;
+	os_memcpy(pos, &vendor_id, sizeof(vendor_id));
+	pos += sizeof(vendor_id);
+	vhdr = (struct radius_attr_vendor *) pos;
+	vhdr->vendor_type = RADIUS_VENDOR_ATTR_MS_MPPE_SEND_KEY;
+	pos = (u8 *) (vhdr + 1);
+	salt = os_random() | 0x8000;
+	WPA_PUT_BE16(pos, salt);
+	pos += 2;
+	encrypt_ms_key(send_key, send_key_len, salt, req_authenticator, secret,
+		       secret_len, pos, &elen);
+	vhdr->vendor_length = hlen + elen - sizeof(vendor_id);
+
+	attr = radius_msg_add_attr(msg, RADIUS_ATTR_VENDOR_SPECIFIC,
+				   buf, hlen + elen);
+	os_free(buf);
+	if (attr == NULL) {
+		return 0;
+	}
+
+	/* MS-MPPE-Recv-Key */
+	buf = os_malloc(hlen + send_key_len + 16);
+	if (buf == NULL) {
+		return 0;
+	}
+	pos = buf;
+	os_memcpy(pos, &vendor_id, sizeof(vendor_id));
+	pos += sizeof(vendor_id);
+	vhdr = (struct radius_attr_vendor *) pos;
+	vhdr->vendor_type = RADIUS_VENDOR_ATTR_MS_MPPE_RECV_KEY;
+	pos = (u8 *) (vhdr + 1);
+	salt ^= 1;
+	WPA_PUT_BE16(pos, salt);
+	pos += 2;
+	encrypt_ms_key(recv_key, recv_key_len, salt, req_authenticator, secret,
+		       secret_len, pos, &elen);
+	vhdr->vendor_length = hlen + elen - sizeof(vendor_id);
+
+	attr = radius_msg_add_attr(msg, RADIUS_ATTR_VENDOR_SPECIFIC,
+				   buf, hlen + elen);
+	os_free(buf);
+	if (attr == NULL) {
+		return 0;
+	}
+
+	return 1;
+}
+
+
+/* Add User-Password attribute to a RADIUS message and encrypt it as specified
+ * in RFC 2865, Chap. 5.2 */
+struct radius_attr_hdr *
+radius_msg_add_attr_user_password(struct radius_msg *msg,
+				  const u8 *data, size_t data_len,
+				  const u8 *secret, size_t secret_len)
+{
+	u8 buf[128];
+	int padlen, i;
+	size_t buf_len, pos;
+	const u8 *addr[2];
+	size_t len[2];
+	u8 hash[16];
+
+	if (data_len > 128)
+		return NULL;
+
+	os_memcpy(buf, data, data_len);
+	buf_len = data_len;
+
+	padlen = data_len % 16;
+	if (padlen) {
+		padlen = 16 - padlen;
+		os_memset(buf + data_len, 0, padlen);
+		buf_len += padlen;
+	}
+
+	addr[0] = secret;
+	len[0] = secret_len;
+	addr[1] = msg->hdr->authenticator;
+	len[1] = 16;
+	md5_vector(2, addr, len, hash);
+
+	for (i = 0; i < 16; i++)
+		buf[i] ^= hash[i];
+	pos = 16;
+
+	while (pos < buf_len) {
+		addr[0] = secret;
+		len[0] = secret_len;
+		addr[1] = &buf[pos - 16];
+		len[1] = 16;
+		md5_vector(2, addr, len, hash);
+
+		for (i = 0; i < 16; i++)
+			buf[pos + i] ^= hash[i];
+
+		pos += 16;
+	}
+
+	return radius_msg_add_attr(msg, RADIUS_ATTR_USER_PASSWORD,
+				   buf, buf_len);
+}
+
+
+int radius_msg_get_attr(struct radius_msg *msg, u8 type, u8 *buf, size_t len)
+{
+	struct radius_attr_hdr *attr = NULL, *tmp;
+	size_t i, dlen;
+
+	for (i = 0; i < msg->attr_used; i++) {
+		tmp = radius_get_attr_hdr(msg, i);
+		if (tmp->type == type) {
+			attr = tmp;
+			break;
+		}
+	}
+
+	if (!attr)
+		return -1;
+
+	dlen = attr->length - sizeof(*attr);
+	if (buf)
+		os_memcpy(buf, (attr + 1), dlen > len ? len : dlen);
+	return dlen;
+}
+
+
+int radius_msg_get_attr_ptr(struct radius_msg *msg, u8 type, u8 **buf,
+			    size_t *len, const u8 *start)
+{
+	size_t i;
+	struct radius_attr_hdr *attr = NULL, *tmp;
+
+	for (i = 0; i < msg->attr_used; i++) {
+		tmp = radius_get_attr_hdr(msg, i);
+		if (tmp->type == type &&
+		    (start == NULL || (u8 *) tmp > start)) {
+			attr = tmp;
+			break;
+		}
+	}
+
+	if (!attr)
+		return -1;
+
+	*buf = (u8 *) (attr + 1);
+	*len = attr->length - sizeof(*attr);
+	return 0;
+}
+
+
+int radius_msg_count_attr(struct radius_msg *msg, u8 type, int min_len)
+{
+	size_t i;
+	int count;
+
+	for (count = 0, i = 0; i < msg->attr_used; i++) {
+		struct radius_attr_hdr *attr = radius_get_attr_hdr(msg, i);
+		if (attr->type == type &&
+		    attr->length >= sizeof(struct radius_attr_hdr) + min_len)
+			count++;
+	}
+
+	return count;
+}
+
+
+struct radius_tunnel_attrs {
+	int tag_used;
+	int type; /* Tunnel-Type */
+	int medium_type; /* Tunnel-Medium-Type */
+	int vlanid;
+};
+
+
+/**
+ * radius_msg_get_vlanid - Parse RADIUS attributes for VLAN tunnel information
+ * @msg: RADIUS message
+ * Returns: VLAN ID for the first tunnel configuration of -1 if none is found
+ */
+int radius_msg_get_vlanid(struct radius_msg *msg)
+{
+	struct radius_tunnel_attrs tunnel[RADIUS_TUNNEL_TAGS], *tun;
+	size_t i;
+	struct radius_attr_hdr *attr = NULL;
+	const u8 *data;
+	char buf[10];
+	size_t dlen;
+
+	os_memset(&tunnel, 0, sizeof(tunnel));
+
+	for (i = 0; i < msg->attr_used; i++) {
+		attr = radius_get_attr_hdr(msg, i);
+		data = (const u8 *) (attr + 1);
+		dlen = attr->length - sizeof(*attr);
+		if (attr->length < 3)
+			continue;
+		if (data[0] >= RADIUS_TUNNEL_TAGS)
+			tun = &tunnel[0];
+		else
+			tun = &tunnel[data[0]];
+
+		switch (attr->type) {
+		case RADIUS_ATTR_TUNNEL_TYPE:
+			if (attr->length != 6)
+				break;
+			tun->tag_used++;
+			tun->type = WPA_GET_BE24(data + 1);
+			break;
+		case RADIUS_ATTR_TUNNEL_MEDIUM_TYPE:
+			if (attr->length != 6)
+				break;
+			tun->tag_used++;
+			tun->medium_type = WPA_GET_BE24(data + 1);
+			break;
+		case RADIUS_ATTR_TUNNEL_PRIVATE_GROUP_ID:
+			if (data[0] < RADIUS_TUNNEL_TAGS) {
+				data++;
+				dlen--;
+			}
+			if (dlen >= sizeof(buf))
+				break;
+			os_memcpy(buf, data, dlen);
+			buf[dlen] = '\0';
+			tun->tag_used++;
+			tun->vlanid = atoi(buf);
+			break;
+		}
+	}
+
+	for (i = 0; i < RADIUS_TUNNEL_TAGS; i++) {
+		tun = &tunnel[i];
+		if (tun->tag_used &&
+		    tun->type == RADIUS_TUNNEL_TYPE_VLAN &&
+		    tun->medium_type == RADIUS_TUNNEL_MEDIUM_TYPE_802 &&
+		    tun->vlanid > 0)
+			return tun->vlanid;
+	}
+
+	return -1;
+}
+
+
+void radius_free_class(struct radius_class_data *c)
+{
+	size_t i;
+	if (c == NULL)
+		return;
+	for (i = 0; i < c->count; i++)
+		os_free(c->attr[i].data);
+	os_free(c->attr);
+	c->attr = NULL;
+	c->count = 0;
+}
+
+
+int radius_copy_class(struct radius_class_data *dst,
+		      const struct radius_class_data *src)
+{
+	size_t i;
+
+	if (src->attr == NULL)
+		return 0;
+
+	dst->attr = os_zalloc(src->count * sizeof(struct radius_attr_data));
+	if (dst->attr == NULL)
+		return -1;
+
+	dst->count = 0;
+
+	for (i = 0; i < src->count; i++) {
+		dst->attr[i].data = os_malloc(src->attr[i].len);
+		if (dst->attr[i].data == NULL)
+			break;
+		dst->count++;
+		os_memcpy(dst->attr[i].data, src->attr[i].data,
+			  src->attr[i].len);
+		dst->attr[i].len = src->attr[i].len;
+	}
+
+	return 0;
+}
diff --git a/src/radius/radius.h b/src/radius/radius.h
new file mode 100644
index 0000000..a3cdac0
--- /dev/null
+++ b/src/radius/radius.h
@@ -0,0 +1,273 @@
+/*
+ * RADIUS message processing
+ * Copyright (c) 2002-2009, Jouni Malinen <j@w1.fi>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ *
+ * Alternatively, this software may be distributed under the terms of BSD
+ * license.
+ *
+ * See README and COPYING for more details.
+ */
+
+#ifndef RADIUS_H
+#define RADIUS_H
+
+/* RFC 2865 - RADIUS */
+
+#ifdef _MSC_VER
+#pragma pack(push, 1)
+#endif /* _MSC_VER */
+
+struct radius_hdr {
+	u8 code;
+	u8 identifier;
+	u16 length; /* including this header */
+	u8 authenticator[16];
+	/* followed by length-20 octets of attributes */
+} STRUCT_PACKED;
+
+enum { RADIUS_CODE_ACCESS_REQUEST = 1,
+       RADIUS_CODE_ACCESS_ACCEPT = 2,
+       RADIUS_CODE_ACCESS_REJECT = 3,
+       RADIUS_CODE_ACCOUNTING_REQUEST = 4,
+       RADIUS_CODE_ACCOUNTING_RESPONSE = 5,
+       RADIUS_CODE_ACCESS_CHALLENGE = 11,
+       RADIUS_CODE_STATUS_SERVER = 12,
+       RADIUS_CODE_STATUS_CLIENT = 13,
+       RADIUS_CODE_RESERVED = 255
+};
+
+struct radius_attr_hdr {
+	u8 type;
+	u8 length; /* including this header */
+	/* followed by length-2 octets of attribute value */
+} STRUCT_PACKED;
+
+#define RADIUS_MAX_ATTR_LEN (255 - sizeof(struct radius_attr_hdr))
+
+enum { RADIUS_ATTR_USER_NAME = 1,
+       RADIUS_ATTR_USER_PASSWORD = 2,
+       RADIUS_ATTR_NAS_IP_ADDRESS = 4,
+       RADIUS_ATTR_NAS_PORT = 5,
+       RADIUS_ATTR_FRAMED_MTU = 12,
+       RADIUS_ATTR_REPLY_MESSAGE = 18,
+       RADIUS_ATTR_STATE = 24,
+       RADIUS_ATTR_CLASS = 25,
+       RADIUS_ATTR_VENDOR_SPECIFIC = 26,
+       RADIUS_ATTR_SESSION_TIMEOUT = 27,
+       RADIUS_ATTR_IDLE_TIMEOUT = 28,
+       RADIUS_ATTR_TERMINATION_ACTION = 29,
+       RADIUS_ATTR_CALLED_STATION_ID = 30,
+       RADIUS_ATTR_CALLING_STATION_ID = 31,
+       RADIUS_ATTR_NAS_IDENTIFIER = 32,
+       RADIUS_ATTR_PROXY_STATE = 33,
+       RADIUS_ATTR_ACCT_STATUS_TYPE = 40,
+       RADIUS_ATTR_ACCT_DELAY_TIME = 41,
+       RADIUS_ATTR_ACCT_INPUT_OCTETS = 42,
+       RADIUS_ATTR_ACCT_OUTPUT_OCTETS = 43,
+       RADIUS_ATTR_ACCT_SESSION_ID = 44,
+       RADIUS_ATTR_ACCT_AUTHENTIC = 45,
+       RADIUS_ATTR_ACCT_SESSION_TIME = 46,
+       RADIUS_ATTR_ACCT_INPUT_PACKETS = 47,
+       RADIUS_ATTR_ACCT_OUTPUT_PACKETS = 48,
+       RADIUS_ATTR_ACCT_TERMINATE_CAUSE = 49,
+       RADIUS_ATTR_ACCT_MULTI_SESSION_ID = 50,
+       RADIUS_ATTR_ACCT_LINK_COUNT = 51,
+       RADIUS_ATTR_ACCT_INPUT_GIGAWORDS = 52,
+       RADIUS_ATTR_ACCT_OUTPUT_GIGAWORDS = 53,
+       RADIUS_ATTR_EVENT_TIMESTAMP = 55,
+       RADIUS_ATTR_NAS_PORT_TYPE = 61,
+       RADIUS_ATTR_TUNNEL_TYPE = 64,
+       RADIUS_ATTR_TUNNEL_MEDIUM_TYPE = 65,
+       RADIUS_ATTR_CONNECT_INFO = 77,
+       RADIUS_ATTR_EAP_MESSAGE = 79,
+       RADIUS_ATTR_MESSAGE_AUTHENTICATOR = 80,
+       RADIUS_ATTR_TUNNEL_PRIVATE_GROUP_ID = 81,
+       RADIUS_ATTR_ACCT_INTERIM_INTERVAL = 85,
+       RADIUS_ATTR_CHARGEABLE_USER_IDENTITY = 89,
+       RADIUS_ATTR_NAS_IPV6_ADDRESS = 95
+};
+
+
+/* Termination-Action */
+#define RADIUS_TERMINATION_ACTION_DEFAULT 0
+#define RADIUS_TERMINATION_ACTION_RADIUS_REQUEST 1
+
+/* NAS-Port-Type */
+#define RADIUS_NAS_PORT_TYPE_IEEE_802_11 19
+
+/* Acct-Status-Type */
+#define RADIUS_ACCT_STATUS_TYPE_START 1
+#define RADIUS_ACCT_STATUS_TYPE_STOP 2
+#define RADIUS_ACCT_STATUS_TYPE_INTERIM_UPDATE 3
+#define RADIUS_ACCT_STATUS_TYPE_ACCOUNTING_ON 7
+#define RADIUS_ACCT_STATUS_TYPE_ACCOUNTING_OFF 8
+
+/* Acct-Authentic */
+#define RADIUS_ACCT_AUTHENTIC_RADIUS 1
+#define RADIUS_ACCT_AUTHENTIC_LOCAL 2
+#define RADIUS_ACCT_AUTHENTIC_REMOTE 3
+
+/* Acct-Terminate-Cause */
+#define RADIUS_ACCT_TERMINATE_CAUSE_USER_REQUEST 1
+#define RADIUS_ACCT_TERMINATE_CAUSE_LOST_CARRIER 2
+#define RADIUS_ACCT_TERMINATE_CAUSE_LOST_SERVICE 3
+#define RADIUS_ACCT_TERMINATE_CAUSE_IDLE_TIMEOUT 4
+#define RADIUS_ACCT_TERMINATE_CAUSE_SESSION_TIMEOUT 5
+#define RADIUS_ACCT_TERMINATE_CAUSE_ADMIN_RESET 6
+#define RADIUS_ACCT_TERMINATE_CAUSE_ADMIN_REBOOT 7
+#define RADIUS_ACCT_TERMINATE_CAUSE_PORT_ERROR 8
+#define RADIUS_ACCT_TERMINATE_CAUSE_NAS_ERROR 9
+#define RADIUS_ACCT_TERMINATE_CAUSE_NAS_REQUEST 10
+#define RADIUS_ACCT_TERMINATE_CAUSE_NAS_REBOOT 11
+#define RADIUS_ACCT_TERMINATE_CAUSE_PORT_UNNEEDED 12
+#define RADIUS_ACCT_TERMINATE_CAUSE_PORT_PREEMPTED 13
+#define RADIUS_ACCT_TERMINATE_CAUSE_PORT_SUSPENDED 14
+#define RADIUS_ACCT_TERMINATE_CAUSE_SERVICE_UNAVAILABLE 15
+#define RADIUS_ACCT_TERMINATE_CAUSE_CALLBACK 16
+#define RADIUS_ACCT_TERMINATE_CAUSE_USER_ERROR 17
+#define RADIUS_ACCT_TERMINATE_CAUSE_HOST_REQUEST 18
+
+#define RADIUS_TUNNEL_TAGS 32
+
+/* Tunnel-Type */
+#define RADIUS_TUNNEL_TYPE_PPTP 1
+#define RADIUS_TUNNEL_TYPE_L2TP 3
+#define RADIUS_TUNNEL_TYPE_IPIP 7
+#define RADIUS_TUNNEL_TYPE_GRE 10
+#define RADIUS_TUNNEL_TYPE_VLAN 13
+
+/* Tunnel-Medium-Type */
+#define RADIUS_TUNNEL_MEDIUM_TYPE_IPV4 1
+#define RADIUS_TUNNEL_MEDIUM_TYPE_IPV6 2
+#define RADIUS_TUNNEL_MEDIUM_TYPE_802 6
+
+
+struct radius_attr_vendor {
+	u8 vendor_type;
+	u8 vendor_length;
+} STRUCT_PACKED;
+
+#define RADIUS_VENDOR_ID_CISCO 9
+#define RADIUS_CISCO_AV_PAIR 1
+
+/* RFC 2548 - Microsoft Vendor-specific RADIUS Attributes */
+#define RADIUS_VENDOR_ID_MICROSOFT 311
+
+enum { RADIUS_VENDOR_ATTR_MS_MPPE_SEND_KEY = 16,
+       RADIUS_VENDOR_ATTR_MS_MPPE_RECV_KEY = 17
+};
+
+#ifdef _MSC_VER
+#pragma pack(pop)
+#endif /* _MSC_VER */
+
+struct radius_ms_mppe_keys {
+	u8 *send;
+	size_t send_len;
+	u8 *recv;
+	size_t recv_len;
+};
+
+
+struct radius_msg;
+
+/* Default size to be allocated for new RADIUS messages */
+#define RADIUS_DEFAULT_MSG_SIZE 1024
+
+/* Default size to be allocated for attribute array */
+#define RADIUS_DEFAULT_ATTR_COUNT 16
+
+
+/* MAC address ASCII format for IEEE 802.1X use
+ * (draft-congdon-radius-8021x-20.txt) */
+#define RADIUS_802_1X_ADDR_FORMAT "%02X-%02X-%02X-%02X-%02X-%02X"
+/* MAC address ASCII format for non-802.1X use */
+#define RADIUS_ADDR_FORMAT "%02x%02x%02x%02x%02x%02x"
+
+struct radius_hdr * radius_msg_get_hdr(struct radius_msg *msg);
+struct wpabuf * radius_msg_get_buf(struct radius_msg *msg);
+struct radius_msg * radius_msg_new(u8 code, u8 identifier);
+void radius_msg_free(struct radius_msg *msg);
+void radius_msg_dump(struct radius_msg *msg);
+int radius_msg_finish(struct radius_msg *msg, const u8 *secret,
+		      size_t secret_len);
+int radius_msg_finish_srv(struct radius_msg *msg, const u8 *secret,
+			  size_t secret_len, const u8 *req_authenticator);
+void radius_msg_finish_acct(struct radius_msg *msg, const u8 *secret,
+			    size_t secret_len);
+struct radius_attr_hdr * radius_msg_add_attr(struct radius_msg *msg, u8 type,
+					     const u8 *data, size_t data_len);
+struct radius_msg * radius_msg_parse(const u8 *data, size_t len);
+int radius_msg_add_eap(struct radius_msg *msg, const u8 *data,
+		       size_t data_len);
+u8 *radius_msg_get_eap(struct radius_msg *msg, size_t *len);
+int radius_msg_verify(struct radius_msg *msg, const u8 *secret,
+		      size_t secret_len, struct radius_msg *sent_msg,
+		      int auth);
+int radius_msg_verify_msg_auth(struct radius_msg *msg, const u8 *secret,
+			       size_t secret_len, const u8 *req_auth);
+int radius_msg_copy_attr(struct radius_msg *dst, struct radius_msg *src,
+			 u8 type);
+void radius_msg_make_authenticator(struct radius_msg *msg,
+				   const u8 *data, size_t len);
+struct radius_ms_mppe_keys *
+radius_msg_get_ms_keys(struct radius_msg *msg, struct radius_msg *sent_msg,
+		       const u8 *secret, size_t secret_len);
+struct radius_ms_mppe_keys *
+radius_msg_get_cisco_keys(struct radius_msg *msg, struct radius_msg *sent_msg,
+			  const u8 *secret, size_t secret_len);
+int radius_msg_add_mppe_keys(struct radius_msg *msg,
+			     const u8 *req_authenticator,
+			     const u8 *secret, size_t secret_len,
+			     const u8 *send_key, size_t send_key_len,
+			     const u8 *recv_key, size_t recv_key_len);
+struct radius_attr_hdr *
+radius_msg_add_attr_user_password(struct radius_msg *msg,
+				  const u8 *data, size_t data_len,
+				  const u8 *secret, size_t secret_len);
+int radius_msg_get_attr(struct radius_msg *msg, u8 type, u8 *buf, size_t len);
+int radius_msg_get_vlanid(struct radius_msg *msg);
+
+static inline int radius_msg_add_attr_int32(struct radius_msg *msg, u8 type,
+					    u32 value)
+{
+	u32 val = htonl(value);
+	return radius_msg_add_attr(msg, type, (u8 *) &val, 4) != NULL;
+}
+
+static inline int radius_msg_get_attr_int32(struct radius_msg *msg, u8 type,
+					    u32 *value)
+{
+	u32 val;
+	int res;
+	res = radius_msg_get_attr(msg, type, (u8 *) &val, 4);
+	if (res != 4)
+		return -1;
+
+	*value = ntohl(val);
+	return 0;
+}
+int radius_msg_get_attr_ptr(struct radius_msg *msg, u8 type, u8 **buf,
+			    size_t *len, const u8 *start);
+int radius_msg_count_attr(struct radius_msg *msg, u8 type, int min_len);
+
+
+struct radius_attr_data {
+	u8 *data;
+	size_t len;
+};
+
+struct radius_class_data {
+	struct radius_attr_data *attr;
+	size_t count;
+};
+
+void radius_free_class(struct radius_class_data *c);
+int radius_copy_class(struct radius_class_data *dst,
+		      const struct radius_class_data *src);
+
+#endif /* RADIUS_H */
diff --git a/src/radius/radius_client.c b/src/radius/radius_client.c
new file mode 100644
index 0000000..691f77a
--- /dev/null
+++ b/src/radius/radius_client.c
@@ -0,0 +1,1499 @@
+/*
+ * RADIUS client
+ * Copyright (c) 2002-2009, Jouni Malinen <j@w1.fi>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ *
+ * Alternatively, this software may be distributed under the terms of BSD
+ * license.
+ *
+ * See README and COPYING for more details.
+ */
+
+#include "includes.h"
+
+#include "common.h"
+#include "radius.h"
+#include "radius_client.h"
+#include "eloop.h"
+
+/* Defaults for RADIUS retransmit values (exponential backoff) */
+
+/**
+ * RADIUS_CLIENT_FIRST_WAIT - RADIUS client timeout for first retry in seconds
+ */
+#define RADIUS_CLIENT_FIRST_WAIT 3
+
+/**
+ * RADIUS_CLIENT_MAX_WAIT - RADIUS client maximum retry timeout in seconds
+ */
+#define RADIUS_CLIENT_MAX_WAIT 120
+
+/**
+ * RADIUS_CLIENT_MAX_RETRIES - RADIUS client maximum retries
+ *
+ * Maximum number of retransmit attempts before the entry is removed from
+ * retransmit list.
+ */
+#define RADIUS_CLIENT_MAX_RETRIES 10
+
+/**
+ * RADIUS_CLIENT_MAX_ENTRIES - RADIUS client maximum pending messages
+ *
+ * Maximum number of entries in retransmit list (oldest entries will be
+ * removed, if this limit is exceeded).
+ */
+#define RADIUS_CLIENT_MAX_ENTRIES 30
+
+/**
+ * RADIUS_CLIENT_NUM_FAILOVER - RADIUS client failover point
+ *
+ * The number of failed retry attempts after which the RADIUS server will be
+ * changed (if one of more backup servers are configured).
+ */
+#define RADIUS_CLIENT_NUM_FAILOVER 4
+
+
+/**
+ * struct radius_rx_handler - RADIUS client RX handler
+ *
+ * This data structure is used internally inside the RADIUS client module to
+ * store registered RX handlers. These handlers are registered by calls to
+ * radius_client_register() and unregistered when the RADIUS client is
+ * deinitialized with a call to radius_client_deinit().
+ */
+struct radius_rx_handler {
+	/**
+	 * handler - Received RADIUS message handler
+	 */
+	RadiusRxResult (*handler)(struct radius_msg *msg,
+				  struct radius_msg *req,
+				  const u8 *shared_secret,
+				  size_t shared_secret_len,
+				  void *data);
+
+	/**
+	 * data - Context data for the handler
+	 */
+	void *data;
+};
+
+
+/**
+ * struct radius_msg_list - RADIUS client message retransmit list
+ *
+ * This data structure is used internally inside the RADIUS client module to
+ * store pending RADIUS requests that may still need to be retransmitted.
+ */
+struct radius_msg_list {
+	/**
+	 * addr - STA/client address
+	 *
+	 * This is used to find RADIUS messages for the same STA.
+	 */
+	u8 addr[ETH_ALEN];
+
+	/**
+	 * msg - RADIUS message
+	 */
+	struct radius_msg *msg;
+
+	/**
+	 * msg_type - Message type
+	 */
+	RadiusType msg_type;
+
+	/**
+	 * first_try - Time of the first transmission attempt
+	 */
+	os_time_t first_try;
+
+	/**
+	 * next_try - Time for the next transmission attempt
+	 */
+	os_time_t next_try;
+
+	/**
+	 * attempts - Number of transmission attempts
+	 */
+	int attempts;
+
+	/**
+	 * next_wait - Next retransmission wait time in seconds
+	 */
+	int next_wait;
+
+	/**
+	 * last_attempt - Time of the last transmission attempt
+	 */
+	struct os_time last_attempt;
+
+	/**
+	 * shared_secret - Shared secret with the target RADIUS server
+	 */
+	const u8 *shared_secret;
+
+	/**
+	 * shared_secret_len - shared_secret length in octets
+	 */
+	size_t shared_secret_len;
+
+	/* TODO: server config with failover to backup server(s) */
+
+	/**
+	 * next - Next message in the list
+	 */
+	struct radius_msg_list *next;
+};
+
+
+/**
+ * struct radius_client_data - Internal RADIUS client data
+ *
+ * This data structure is used internally inside the RADIUS client module.
+ * External users allocate this by calling radius_client_init() and free it by
+ * calling radius_client_deinit(). The pointer to this opaque data is used in
+ * calls to other functions as an identifier for the RADIUS client instance.
+ */
+struct radius_client_data {
+	/**
+	 * ctx - Context pointer for hostapd_logger() callbacks
+	 */
+	void *ctx;
+
+	/**
+	 * conf - RADIUS client configuration (list of RADIUS servers to use)
+	 */
+	struct hostapd_radius_servers *conf;
+
+	/**
+	 * auth_serv_sock - IPv4 socket for RADIUS authentication messages
+	 */
+	int auth_serv_sock;
+
+	/**
+	 * acct_serv_sock - IPv4 socket for RADIUS accounting messages
+	 */
+	int acct_serv_sock;
+
+	/**
+	 * auth_serv_sock6 - IPv6 socket for RADIUS authentication messages
+	 */
+	int auth_serv_sock6;
+
+	/**
+	 * acct_serv_sock6 - IPv6 socket for RADIUS accounting messages
+	 */
+	int acct_serv_sock6;
+
+	/**
+	 * auth_sock - Currently used socket for RADIUS authentication server
+	 */
+	int auth_sock;
+
+	/**
+	 * acct_sock - Currently used socket for RADIUS accounting server
+	 */
+	int acct_sock;
+
+	/**
+	 * auth_handlers - Authentication message handlers
+	 */
+	struct radius_rx_handler *auth_handlers;
+
+	/**
+	 * num_auth_handlers - Number of handlers in auth_handlers
+	 */
+	size_t num_auth_handlers;
+
+	/**
+	 * acct_handlers - Accounting message handlers
+	 */
+	struct radius_rx_handler *acct_handlers;
+
+	/**
+	 * num_acct_handlers - Number of handlers in acct_handlers
+	 */
+	size_t num_acct_handlers;
+
+	/**
+	 * msgs - Pending outgoing RADIUS messages
+	 */
+	struct radius_msg_list *msgs;
+
+	/**
+	 * num_msgs - Number of pending messages in the msgs list
+	 */
+	size_t num_msgs;
+
+	/**
+	 * next_radius_identifier - Next RADIUS message identifier to use
+	 */
+	u8 next_radius_identifier;
+};
+
+
+static int
+radius_change_server(struct radius_client_data *radius,
+		     struct hostapd_radius_server *nserv,
+		     struct hostapd_radius_server *oserv,
+		     int sock, int sock6, int auth);
+static int radius_client_init_acct(struct radius_client_data *radius);
+static int radius_client_init_auth(struct radius_client_data *radius);
+
+
+static void radius_client_msg_free(struct radius_msg_list *req)
+{
+	radius_msg_free(req->msg);
+	os_free(req);
+}
+
+
+/**
+ * radius_client_register - Register a RADIUS client RX handler
+ * @radius: RADIUS client context from radius_client_init()
+ * @msg_type: RADIUS client type (RADIUS_AUTH or RADIUS_ACCT)
+ * @handler: Handler for received RADIUS messages
+ * @data: Context pointer for handler callbacks
+ * Returns: 0 on success, -1 on failure
+ *
+ * This function is used to register a handler for processing received RADIUS
+ * authentication and accounting messages. The handler() callback function will
+ * be called whenever a RADIUS message is received from the active server.
+ *
+ * There can be multiple registered RADIUS message handlers. The handlers will
+ * be called in order until one of them indicates that it has processed or
+ * queued the message.
+ */
+int radius_client_register(struct radius_client_data *radius,
+			   RadiusType msg_type,
+			   RadiusRxResult (*handler)(struct radius_msg *msg,
+						     struct radius_msg *req,
+						     const u8 *shared_secret,
+						     size_t shared_secret_len,
+						     void *data),
+			   void *data)
+{
+	struct radius_rx_handler **handlers, *newh;
+	size_t *num;
+
+	if (msg_type == RADIUS_ACCT) {
+		handlers = &radius->acct_handlers;
+		num = &radius->num_acct_handlers;
+	} else {
+		handlers = &radius->auth_handlers;
+		num = &radius->num_auth_handlers;
+	}
+
+	newh = os_realloc(*handlers,
+			  (*num + 1) * sizeof(struct radius_rx_handler));
+	if (newh == NULL)
+		return -1;
+
+	newh[*num].handler = handler;
+	newh[*num].data = data;
+	(*num)++;
+	*handlers = newh;
+
+	return 0;
+}
+
+
+static void radius_client_handle_send_error(struct radius_client_data *radius,
+					    int s, RadiusType msg_type)
+{
+#ifndef CONFIG_NATIVE_WINDOWS
+	int _errno = errno;
+	perror("send[RADIUS]");
+	if (_errno == ENOTCONN || _errno == EDESTADDRREQ || _errno == EINVAL ||
+	    _errno == EBADF) {
+		hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
+			       HOSTAPD_LEVEL_INFO,
+			       "Send failed - maybe interface status changed -"
+			       " try to connect again");
+		eloop_unregister_read_sock(s);
+		close(s);
+		if (msg_type == RADIUS_ACCT || msg_type == RADIUS_ACCT_INTERIM)
+			radius_client_init_acct(radius);
+		else
+			radius_client_init_auth(radius);
+	}
+#endif /* CONFIG_NATIVE_WINDOWS */
+}
+
+
+static int radius_client_retransmit(struct radius_client_data *radius,
+				    struct radius_msg_list *entry,
+				    os_time_t now)
+{
+	struct hostapd_radius_servers *conf = radius->conf;
+	int s;
+	struct wpabuf *buf;
+
+	if (entry->msg_type == RADIUS_ACCT ||
+	    entry->msg_type == RADIUS_ACCT_INTERIM) {
+		s = radius->acct_sock;
+		if (entry->attempts == 0)
+			conf->acct_server->requests++;
+		else {
+			conf->acct_server->timeouts++;
+			conf->acct_server->retransmissions++;
+		}
+	} else {
+		s = radius->auth_sock;
+		if (entry->attempts == 0)
+			conf->auth_server->requests++;
+		else {
+			conf->auth_server->timeouts++;
+			conf->auth_server->retransmissions++;
+		}
+	}
+
+	/* retransmit; remove entry if too many attempts */
+	entry->attempts++;
+	hostapd_logger(radius->ctx, entry->addr, HOSTAPD_MODULE_RADIUS,
+		       HOSTAPD_LEVEL_DEBUG, "Resending RADIUS message (id=%d)",
+		       radius_msg_get_hdr(entry->msg)->identifier);
+
+	os_get_time(&entry->last_attempt);
+	buf = radius_msg_get_buf(entry->msg);
+	if (send(s, wpabuf_head(buf), wpabuf_len(buf), 0) < 0)
+		radius_client_handle_send_error(radius, s, entry->msg_type);
+
+	entry->next_try = now + entry->next_wait;
+	entry->next_wait *= 2;
+	if (entry->next_wait > RADIUS_CLIENT_MAX_WAIT)
+		entry->next_wait = RADIUS_CLIENT_MAX_WAIT;
+	if (entry->attempts >= RADIUS_CLIENT_MAX_RETRIES) {
+		printf("Removing un-ACKed RADIUS message due to too many "
+		       "failed retransmit attempts\n");
+		return 1;
+	}
+
+	return 0;
+}
+
+
+static void radius_client_timer(void *eloop_ctx, void *timeout_ctx)
+{
+	struct radius_client_data *radius = eloop_ctx;
+	struct hostapd_radius_servers *conf = radius->conf;
+	struct os_time now;
+	os_time_t first;
+	struct radius_msg_list *entry, *prev, *tmp;
+	int auth_failover = 0, acct_failover = 0;
+	char abuf[50];
+
+	entry = radius->msgs;
+	if (!entry)
+		return;
+
+	os_get_time(&now);
+	first = 0;
+
+	prev = NULL;
+	while (entry) {
+		if (now.sec >= entry->next_try &&
+		    radius_client_retransmit(radius, entry, now.sec)) {
+			if (prev)
+				prev->next = entry->next;
+			else
+				radius->msgs = entry->next;
+
+			tmp = entry;
+			entry = entry->next;
+			radius_client_msg_free(tmp);
+			radius->num_msgs--;
+			continue;
+		}
+
+		if (entry->attempts > RADIUS_CLIENT_NUM_FAILOVER) {
+			if (entry->msg_type == RADIUS_ACCT ||
+			    entry->msg_type == RADIUS_ACCT_INTERIM)
+				acct_failover++;
+			else
+				auth_failover++;
+		}
+
+		if (first == 0 || entry->next_try < first)
+			first = entry->next_try;
+
+		prev = entry;
+		entry = entry->next;
+	}
+
+	if (radius->msgs) {
+		if (first < now.sec)
+			first = now.sec;
+		eloop_register_timeout(first - now.sec, 0,
+				       radius_client_timer, radius, NULL);
+		hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
+			       HOSTAPD_LEVEL_DEBUG, "Next RADIUS client "
+			       "retransmit in %ld seconds",
+			       (long int) (first - now.sec));
+	}
+
+	if (auth_failover && conf->num_auth_servers > 1) {
+		struct hostapd_radius_server *next, *old;
+		old = conf->auth_server;
+		hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
+			       HOSTAPD_LEVEL_NOTICE,
+			       "No response from Authentication server "
+			       "%s:%d - failover",
+			       hostapd_ip_txt(&old->addr, abuf, sizeof(abuf)),
+			       old->port);
+
+		for (entry = radius->msgs; entry; entry = entry->next) {
+			if (entry->msg_type == RADIUS_AUTH)
+				old->timeouts++;
+		}
+
+		next = old + 1;
+		if (next > &(conf->auth_servers[conf->num_auth_servers - 1]))
+			next = conf->auth_servers;
+		conf->auth_server = next;
+		radius_change_server(radius, next, old,
+				     radius->auth_serv_sock,
+				     radius->auth_serv_sock6, 1);
+	}
+
+	if (acct_failover && conf->num_acct_servers > 1) {
+		struct hostapd_radius_server *next, *old;
+		old = conf->acct_server;
+		hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
+			       HOSTAPD_LEVEL_NOTICE,
+			       "No response from Accounting server "
+			       "%s:%d - failover",
+			       hostapd_ip_txt(&old->addr, abuf, sizeof(abuf)),
+			       old->port);
+
+		for (entry = radius->msgs; entry; entry = entry->next) {
+			if (entry->msg_type == RADIUS_ACCT ||
+			    entry->msg_type == RADIUS_ACCT_INTERIM)
+				old->timeouts++;
+		}
+
+		next = old + 1;
+		if (next > &conf->acct_servers[conf->num_acct_servers - 1])
+			next = conf->acct_servers;
+		conf->acct_server = next;
+		radius_change_server(radius, next, old,
+				     radius->acct_serv_sock,
+				     radius->acct_serv_sock6, 0);
+	}
+}
+
+
+static void radius_client_update_timeout(struct radius_client_data *radius)
+{
+	struct os_time now;
+	os_time_t first;
+	struct radius_msg_list *entry;
+
+	eloop_cancel_timeout(radius_client_timer, radius, NULL);
+
+	if (radius->msgs == NULL) {
+		return;
+	}
+
+	first = 0;
+	for (entry = radius->msgs; entry; entry = entry->next) {
+		if (first == 0 || entry->next_try < first)
+			first = entry->next_try;
+	}
+
+	os_get_time(&now);
+	if (first < now.sec)
+		first = now.sec;
+	eloop_register_timeout(first - now.sec, 0, radius_client_timer, radius,
+			       NULL);
+	hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
+		       HOSTAPD_LEVEL_DEBUG, "Next RADIUS client retransmit in"
+		       " %ld seconds\n", (long int) (first - now.sec));
+}
+
+
+static void radius_client_list_add(struct radius_client_data *radius,
+				   struct radius_msg *msg,
+				   RadiusType msg_type,
+				   const u8 *shared_secret,
+				   size_t shared_secret_len, const u8 *addr)
+{
+	struct radius_msg_list *entry, *prev;
+
+	if (eloop_terminated()) {
+		/* No point in adding entries to retransmit queue since event
+		 * loop has already been terminated. */
+		radius_msg_free(msg);
+		return;
+	}
+
+	entry = os_zalloc(sizeof(*entry));
+	if (entry == NULL) {
+		printf("Failed to add RADIUS packet into retransmit list\n");
+		radius_msg_free(msg);
+		return;
+	}
+
+	if (addr)
+		os_memcpy(entry->addr, addr, ETH_ALEN);
+	entry->msg = msg;
+	entry->msg_type = msg_type;
+	entry->shared_secret = shared_secret;
+	entry->shared_secret_len = shared_secret_len;
+	os_get_time(&entry->last_attempt);
+	entry->first_try = entry->last_attempt.sec;
+	entry->next_try = entry->first_try + RADIUS_CLIENT_FIRST_WAIT;
+	entry->attempts = 1;
+	entry->next_wait = RADIUS_CLIENT_FIRST_WAIT * 2;
+	entry->next = radius->msgs;
+	radius->msgs = entry;
+	radius_client_update_timeout(radius);
+
+	if (radius->num_msgs >= RADIUS_CLIENT_MAX_ENTRIES) {
+		printf("Removing the oldest un-ACKed RADIUS packet due to "
+		       "retransmit list limits.\n");
+		prev = NULL;
+		while (entry->next) {
+			prev = entry;
+			entry = entry->next;
+		}
+		if (prev) {
+			prev->next = NULL;
+			radius_client_msg_free(entry);
+		}
+	} else
+		radius->num_msgs++;
+}
+
+
+static void radius_client_list_del(struct radius_client_data *radius,
+				   RadiusType msg_type, const u8 *addr)
+{
+	struct radius_msg_list *entry, *prev, *tmp;
+
+	if (addr == NULL)
+		return;
+
+	entry = radius->msgs;
+	prev = NULL;
+	while (entry) {
+		if (entry->msg_type == msg_type &&
+		    os_memcmp(entry->addr, addr, ETH_ALEN) == 0) {
+			if (prev)
+				prev->next = entry->next;
+			else
+				radius->msgs = entry->next;
+			tmp = entry;
+			entry = entry->next;
+			hostapd_logger(radius->ctx, addr,
+				       HOSTAPD_MODULE_RADIUS,
+				       HOSTAPD_LEVEL_DEBUG,
+				       "Removing matching RADIUS message");
+			radius_client_msg_free(tmp);
+			radius->num_msgs--;
+			continue;
+		}
+		prev = entry;
+		entry = entry->next;
+	}
+}
+
+
+/**
+ * radius_client_send - Send a RADIUS request
+ * @radius: RADIUS client context from radius_client_init()
+ * @msg: RADIUS message to be sent
+ * @msg_type: Message type (RADIUS_AUTH, RADIUS_ACCT, RADIUS_ACCT_INTERIM)
+ * @addr: MAC address of the device related to this message or %NULL
+ * Returns: 0 on success, -1 on failure
+ *
+ * This function is used to transmit a RADIUS authentication (RADIUS_AUTH) or
+ * accounting request (RADIUS_ACCT or RADIUS_ACCT_INTERIM). The only difference
+ * between accounting and interim accounting messages is that the interim
+ * message will override any pending interim accounting updates while a new
+ * accounting message does not remove any pending messages.
+ *
+ * The message is added on the retransmission queue and will be retransmitted
+ * automatically until a response is received or maximum number of retries
+ * (RADIUS_CLIENT_MAX_RETRIES) is reached.
+ *
+ * The related device MAC address can be used to identify pending messages that
+ * can be removed with radius_client_flush_auth() or with interim accounting
+ * updates.
+ */
+int radius_client_send(struct radius_client_data *radius,
+		       struct radius_msg *msg, RadiusType msg_type,
+		       const u8 *addr)
+{
+	struct hostapd_radius_servers *conf = radius->conf;
+	const u8 *shared_secret;
+	size_t shared_secret_len;
+	char *name;
+	int s, res;
+	struct wpabuf *buf;
+
+	if (msg_type == RADIUS_ACCT_INTERIM) {
+		/* Remove any pending interim acct update for the same STA. */
+		radius_client_list_del(radius, msg_type, addr);
+	}
+
+	if (msg_type == RADIUS_ACCT || msg_type == RADIUS_ACCT_INTERIM) {
+		if (conf->acct_server == NULL) {
+			hostapd_logger(radius->ctx, NULL,
+				       HOSTAPD_MODULE_RADIUS,
+				       HOSTAPD_LEVEL_INFO,
+				       "No accounting server configured");
+			return -1;
+		}
+		shared_secret = conf->acct_server->shared_secret;
+		shared_secret_len = conf->acct_server->shared_secret_len;
+		radius_msg_finish_acct(msg, shared_secret, shared_secret_len);
+		name = "accounting";
+		s = radius->acct_sock;
+		conf->acct_server->requests++;
+	} else {
+		if (conf->auth_server == NULL) {
+			hostapd_logger(radius->ctx, NULL,
+				       HOSTAPD_MODULE_RADIUS,
+				       HOSTAPD_LEVEL_INFO,
+				       "No authentication server configured");
+			return -1;
+		}
+		shared_secret = conf->auth_server->shared_secret;
+		shared_secret_len = conf->auth_server->shared_secret_len;
+		radius_msg_finish(msg, shared_secret, shared_secret_len);
+		name = "authentication";
+		s = radius->auth_sock;
+		conf->auth_server->requests++;
+	}
+
+	hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
+		       HOSTAPD_LEVEL_DEBUG, "Sending RADIUS message to %s "
+		       "server", name);
+	if (conf->msg_dumps)
+		radius_msg_dump(msg);
+
+	buf = radius_msg_get_buf(msg);
+	res = send(s, wpabuf_head(buf), wpabuf_len(buf), 0);
+	if (res < 0)
+		radius_client_handle_send_error(radius, s, msg_type);
+
+	radius_client_list_add(radius, msg, msg_type, shared_secret,
+			       shared_secret_len, addr);
+
+	return res;
+}
+
+
+static void radius_client_receive(int sock, void *eloop_ctx, void *sock_ctx)
+{
+	struct radius_client_data *radius = eloop_ctx;
+	struct hostapd_radius_servers *conf = radius->conf;
+	RadiusType msg_type = (RadiusType) sock_ctx;
+	int len, roundtrip;
+	unsigned char buf[3000];
+	struct radius_msg *msg;
+	struct radius_hdr *hdr;
+	struct radius_rx_handler *handlers;
+	size_t num_handlers, i;
+	struct radius_msg_list *req, *prev_req;
+	struct os_time now;
+	struct hostapd_radius_server *rconf;
+	int invalid_authenticator = 0;
+
+	if (msg_type == RADIUS_ACCT) {
+		handlers = radius->acct_handlers;
+		num_handlers = radius->num_acct_handlers;
+		rconf = conf->acct_server;
+	} else {
+		handlers = radius->auth_handlers;
+		num_handlers = radius->num_auth_handlers;
+		rconf = conf->auth_server;
+	}
+
+	len = recv(sock, buf, sizeof(buf), MSG_DONTWAIT);
+	if (len < 0) {
+		perror("recv[RADIUS]");
+		return;
+	}
+	hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
+		       HOSTAPD_LEVEL_DEBUG, "Received %d bytes from RADIUS "
+		       "server", len);
+	if (len == sizeof(buf)) {
+		printf("Possibly too long UDP frame for our buffer - "
+		       "dropping it\n");
+		return;
+	}
+
+	msg = radius_msg_parse(buf, len);
+	if (msg == NULL) {
+		printf("Parsing incoming RADIUS frame failed\n");
+		rconf->malformed_responses++;
+		return;
+	}
+	hdr = radius_msg_get_hdr(msg);
+
+	hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
+		       HOSTAPD_LEVEL_DEBUG, "Received RADIUS message");
+	if (conf->msg_dumps)
+		radius_msg_dump(msg);
+
+	switch (hdr->code) {
+	case RADIUS_CODE_ACCESS_ACCEPT:
+		rconf->access_accepts++;
+		break;
+	case RADIUS_CODE_ACCESS_REJECT:
+		rconf->access_rejects++;
+		break;
+	case RADIUS_CODE_ACCESS_CHALLENGE:
+		rconf->access_challenges++;
+		break;
+	case RADIUS_CODE_ACCOUNTING_RESPONSE:
+		rconf->responses++;
+		break;
+	}
+
+	prev_req = NULL;
+	req = radius->msgs;
+	while (req) {
+		/* TODO: also match by src addr:port of the packet when using
+		 * alternative RADIUS servers (?) */
+		if ((req->msg_type == msg_type ||
+		     (req->msg_type == RADIUS_ACCT_INTERIM &&
+		      msg_type == RADIUS_ACCT)) &&
+		    radius_msg_get_hdr(req->msg)->identifier ==
+		    hdr->identifier)
+			break;
+
+		prev_req = req;
+		req = req->next;
+	}
+
+	if (req == NULL) {
+		hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
+			       HOSTAPD_LEVEL_DEBUG,
+			       "No matching RADIUS request found (type=%d "
+			       "id=%d) - dropping packet",
+			       msg_type, hdr->identifier);
+		goto fail;
+	}
+
+	os_get_time(&now);
+	roundtrip = (now.sec - req->last_attempt.sec) * 100 +
+		(now.usec - req->last_attempt.usec) / 10000;
+	hostapd_logger(radius->ctx, req->addr, HOSTAPD_MODULE_RADIUS,
+		       HOSTAPD_LEVEL_DEBUG,
+		       "Received RADIUS packet matched with a pending "
+		       "request, round trip time %d.%02d sec",
+		       roundtrip / 100, roundtrip % 100);
+	rconf->round_trip_time = roundtrip;
+
+	/* Remove ACKed RADIUS packet from retransmit list */
+	if (prev_req)
+		prev_req->next = req->next;
+	else
+		radius->msgs = req->next;
+	radius->num_msgs--;
+
+	for (i = 0; i < num_handlers; i++) {
+		RadiusRxResult res;
+		res = handlers[i].handler(msg, req->msg, req->shared_secret,
+					  req->shared_secret_len,
+					  handlers[i].data);
+		switch (res) {
+		case RADIUS_RX_PROCESSED:
+			radius_msg_free(msg);
+			/* continue */
+		case RADIUS_RX_QUEUED:
+			radius_client_msg_free(req);
+			return;
+		case RADIUS_RX_INVALID_AUTHENTICATOR:
+			invalid_authenticator++;
+			/* continue */
+		case RADIUS_RX_UNKNOWN:
+			/* continue with next handler */
+			break;
+		}
+	}
+
+	if (invalid_authenticator)
+		rconf->bad_authenticators++;
+	else
+		rconf->unknown_types++;
+	hostapd_logger(radius->ctx, req->addr, HOSTAPD_MODULE_RADIUS,
+		       HOSTAPD_LEVEL_DEBUG, "No RADIUS RX handler found "
+		       "(type=%d code=%d id=%d)%s - dropping packet",
+		       msg_type, hdr->code, hdr->identifier,
+		       invalid_authenticator ? " [INVALID AUTHENTICATOR]" :
+		       "");
+	radius_client_msg_free(req);
+
+ fail:
+	radius_msg_free(msg);
+}
+
+
+/**
+ * radius_client_get_id - Get an identifier for a new RADIUS message
+ * @radius: RADIUS client context from radius_client_init()
+ * Returns: Allocated identifier
+ *
+ * This function is used to fetch a unique (among pending requests) identifier
+ * for a new RADIUS message.
+ */
+u8 radius_client_get_id(struct radius_client_data *radius)
+{
+	struct radius_msg_list *entry, *prev, *_remove;
+	u8 id = radius->next_radius_identifier++;
+
+	/* remove entries with matching id from retransmit list to avoid
+	 * using new reply from the RADIUS server with an old request */
+	entry = radius->msgs;
+	prev = NULL;
+	while (entry) {
+		if (radius_msg_get_hdr(entry->msg)->identifier == id) {
+			hostapd_logger(radius->ctx, entry->addr,
+				       HOSTAPD_MODULE_RADIUS,
+				       HOSTAPD_LEVEL_DEBUG,
+				       "Removing pending RADIUS message, "
+				       "since its id (%d) is reused", id);
+			if (prev)
+				prev->next = entry->next;
+			else
+				radius->msgs = entry->next;
+			_remove = entry;
+		} else {
+			_remove = NULL;
+			prev = entry;
+		}
+		entry = entry->next;
+
+		if (_remove)
+			radius_client_msg_free(_remove);
+	}
+
+	return id;
+}
+
+
+/**
+ * radius_client_flush - Flush all pending RADIUS client messages
+ * @radius: RADIUS client context from radius_client_init()
+ * @only_auth: Whether only authentication messages are removed
+ */
+void radius_client_flush(struct radius_client_data *radius, int only_auth)
+{
+	struct radius_msg_list *entry, *prev, *tmp;
+
+	if (!radius)
+		return;
+
+	prev = NULL;
+	entry = radius->msgs;
+
+	while (entry) {
+		if (!only_auth || entry->msg_type == RADIUS_AUTH) {
+			if (prev)
+				prev->next = entry->next;
+			else
+				radius->msgs = entry->next;
+
+			tmp = entry;
+			entry = entry->next;
+			radius_client_msg_free(tmp);
+			radius->num_msgs--;
+		} else {
+			prev = entry;
+			entry = entry->next;
+		}
+	}
+
+	if (radius->msgs == NULL)
+		eloop_cancel_timeout(radius_client_timer, radius, NULL);
+}
+
+
+static void radius_client_update_acct_msgs(struct radius_client_data *radius,
+					   const u8 *shared_secret,
+					   size_t shared_secret_len)
+{
+	struct radius_msg_list *entry;
+
+	if (!radius)
+		return;
+
+	for (entry = radius->msgs; entry; entry = entry->next) {
+		if (entry->msg_type == RADIUS_ACCT) {
+			entry->shared_secret = shared_secret;
+			entry->shared_secret_len = shared_secret_len;
+			radius_msg_finish_acct(entry->msg, shared_secret,
+					       shared_secret_len);
+		}
+	}
+}
+
+
+static int
+radius_change_server(struct radius_client_data *radius,
+		     struct hostapd_radius_server *nserv,
+		     struct hostapd_radius_server *oserv,
+		     int sock, int sock6, int auth)
+{
+	struct sockaddr_in serv, claddr;
+#ifdef CONFIG_IPV6
+	struct sockaddr_in6 serv6, claddr6;
+#endif /* CONFIG_IPV6 */
+	struct sockaddr *addr, *cl_addr;
+	socklen_t addrlen, claddrlen;
+	char abuf[50];
+	int sel_sock;
+	struct radius_msg_list *entry;
+	struct hostapd_radius_servers *conf = radius->conf;
+
+	hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
+		       HOSTAPD_LEVEL_INFO,
+		       "%s server %s:%d",
+		       auth ? "Authentication" : "Accounting",
+		       hostapd_ip_txt(&nserv->addr, abuf, sizeof(abuf)),
+		       nserv->port);
+
+	if (!oserv || nserv->shared_secret_len != oserv->shared_secret_len ||
+	    os_memcmp(nserv->shared_secret, oserv->shared_secret,
+		      nserv->shared_secret_len) != 0) {
+		/* Pending RADIUS packets used different shared secret, so
+		 * they need to be modified. Update accounting message
+		 * authenticators here. Authentication messages are removed
+		 * since they would require more changes and the new RADIUS
+		 * server may not be prepared to receive them anyway due to
+		 * missing state information. Client will likely retry
+		 * authentication, so this should not be an issue. */
+		if (auth)
+			radius_client_flush(radius, 1);
+		else {
+			radius_client_update_acct_msgs(
+				radius, nserv->shared_secret,
+				nserv->shared_secret_len);
+		}
+	}
+
+	/* Reset retry counters for the new server */
+	for (entry = radius->msgs; entry; entry = entry->next) {
+		if ((auth && entry->msg_type != RADIUS_AUTH) ||
+		    (!auth && entry->msg_type != RADIUS_ACCT))
+			continue;
+		entry->next_try = entry->first_try + RADIUS_CLIENT_FIRST_WAIT;
+		entry->attempts = 0;
+		entry->next_wait = RADIUS_CLIENT_FIRST_WAIT * 2;
+	}
+
+	if (radius->msgs) {
+		eloop_cancel_timeout(radius_client_timer, radius, NULL);
+		eloop_register_timeout(RADIUS_CLIENT_FIRST_WAIT, 0,
+				       radius_client_timer, radius, NULL);
+	}
+
+	switch (nserv->addr.af) {
+	case AF_INET:
+		os_memset(&serv, 0, sizeof(serv));
+		serv.sin_family = AF_INET;
+		serv.sin_addr.s_addr = nserv->addr.u.v4.s_addr;
+		serv.sin_port = htons(nserv->port);
+		addr = (struct sockaddr *) &serv;
+		addrlen = sizeof(serv);
+		sel_sock = sock;
+		break;
+#ifdef CONFIG_IPV6
+	case AF_INET6:
+		os_memset(&serv6, 0, sizeof(serv6));
+		serv6.sin6_family = AF_INET6;
+		os_memcpy(&serv6.sin6_addr, &nserv->addr.u.v6,
+			  sizeof(struct in6_addr));
+		serv6.sin6_port = htons(nserv->port);
+		addr = (struct sockaddr *) &serv6;
+		addrlen = sizeof(serv6);
+		sel_sock = sock6;
+		break;
+#endif /* CONFIG_IPV6 */
+	default:
+		return -1;
+	}
+
+	if (conf->force_client_addr) {
+		switch (conf->client_addr.af) {
+		case AF_INET:
+			os_memset(&claddr, 0, sizeof(claddr));
+			claddr.sin_family = AF_INET;
+			claddr.sin_addr.s_addr = conf->client_addr.u.v4.s_addr;
+			claddr.sin_port = htons(0);
+			cl_addr = (struct sockaddr *) &claddr;
+			claddrlen = sizeof(claddr);
+			break;
+#ifdef CONFIG_IPV6
+		case AF_INET6:
+			os_memset(&claddr6, 0, sizeof(claddr6));
+			claddr6.sin6_family = AF_INET6;
+			os_memcpy(&claddr6.sin6_addr, &conf->client_addr.u.v6,
+				  sizeof(struct in6_addr));
+			claddr6.sin6_port = htons(0);
+			cl_addr = (struct sockaddr *) &claddr6;
+			claddrlen = sizeof(claddr6);
+			break;
+#endif /* CONFIG_IPV6 */
+		default:
+			return -1;
+		}
+
+		if (bind(sel_sock, cl_addr, claddrlen) < 0) {
+			perror("bind[radius]");
+			return -1;
+		}
+	}
+
+	if (connect(sel_sock, addr, addrlen) < 0) {
+		perror("connect[radius]");
+		return -1;
+	}
+
+#ifndef CONFIG_NATIVE_WINDOWS
+	switch (nserv->addr.af) {
+	case AF_INET:
+		claddrlen = sizeof(claddr);
+		getsockname(sel_sock, (struct sockaddr *) &claddr, &claddrlen);
+		wpa_printf(MSG_DEBUG, "RADIUS local address: %s:%u",
+			   inet_ntoa(claddr.sin_addr), ntohs(claddr.sin_port));
+		break;
+#ifdef CONFIG_IPV6
+	case AF_INET6: {
+		claddrlen = sizeof(claddr6);
+		getsockname(sel_sock, (struct sockaddr *) &claddr6,
+			    &claddrlen);
+		wpa_printf(MSG_DEBUG, "RADIUS local address: %s:%u",
+			   inet_ntop(AF_INET6, &claddr6.sin6_addr,
+				     abuf, sizeof(abuf)),
+			   ntohs(claddr6.sin6_port));
+		break;
+	}
+#endif /* CONFIG_IPV6 */
+	}
+#endif /* CONFIG_NATIVE_WINDOWS */
+
+	if (auth)
+		radius->auth_sock = sel_sock;
+	else
+		radius->acct_sock = sel_sock;
+
+	return 0;
+}
+
+
+static void radius_retry_primary_timer(void *eloop_ctx, void *timeout_ctx)
+{
+	struct radius_client_data *radius = eloop_ctx;
+	struct hostapd_radius_servers *conf = radius->conf;
+	struct hostapd_radius_server *oserv;
+
+	if (radius->auth_sock >= 0 && conf->auth_servers &&
+	    conf->auth_server != conf->auth_servers) {
+		oserv = conf->auth_server;
+		conf->auth_server = conf->auth_servers;
+		radius_change_server(radius, conf->auth_server, oserv,
+				     radius->auth_serv_sock,
+				     radius->auth_serv_sock6, 1);
+	}
+
+	if (radius->acct_sock >= 0 && conf->acct_servers &&
+	    conf->acct_server != conf->acct_servers) {
+		oserv = conf->acct_server;
+		conf->acct_server = conf->acct_servers;
+		radius_change_server(radius, conf->acct_server, oserv,
+				     radius->acct_serv_sock,
+				     radius->acct_serv_sock6, 0);
+	}
+
+	if (conf->retry_primary_interval)
+		eloop_register_timeout(conf->retry_primary_interval, 0,
+				       radius_retry_primary_timer, radius,
+				       NULL);
+}
+
+
+static int radius_client_disable_pmtu_discovery(int s)
+{
+	int r = -1;
+#if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
+	/* Turn off Path MTU discovery on IPv4/UDP sockets. */
+	int action = IP_PMTUDISC_DONT;
+	r = setsockopt(s, IPPROTO_IP, IP_MTU_DISCOVER, &action,
+		       sizeof(action));
+	if (r == -1)
+		wpa_printf(MSG_ERROR, "Failed to set IP_MTU_DISCOVER: "
+			   "%s", strerror(errno));
+#endif
+	return r;
+}
+
+
+static int radius_client_init_auth(struct radius_client_data *radius)
+{
+	struct hostapd_radius_servers *conf = radius->conf;
+	int ok = 0;
+
+	radius->auth_serv_sock = socket(PF_INET, SOCK_DGRAM, 0);
+	if (radius->auth_serv_sock < 0)
+		perror("socket[PF_INET,SOCK_DGRAM]");
+	else {
+		radius_client_disable_pmtu_discovery(radius->auth_serv_sock);
+		ok++;
+	}
+
+#ifdef CONFIG_IPV6
+	radius->auth_serv_sock6 = socket(PF_INET6, SOCK_DGRAM, 0);
+	if (radius->auth_serv_sock6 < 0)
+		perror("socket[PF_INET6,SOCK_DGRAM]");
+	else
+		ok++;
+#endif /* CONFIG_IPV6 */
+
+	if (ok == 0)
+		return -1;
+
+	radius_change_server(radius, conf->auth_server, NULL,
+			     radius->auth_serv_sock, radius->auth_serv_sock6,
+			     1);
+
+	if (radius->auth_serv_sock >= 0 &&
+	    eloop_register_read_sock(radius->auth_serv_sock,
+				     radius_client_receive, radius,
+				     (void *) RADIUS_AUTH)) {
+		printf("Could not register read socket for authentication "
+		       "server\n");
+		return -1;
+	}
+
+#ifdef CONFIG_IPV6
+	if (radius->auth_serv_sock6 >= 0 &&
+	    eloop_register_read_sock(radius->auth_serv_sock6,
+				     radius_client_receive, radius,
+				     (void *) RADIUS_AUTH)) {
+		printf("Could not register read socket for authentication "
+		       "server\n");
+		return -1;
+	}
+#endif /* CONFIG_IPV6 */
+
+	return 0;
+}
+
+
+static int radius_client_init_acct(struct radius_client_data *radius)
+{
+	struct hostapd_radius_servers *conf = radius->conf;
+	int ok = 0;
+
+	radius->acct_serv_sock = socket(PF_INET, SOCK_DGRAM, 0);
+	if (radius->acct_serv_sock < 0)
+		perror("socket[PF_INET,SOCK_DGRAM]");
+	else {
+		radius_client_disable_pmtu_discovery(radius->acct_serv_sock);
+		ok++;
+	}
+
+#ifdef CONFIG_IPV6
+	radius->acct_serv_sock6 = socket(PF_INET6, SOCK_DGRAM, 0);
+	if (radius->acct_serv_sock6 < 0)
+		perror("socket[PF_INET6,SOCK_DGRAM]");
+	else
+		ok++;
+#endif /* CONFIG_IPV6 */
+
+	if (ok == 0)
+		return -1;
+
+	radius_change_server(radius, conf->acct_server, NULL,
+			     radius->acct_serv_sock, radius->acct_serv_sock6,
+			     0);
+
+	if (radius->acct_serv_sock >= 0 &&
+	    eloop_register_read_sock(radius->acct_serv_sock,
+				     radius_client_receive, radius,
+				     (void *) RADIUS_ACCT)) {
+		printf("Could not register read socket for accounting "
+		       "server\n");
+		return -1;
+	}
+
+#ifdef CONFIG_IPV6
+	if (radius->acct_serv_sock6 >= 0 &&
+	    eloop_register_read_sock(radius->acct_serv_sock6,
+				     radius_client_receive, radius,
+				     (void *) RADIUS_ACCT)) {
+		printf("Could not register read socket for accounting "
+		       "server\n");
+		return -1;
+	}
+#endif /* CONFIG_IPV6 */
+
+	return 0;
+}
+
+
+/**
+ * radius_client_init - Initialize RADIUS client
+ * @ctx: Callback context to be used in hostapd_logger() calls
+ * @conf: RADIUS client configuration (RADIUS servers)
+ * Returns: Pointer to private RADIUS client context or %NULL on failure
+ *
+ * The caller is responsible for keeping the configuration data available for
+ * the lifetime of the RADIUS client, i.e., until radius_client_deinit() is
+ * called for the returned context pointer.
+ */
+struct radius_client_data *
+radius_client_init(void *ctx, struct hostapd_radius_servers *conf)
+{
+	struct radius_client_data *radius;
+
+	radius = os_zalloc(sizeof(struct radius_client_data));
+	if (radius == NULL)
+		return NULL;
+
+	radius->ctx = ctx;
+	radius->conf = conf;
+	radius->auth_serv_sock = radius->acct_serv_sock =
+		radius->auth_serv_sock6 = radius->acct_serv_sock6 =
+		radius->auth_sock = radius->acct_sock = -1;
+
+	if (conf->auth_server && radius_client_init_auth(radius)) {
+		radius_client_deinit(radius);
+		return NULL;
+	}
+
+	if (conf->acct_server && radius_client_init_acct(radius)) {
+		radius_client_deinit(radius);
+		return NULL;
+	}
+
+	if (conf->retry_primary_interval)
+		eloop_register_timeout(conf->retry_primary_interval, 0,
+				       radius_retry_primary_timer, radius,
+				       NULL);
+
+	return radius;
+}
+
+
+/**
+ * radius_client_deinit - Deinitialize RADIUS client
+ * @radius: RADIUS client context from radius_client_init()
+ */
+void radius_client_deinit(struct radius_client_data *radius)
+{
+	if (!radius)
+		return;
+
+	if (radius->auth_serv_sock >= 0)
+		eloop_unregister_read_sock(radius->auth_serv_sock);
+	if (radius->acct_serv_sock >= 0)
+		eloop_unregister_read_sock(radius->acct_serv_sock);
+#ifdef CONFIG_IPV6
+	if (radius->auth_serv_sock6 >= 0)
+		eloop_unregister_read_sock(radius->auth_serv_sock6);
+	if (radius->acct_serv_sock6 >= 0)
+		eloop_unregister_read_sock(radius->acct_serv_sock6);
+#endif /* CONFIG_IPV6 */
+
+	eloop_cancel_timeout(radius_retry_primary_timer, radius, NULL);
+
+	radius_client_flush(radius, 0);
+	os_free(radius->auth_handlers);
+	os_free(radius->acct_handlers);
+	os_free(radius);
+}
+
+
+/**
+ * radius_client_flush_auth - Flush pending RADIUS messages for an address
+ * @radius: RADIUS client context from radius_client_init()
+ * @addr: MAC address of the related device
+ *
+ * This function can be used to remove pending RADIUS authentication messages
+ * that are related to a specific device. The addr parameter is matched with
+ * the one used in radius_client_send() call that was used to transmit the
+ * authentication request.
+ */
+void radius_client_flush_auth(struct radius_client_data *radius,
+			      const u8 *addr)
+{
+	struct radius_msg_list *entry, *prev, *tmp;
+
+	prev = NULL;
+	entry = radius->msgs;
+	while (entry) {
+		if (entry->msg_type == RADIUS_AUTH &&
+		    os_memcmp(entry->addr, addr, ETH_ALEN) == 0) {
+			hostapd_logger(radius->ctx, addr,
+				       HOSTAPD_MODULE_RADIUS,
+				       HOSTAPD_LEVEL_DEBUG,
+				       "Removing pending RADIUS authentication"
+				       " message for removed client");
+
+			if (prev)
+				prev->next = entry->next;
+			else
+				radius->msgs = entry->next;
+
+			tmp = entry;
+			entry = entry->next;
+			radius_client_msg_free(tmp);
+			radius->num_msgs--;
+			continue;
+		}
+
+		prev = entry;
+		entry = entry->next;
+	}
+}
+
+
+static int radius_client_dump_auth_server(char *buf, size_t buflen,
+					  struct hostapd_radius_server *serv,
+					  struct radius_client_data *cli)
+{
+	int pending = 0;
+	struct radius_msg_list *msg;
+	char abuf[50];
+
+	if (cli) {
+		for (msg = cli->msgs; msg; msg = msg->next) {
+			if (msg->msg_type == RADIUS_AUTH)
+				pending++;
+		}
+	}
+
+	return os_snprintf(buf, buflen,
+			   "radiusAuthServerIndex=%d\n"
+			   "radiusAuthServerAddress=%s\n"
+			   "radiusAuthClientServerPortNumber=%d\n"
+			   "radiusAuthClientRoundTripTime=%d\n"
+			   "radiusAuthClientAccessRequests=%u\n"
+			   "radiusAuthClientAccessRetransmissions=%u\n"
+			   "radiusAuthClientAccessAccepts=%u\n"
+			   "radiusAuthClientAccessRejects=%u\n"
+			   "radiusAuthClientAccessChallenges=%u\n"
+			   "radiusAuthClientMalformedAccessResponses=%u\n"
+			   "radiusAuthClientBadAuthenticators=%u\n"
+			   "radiusAuthClientPendingRequests=%u\n"
+			   "radiusAuthClientTimeouts=%u\n"
+			   "radiusAuthClientUnknownTypes=%u\n"
+			   "radiusAuthClientPacketsDropped=%u\n",
+			   serv->index,
+			   hostapd_ip_txt(&serv->addr, abuf, sizeof(abuf)),
+			   serv->port,
+			   serv->round_trip_time,
+			   serv->requests,
+			   serv->retransmissions,
+			   serv->access_accepts,
+			   serv->access_rejects,
+			   serv->access_challenges,
+			   serv->malformed_responses,
+			   serv->bad_authenticators,
+			   pending,
+			   serv->timeouts,
+			   serv->unknown_types,
+			   serv->packets_dropped);
+}
+
+
+static int radius_client_dump_acct_server(char *buf, size_t buflen,
+					  struct hostapd_radius_server *serv,
+					  struct radius_client_data *cli)
+{
+	int pending = 0;
+	struct radius_msg_list *msg;
+	char abuf[50];
+
+	if (cli) {
+		for (msg = cli->msgs; msg; msg = msg->next) {
+			if (msg->msg_type == RADIUS_ACCT ||
+			    msg->msg_type == RADIUS_ACCT_INTERIM)
+				pending++;
+		}
+	}
+
+	return os_snprintf(buf, buflen,
+			   "radiusAccServerIndex=%d\n"
+			   "radiusAccServerAddress=%s\n"
+			   "radiusAccClientServerPortNumber=%d\n"
+			   "radiusAccClientRoundTripTime=%d\n"
+			   "radiusAccClientRequests=%u\n"
+			   "radiusAccClientRetransmissions=%u\n"
+			   "radiusAccClientResponses=%u\n"
+			   "radiusAccClientMalformedResponses=%u\n"
+			   "radiusAccClientBadAuthenticators=%u\n"
+			   "radiusAccClientPendingRequests=%u\n"
+			   "radiusAccClientTimeouts=%u\n"
+			   "radiusAccClientUnknownTypes=%u\n"
+			   "radiusAccClientPacketsDropped=%u\n",
+			   serv->index,
+			   hostapd_ip_txt(&serv->addr, abuf, sizeof(abuf)),
+			   serv->port,
+			   serv->round_trip_time,
+			   serv->requests,
+			   serv->retransmissions,
+			   serv->responses,
+			   serv->malformed_responses,
+			   serv->bad_authenticators,
+			   pending,
+			   serv->timeouts,
+			   serv->unknown_types,
+			   serv->packets_dropped);
+}
+
+
+/**
+ * radius_client_get_mib - Get RADIUS client MIB information
+ * @radius: RADIUS client context from radius_client_init()
+ * @buf: Buffer for returning MIB data in text format
+ * @buflen: Maximum buf length in octets
+ * Returns: Number of octets written into the buffer
+ */
+int radius_client_get_mib(struct radius_client_data *radius, char *buf,
+			  size_t buflen)
+{
+	struct hostapd_radius_servers *conf = radius->conf;
+	int i;
+	struct hostapd_radius_server *serv;
+	int count = 0;
+
+	if (conf->auth_servers) {
+		for (i = 0; i < conf->num_auth_servers; i++) {
+			serv = &conf->auth_servers[i];
+			count += radius_client_dump_auth_server(
+				buf + count, buflen - count, serv,
+				serv == conf->auth_server ?
+				radius : NULL);
+		}
+	}
+
+	if (conf->acct_servers) {
+		for (i = 0; i < conf->num_acct_servers; i++) {
+			serv = &conf->acct_servers[i];
+			count += radius_client_dump_acct_server(
+				buf + count, buflen - count, serv,
+				serv == conf->acct_server ?
+				radius : NULL);
+		}
+	}
+
+	return count;
+}
+
+
+void radius_client_reconfig(struct radius_client_data *radius,
+			    struct hostapd_radius_servers *conf)
+{
+	if (radius)
+		radius->conf = conf;
+}
diff --git a/src/radius/radius_client.h b/src/radius/radius_client.h
new file mode 100644
index 0000000..18e7290
--- /dev/null
+++ b/src/radius/radius_client.h
@@ -0,0 +1,265 @@
+/*
+ * RADIUS client
+ * Copyright (c) 2002-2009, Jouni Malinen <j@w1.fi>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ *
+ * Alternatively, this software may be distributed under the terms of BSD
+ * license.
+ *
+ * See README and COPYING for more details.
+ */
+
+#ifndef RADIUS_CLIENT_H
+#define RADIUS_CLIENT_H
+
+#include "ip_addr.h"
+
+struct radius_msg;
+
+/**
+ * struct hostapd_radius_server - RADIUS server information for RADIUS client
+ *
+ * This structure contains information about a RADIUS server. The values are
+ * mainly for MIB information. The MIB variable prefix (radiusAuth or
+ * radiusAcc) depends on whether this is an authentication or accounting
+ * server.
+ *
+ * radiusAuthClientPendingRequests (or radiusAccClientPendingRequests) is the
+ * number struct radius_client_data::msgs for matching msg_type.
+ */
+struct hostapd_radius_server {
+	/**
+	 * addr - radiusAuthServerAddress or radiusAccServerAddress
+	 */
+	struct hostapd_ip_addr addr;
+
+	/**
+	 * port - radiusAuthClientServerPortNumber or radiusAccClientServerPortNumber
+	 */
+	int port;
+
+	/**
+	 * shared_secret - Shared secret for authenticating RADIUS messages
+	 */
+	u8 *shared_secret;
+
+	/**
+	 * shared_secret_len - Length of shared_secret in octets
+	 */
+	size_t shared_secret_len;
+
+	/* Dynamic (not from configuration file) MIB data */
+
+	/**
+	 * index - radiusAuthServerIndex or radiusAccServerIndex
+	 */
+	int index;
+
+	/**
+	 * round_trip_time - radiusAuthClientRoundTripTime or radiusAccClientRoundTripTime
+	 * Round-trip time in hundredths of a second.
+	 */
+	int round_trip_time;
+
+	/**
+	 * requests - radiusAuthClientAccessRequests or radiusAccClientRequests
+	 */
+	u32 requests;
+
+	/**
+	 * retransmissions - radiusAuthClientAccessRetransmissions or radiusAccClientRetransmissions
+	 */
+	u32 retransmissions;
+
+	/**
+	 * access_accepts - radiusAuthClientAccessAccepts
+	 */
+	u32 access_accepts;
+
+	/**
+	 * access_rejects - radiusAuthClientAccessRejects
+	 */
+	u32 access_rejects;
+
+	/**
+	 * access_challenges - radiusAuthClientAccessChallenges
+	 */
+	u32 access_challenges;
+
+	/**
+	 * responses - radiusAccClientResponses
+	 */
+	u32 responses;
+
+	/**
+	 * malformed_responses - radiusAuthClientMalformedAccessResponses or radiusAccClientMalformedResponses
+	 */
+	u32 malformed_responses;
+
+	/**
+	 * bad_authenticators - radiusAuthClientBadAuthenticators or radiusAccClientBadAuthenticators
+	 */
+	u32 bad_authenticators;
+
+	/**
+	 * timeouts - radiusAuthClientTimeouts or radiusAccClientTimeouts
+	 */
+	u32 timeouts;
+
+	/**
+	 * unknown_types - radiusAuthClientUnknownTypes or radiusAccClientUnknownTypes
+	 */
+	u32 unknown_types;
+
+	/**
+	 * packets_dropped - radiusAuthClientPacketsDropped or radiusAccClientPacketsDropped
+	 */
+	u32 packets_dropped;
+};
+
+/**
+ * struct hostapd_radius_servers - RADIUS servers for RADIUS client
+ */
+struct hostapd_radius_servers {
+	/**
+	 * auth_servers - RADIUS Authentication servers in priority order
+	 */
+	struct hostapd_radius_server *auth_servers;
+
+	/**
+	 * num_auth_servers - Number of auth_servers entries
+	 */
+	int num_auth_servers;
+
+	/**
+	 * auth_server - The current Authentication server
+	 */
+	struct hostapd_radius_server *auth_server;
+
+	/**
+	 * acct_servers - RADIUS Accounting servers in priority order
+	 */
+	struct hostapd_radius_server *acct_servers;
+
+	/**
+	 * num_acct_servers - Number of acct_servers entries
+	 */
+	int num_acct_servers;
+
+	/**
+	 * acct_server - The current Accounting server
+	 */
+	struct hostapd_radius_server *acct_server;
+
+	/**
+	 * retry_primary_interval - Retry interval for trying primary server
+	 *
+	 * This specifies a retry interval in sexconds for trying to return to
+	 * the primary RADIUS server. RADIUS client code will automatically try
+	 * to use the next server when the current server is not replying to
+	 * requests. If this interval is set (non-zero), the primary server
+	 * will be retried after the specified number of seconds has passed
+	 * even if the current used secondary server is still working.
+	 */
+	int retry_primary_interval;
+
+	/**
+	 * msg_dumps - Whether RADIUS message details are shown in stdout
+	 */
+	int msg_dumps;
+
+	/**
+	 * client_addr - Client (local) address to use if force_client_addr
+	 */
+	struct hostapd_ip_addr client_addr;
+
+	/**
+	 * force_client_addr - Whether to force client (local) address
+	 */
+	int force_client_addr;
+};
+
+
+/**
+ * RadiusType - RADIUS server type for RADIUS client
+ */
+typedef enum {
+	/**
+	 * RADIUS authentication
+	 */
+	RADIUS_AUTH,
+
+	/**
+	 * RADIUS_ACCT - RADIUS accounting
+	 */
+	RADIUS_ACCT,
+
+	/**
+	 * RADIUS_ACCT_INTERIM - RADIUS interim accounting message
+	 *
+	 * Used only with radius_client_send(). This behaves just like
+	 * RADIUS_ACCT, but removes any pending interim RADIUS Accounting
+	 * messages for the same STA before sending the new interim update.
+	 */
+	RADIUS_ACCT_INTERIM
+} RadiusType;
+
+/**
+ * RadiusRxResult - RADIUS client RX handler result
+ */
+typedef enum {
+	/**
+	 * RADIUS_RX_PROCESSED - Message processed
+	 *
+	 * This stops handler calls and frees the message.
+	 */
+	RADIUS_RX_PROCESSED,
+
+	/**
+	 * RADIUS_RX_QUEUED - Message has been queued
+	 *
+	 * This stops handler calls, but does not free the message; the handler
+	 * that returned this is responsible for eventually freeing the
+	 * message.
+	 */
+	RADIUS_RX_QUEUED,
+
+	/**
+	 * RADIUS_RX_UNKNOWN - Message is not for this handler
+	 */
+	RADIUS_RX_UNKNOWN,
+
+	/**
+	 * RADIUS_RX_INVALID_AUTHENTICATOR - Message has invalid Authenticator
+	 */
+	RADIUS_RX_INVALID_AUTHENTICATOR
+} RadiusRxResult;
+
+struct radius_client_data;
+
+int radius_client_register(struct radius_client_data *radius,
+			   RadiusType msg_type,
+			   RadiusRxResult (*handler)
+			   (struct radius_msg *msg, struct radius_msg *req,
+			    const u8 *shared_secret, size_t shared_secret_len,
+			    void *data),
+			   void *data);
+int radius_client_send(struct radius_client_data *radius,
+		       struct radius_msg *msg,
+		       RadiusType msg_type, const u8 *addr);
+u8 radius_client_get_id(struct radius_client_data *radius);
+void radius_client_flush(struct radius_client_data *radius, int only_auth);
+struct radius_client_data *
+radius_client_init(void *ctx, struct hostapd_radius_servers *conf);
+void radius_client_deinit(struct radius_client_data *radius);
+void radius_client_flush_auth(struct radius_client_data *radius,
+			      const u8 *addr);
+int radius_client_get_mib(struct radius_client_data *radius, char *buf,
+			  size_t buflen);
+void radius_client_reconfig(struct radius_client_data *radius,
+			    struct hostapd_radius_servers *conf);
+
+#endif /* RADIUS_CLIENT_H */
diff --git a/src/radius/radius_server.c b/src/radius/radius_server.c
new file mode 100644
index 0000000..6f1c3a5
--- /dev/null
+++ b/src/radius/radius_server.c
@@ -0,0 +1,1527 @@
+/*
+ * RADIUS authentication server
+ * Copyright (c) 2005-2009, Jouni Malinen <j@w1.fi>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ *
+ * Alternatively, this software may be distributed under the terms of BSD
+ * license.
+ *
+ * See README and COPYING for more details.
+ */
+
+#include "includes.h"
+#include <net/if.h>
+
+#include "common.h"
+#include "radius.h"
+#include "eloop.h"
+#include "eap_server/eap.h"
+#include "radius_server.h"
+
+/**
+ * RADIUS_SESSION_TIMEOUT - Session timeout in seconds
+ */
+#define RADIUS_SESSION_TIMEOUT 60
+
+/**
+ * RADIUS_MAX_SESSION - Maximum number of active sessions
+ */
+#define RADIUS_MAX_SESSION 100
+
+/**
+ * RADIUS_MAX_MSG_LEN - Maximum message length for incoming RADIUS messages
+ */
+#define RADIUS_MAX_MSG_LEN 3000
+
+static struct eapol_callbacks radius_server_eapol_cb;
+
+struct radius_client;
+struct radius_server_data;
+
+/**
+ * struct radius_server_counters - RADIUS server statistics counters
+ */
+struct radius_server_counters {
+	u32 access_requests;
+	u32 invalid_requests;
+	u32 dup_access_requests;
+	u32 access_accepts;
+	u32 access_rejects;
+	u32 access_challenges;
+	u32 malformed_access_requests;
+	u32 bad_authenticators;
+	u32 packets_dropped;
+	u32 unknown_types;
+};
+
+/**
+ * struct radius_session - Internal RADIUS server data for a session
+ */
+struct radius_session {
+	struct radius_session *next;
+	struct radius_client *client;
+	struct radius_server_data *server;
+	unsigned int sess_id;
+	struct eap_sm *eap;
+	struct eap_eapol_interface *eap_if;
+
+	struct radius_msg *last_msg;
+	char *last_from_addr;
+	int last_from_port;
+	struct sockaddr_storage last_from;
+	socklen_t last_fromlen;
+	u8 last_identifier;
+	struct radius_msg *last_reply;
+	u8 last_authenticator[16];
+};
+
+/**
+ * struct radius_client - Internal RADIUS server data for a client
+ */
+struct radius_client {
+	struct radius_client *next;
+	struct in_addr addr;
+	struct in_addr mask;
+#ifdef CONFIG_IPV6
+	struct in6_addr addr6;
+	struct in6_addr mask6;
+#endif /* CONFIG_IPV6 */
+	char *shared_secret;
+	int shared_secret_len;
+	struct radius_session *sessions;
+	struct radius_server_counters counters;
+};
+
+/**
+ * struct radius_server_data - Internal RADIUS server data
+ */
+struct radius_server_data {
+	/**
+	 * auth_sock - Socket for RADIUS authentication messages
+	 */
+	int auth_sock;
+
+	/**
+	 * clients - List of authorized RADIUS clients
+	 */
+	struct radius_client *clients;
+
+	/**
+	 * next_sess_id - Next session identifier
+	 */
+	unsigned int next_sess_id;
+
+	/**
+	 * conf_ctx - Context pointer for callbacks
+	 *
+	 * This is used as the ctx argument in get_eap_user() calls.
+	 */
+	void *conf_ctx;
+
+	/**
+	 * num_sess - Number of active sessions
+	 */
+	int num_sess;
+
+	/**
+	 * eap_sim_db_priv - EAP-SIM/AKA database context
+	 *
+	 * This is passed to the EAP-SIM/AKA server implementation as a
+	 * callback context.
+	 */
+	void *eap_sim_db_priv;
+
+	/**
+	 * ssl_ctx - TLS context
+	 *
+	 * This is passed to the EAP server implementation as a callback
+	 * context for TLS operations.
+	 */
+	void *ssl_ctx;
+
+	/**
+	 * pac_opaque_encr_key - PAC-Opaque encryption key for EAP-FAST
+	 *
+	 * This parameter is used to set a key for EAP-FAST to encrypt the
+	 * PAC-Opaque data. It can be set to %NULL if EAP-FAST is not used. If
+	 * set, must point to a 16-octet key.
+	 */
+	u8 *pac_opaque_encr_key;
+
+	/**
+	 * eap_fast_a_id - EAP-FAST authority identity (A-ID)
+	 *
+	 * If EAP-FAST is not used, this can be set to %NULL. In theory, this
+	 * is a variable length field, but due to some existing implementations
+	 * requiring A-ID to be 16 octets in length, it is recommended to use
+	 * that length for the field to provide interoperability with deployed
+	 * peer implementations.
+	 */
+	u8 *eap_fast_a_id;
+
+	/**
+	 * eap_fast_a_id_len - Length of eap_fast_a_id buffer in octets
+	 */
+	size_t eap_fast_a_id_len;
+
+	/**
+	 * eap_fast_a_id_info - EAP-FAST authority identifier information
+	 *
+	 * This A-ID-Info contains a user-friendly name for the A-ID. For
+	 * example, this could be the enterprise and server names in
+	 * human-readable format. This field is encoded as UTF-8. If EAP-FAST
+	 * is not used, this can be set to %NULL.
+	 */
+	char *eap_fast_a_id_info;
+
+	/**
+	 * eap_fast_prov - EAP-FAST provisioning modes
+	 *
+	 * 0 = provisioning disabled, 1 = only anonymous provisioning allowed,
+	 * 2 = only authenticated provisioning allowed, 3 = both provisioning
+	 * modes allowed.
+	 */
+	int eap_fast_prov;
+
+	/**
+	 * pac_key_lifetime - EAP-FAST PAC-Key lifetime in seconds
+	 *
+	 * This is the hard limit on how long a provisioned PAC-Key can be
+	 * used.
+	 */
+	int pac_key_lifetime;
+
+	/**
+	 * pac_key_refresh_time - EAP-FAST PAC-Key refresh time in seconds
+	 *
+	 * This is a soft limit on the PAC-Key. The server will automatically
+	 * generate a new PAC-Key when this number of seconds (or fewer) of the
+	 * lifetime remains.
+	 */
+	int pac_key_refresh_time;
+
+	/**
+	 * eap_sim_aka_result_ind - EAP-SIM/AKA protected success indication
+	 *
+	 * This controls whether the protected success/failure indication
+	 * (AT_RESULT_IND) is used with EAP-SIM and EAP-AKA.
+	 */
+	int eap_sim_aka_result_ind;
+
+	/**
+	 * tnc - Trusted Network Connect (TNC)
+	 *
+	 * This controls whether TNC is enabled and will be required before the
+	 * peer is allowed to connect. Note: This is only used with EAP-TTLS
+	 * and EAP-FAST. If any other EAP method is enabled, the peer will be
+	 * allowed to connect without TNC.
+	 */
+	int tnc;
+
+	/**
+	 * pwd_group - The D-H group assigned for EAP-pwd
+	 *
+	 * If EAP-pwd is not used it can be set to zero.
+	 */
+	u16 pwd_group;
+
+	/**
+	 * wps - Wi-Fi Protected Setup context
+	 *
+	 * If WPS is used with an external RADIUS server (which is quite
+	 * unlikely configuration), this is used to provide a pointer to WPS
+	 * context data. Normally, this can be set to %NULL.
+	 */
+	struct wps_context *wps;
+
+	/**
+	 * ipv6 - Whether to enable IPv6 support in the RADIUS server
+	 */
+	int ipv6;
+
+	/**
+	 * start_time - Timestamp of server start
+	 */
+	struct os_time start_time;
+
+	/**
+	 * counters - Statistics counters for server operations
+	 *
+	 * These counters are the sum over all clients.
+	 */
+	struct radius_server_counters counters;
+
+	/**
+	 * get_eap_user - Callback for fetching EAP user information
+	 * @ctx: Context data from conf_ctx
+	 * @identity: User identity
+	 * @identity_len: identity buffer length in octets
+	 * @phase2: Whether this is for Phase 2 identity
+	 * @user: Data structure for filling in the user information
+	 * Returns: 0 on success, -1 on failure
+	 *
+	 * This is used to fetch information from user database. The callback
+	 * will fill in information about allowed EAP methods and the user
+	 * password. The password field will be an allocated copy of the
+	 * password data and RADIUS server will free it after use.
+	 */
+	int (*get_eap_user)(void *ctx, const u8 *identity, size_t identity_len,
+			    int phase2, struct eap_user *user);
+
+	/**
+	 * eap_req_id_text - Optional data for EAP-Request/Identity
+	 *
+	 * This can be used to configure an optional, displayable message that
+	 * will be sent in EAP-Request/Identity. This string can contain an
+	 * ASCII-0 character (nul) to separate network infromation per RFC
+	 * 4284. The actual string length is explicit provided in
+	 * eap_req_id_text_len since nul character will not be used as a string
+	 * terminator.
+	 */
+	char *eap_req_id_text;
+
+	/**
+	 * eap_req_id_text_len - Length of eap_req_id_text buffer in octets
+	 */
+	size_t eap_req_id_text_len;
+
+	/*
+	 * msg_ctx - Context data for wpa_msg() calls
+	 */
+	void *msg_ctx;
+};
+
+
+extern int wpa_debug_level;
+
+#define RADIUS_DEBUG(args...) \
+wpa_printf(MSG_DEBUG, "RADIUS SRV: " args)
+#define RADIUS_ERROR(args...) \
+wpa_printf(MSG_ERROR, "RADIUS SRV: " args)
+#define RADIUS_DUMP(args...) \
+wpa_hexdump(MSG_MSGDUMP, "RADIUS SRV: " args)
+#define RADIUS_DUMP_ASCII(args...) \
+wpa_hexdump_ascii(MSG_MSGDUMP, "RADIUS SRV: " args)
+
+
+static void radius_server_session_timeout(void *eloop_ctx, void *timeout_ctx);
+static void radius_server_session_remove_timeout(void *eloop_ctx,
+						 void *timeout_ctx);
+
+
+static struct radius_client *
+radius_server_get_client(struct radius_server_data *data, struct in_addr *addr,
+			 int ipv6)
+{
+	struct radius_client *client = data->clients;
+
+	while (client) {
+#ifdef CONFIG_IPV6
+		if (ipv6) {
+			struct in6_addr *addr6;
+			int i;
+
+			addr6 = (struct in6_addr *) addr;
+			for (i = 0; i < 16; i++) {
+				if ((addr6->s6_addr[i] &
+				     client->mask6.s6_addr[i]) !=
+				    (client->addr6.s6_addr[i] &
+				     client->mask6.s6_addr[i])) {
+					i = 17;
+					break;
+				}
+			}
+			if (i == 16) {
+				break;
+			}
+		}
+#endif /* CONFIG_IPV6 */
+		if (!ipv6 && (client->addr.s_addr & client->mask.s_addr) ==
+		    (addr->s_addr & client->mask.s_addr)) {
+			break;
+		}
+
+		client = client->next;
+	}
+
+	return client;
+}
+
+
+static struct radius_session *
+radius_server_get_session(struct radius_client *client, unsigned int sess_id)
+{
+	struct radius_session *sess = client->sessions;
+
+	while (sess) {
+		if (sess->sess_id == sess_id) {
+			break;
+		}
+		sess = sess->next;
+	}
+
+	return sess;
+}
+
+
+static void radius_server_session_free(struct radius_server_data *data,
+				       struct radius_session *sess)
+{
+	eloop_cancel_timeout(radius_server_session_timeout, data, sess);
+	eloop_cancel_timeout(radius_server_session_remove_timeout, data, sess);
+	eap_server_sm_deinit(sess->eap);
+	radius_msg_free(sess->last_msg);
+	os_free(sess->last_from_addr);
+	radius_msg_free(sess->last_reply);
+	os_free(sess);
+	data->num_sess--;
+}
+
+
+static void radius_server_session_remove(struct radius_server_data *data,
+					 struct radius_session *sess)
+{
+	struct radius_client *client = sess->client;
+	struct radius_session *session, *prev;
+
+	eloop_cancel_timeout(radius_server_session_remove_timeout, data, sess);
+
+	prev = NULL;
+	session = client->sessions;
+	while (session) {
+		if (session == sess) {
+			if (prev == NULL) {
+				client->sessions = sess->next;
+			} else {
+				prev->next = sess->next;
+			}
+			radius_server_session_free(data, sess);
+			break;
+		}
+		prev = session;
+		session = session->next;
+	}
+}
+
+
+static void radius_server_session_remove_timeout(void *eloop_ctx,
+						 void *timeout_ctx)
+{
+	struct radius_server_data *data = eloop_ctx;
+	struct radius_session *sess = timeout_ctx;
+	RADIUS_DEBUG("Removing completed session 0x%x", sess->sess_id);
+	radius_server_session_remove(data, sess);
+}
+
+
+static void radius_server_session_timeout(void *eloop_ctx, void *timeout_ctx)
+{
+	struct radius_server_data *data = eloop_ctx;
+	struct radius_session *sess = timeout_ctx;
+
+	RADIUS_DEBUG("Timing out authentication session 0x%x", sess->sess_id);
+	radius_server_session_remove(data, sess);
+}
+
+
+static struct radius_session *
+radius_server_new_session(struct radius_server_data *data,
+			  struct radius_client *client)
+{
+	struct radius_session *sess;
+
+	if (data->num_sess >= RADIUS_MAX_SESSION) {
+		RADIUS_DEBUG("Maximum number of existing session - no room "
+			     "for a new session");
+		return NULL;
+	}
+
+	sess = os_zalloc(sizeof(*sess));
+	if (sess == NULL)
+		return NULL;
+
+	sess->server = data;
+	sess->client = client;
+	sess->sess_id = data->next_sess_id++;
+	sess->next = client->sessions;
+	client->sessions = sess;
+	eloop_register_timeout(RADIUS_SESSION_TIMEOUT, 0,
+			       radius_server_session_timeout, data, sess);
+	data->num_sess++;
+	return sess;
+}
+
+
+static struct radius_session *
+radius_server_get_new_session(struct radius_server_data *data,
+			      struct radius_client *client,
+			      struct radius_msg *msg)
+{
+	u8 *user;
+	size_t user_len;
+	int res;
+	struct radius_session *sess;
+	struct eap_config eap_conf;
+
+	RADIUS_DEBUG("Creating a new session");
+
+	user = os_malloc(256);
+	if (user == NULL) {
+		return NULL;
+	}
+	res = radius_msg_get_attr(msg, RADIUS_ATTR_USER_NAME, user, 256);
+	if (res < 0 || res > 256) {
+		RADIUS_DEBUG("Could not get User-Name");
+		os_free(user);
+		return NULL;
+	}
+	user_len = res;
+	RADIUS_DUMP_ASCII("User-Name", user, user_len);
+
+	res = data->get_eap_user(data->conf_ctx, user, user_len, 0, NULL);
+	os_free(user);
+
+	if (res == 0) {
+		RADIUS_DEBUG("Matching user entry found");
+		sess = radius_server_new_session(data, client);
+		if (sess == NULL) {
+			RADIUS_DEBUG("Failed to create a new session");
+			return NULL;
+		}
+	} else {
+		RADIUS_DEBUG("User-Name not found from user database");
+		return NULL;
+	}
+
+	os_memset(&eap_conf, 0, sizeof(eap_conf));
+	eap_conf.ssl_ctx = data->ssl_ctx;
+	eap_conf.msg_ctx = data->msg_ctx;
+	eap_conf.eap_sim_db_priv = data->eap_sim_db_priv;
+	eap_conf.backend_auth = TRUE;
+	eap_conf.eap_server = 1;
+	eap_conf.pac_opaque_encr_key = data->pac_opaque_encr_key;
+	eap_conf.eap_fast_a_id = data->eap_fast_a_id;
+	eap_conf.eap_fast_a_id_len = data->eap_fast_a_id_len;
+	eap_conf.eap_fast_a_id_info = data->eap_fast_a_id_info;
+	eap_conf.eap_fast_prov = data->eap_fast_prov;
+	eap_conf.pac_key_lifetime = data->pac_key_lifetime;
+	eap_conf.pac_key_refresh_time = data->pac_key_refresh_time;
+	eap_conf.eap_sim_aka_result_ind = data->eap_sim_aka_result_ind;
+	eap_conf.tnc = data->tnc;
+	eap_conf.wps = data->wps;
+	eap_conf.pwd_group = data->pwd_group;
+	sess->eap = eap_server_sm_init(sess, &radius_server_eapol_cb,
+				       &eap_conf);
+	if (sess->eap == NULL) {
+		RADIUS_DEBUG("Failed to initialize EAP state machine for the "
+			     "new session");
+		radius_server_session_free(data, sess);
+		return NULL;
+	}
+	sess->eap_if = eap_get_interface(sess->eap);
+	sess->eap_if->eapRestart = TRUE;
+	sess->eap_if->portEnabled = TRUE;
+
+	RADIUS_DEBUG("New session 0x%x initialized", sess->sess_id);
+
+	return sess;
+}
+
+
+static struct radius_msg *
+radius_server_encapsulate_eap(struct radius_server_data *data,
+			      struct radius_client *client,
+			      struct radius_session *sess,
+			      struct radius_msg *request)
+{
+	struct radius_msg *msg;
+	int code;
+	unsigned int sess_id;
+	struct radius_hdr *hdr = radius_msg_get_hdr(request);
+
+	if (sess->eap_if->eapFail) {
+		sess->eap_if->eapFail = FALSE;
+		code = RADIUS_CODE_ACCESS_REJECT;
+	} else if (sess->eap_if->eapSuccess) {
+		sess->eap_if->eapSuccess = FALSE;
+		code = RADIUS_CODE_ACCESS_ACCEPT;
+	} else {
+		sess->eap_if->eapReq = FALSE;
+		code = RADIUS_CODE_ACCESS_CHALLENGE;
+	}
+
+	msg = radius_msg_new(code, hdr->identifier);
+	if (msg == NULL) {
+		RADIUS_DEBUG("Failed to allocate reply message");
+		return NULL;
+	}
+
+	sess_id = htonl(sess->sess_id);
+	if (code == RADIUS_CODE_ACCESS_CHALLENGE &&
+	    !radius_msg_add_attr(msg, RADIUS_ATTR_STATE,
+				 (u8 *) &sess_id, sizeof(sess_id))) {
+		RADIUS_DEBUG("Failed to add State attribute");
+	}
+
+	if (sess->eap_if->eapReqData &&
+	    !radius_msg_add_eap(msg, wpabuf_head(sess->eap_if->eapReqData),
+				wpabuf_len(sess->eap_if->eapReqData))) {
+		RADIUS_DEBUG("Failed to add EAP-Message attribute");
+	}
+
+	if (code == RADIUS_CODE_ACCESS_ACCEPT && sess->eap_if->eapKeyData) {
+		int len;
+		if (sess->eap_if->eapKeyDataLen > 64) {
+			len = 32;
+		} else {
+			len = sess->eap_if->eapKeyDataLen / 2;
+		}
+		if (!radius_msg_add_mppe_keys(msg, hdr->authenticator,
+					      (u8 *) client->shared_secret,
+					      client->shared_secret_len,
+					      sess->eap_if->eapKeyData + len,
+					      len, sess->eap_if->eapKeyData,
+					      len)) {
+			RADIUS_DEBUG("Failed to add MPPE key attributes");
+		}
+	}
+
+	if (radius_msg_copy_attr(msg, request, RADIUS_ATTR_PROXY_STATE) < 0) {
+		RADIUS_DEBUG("Failed to copy Proxy-State attribute(s)");
+		radius_msg_free(msg);
+		return NULL;
+	}
+
+	if (radius_msg_finish_srv(msg, (u8 *) client->shared_secret,
+				  client->shared_secret_len,
+				  hdr->authenticator) < 0) {
+		RADIUS_DEBUG("Failed to add Message-Authenticator attribute");
+	}
+
+	return msg;
+}
+
+
+static int radius_server_reject(struct radius_server_data *data,
+				struct radius_client *client,
+				struct radius_msg *request,
+				struct sockaddr *from, socklen_t fromlen,
+				const char *from_addr, int from_port)
+{
+	struct radius_msg *msg;
+	int ret = 0;
+	struct eap_hdr eapfail;
+	struct wpabuf *buf;
+	struct radius_hdr *hdr = radius_msg_get_hdr(request);
+
+	RADIUS_DEBUG("Reject invalid request from %s:%d",
+		     from_addr, from_port);
+
+	msg = radius_msg_new(RADIUS_CODE_ACCESS_REJECT, hdr->identifier);
+	if (msg == NULL) {
+		return -1;
+	}
+
+	os_memset(&eapfail, 0, sizeof(eapfail));
+	eapfail.code = EAP_CODE_FAILURE;
+	eapfail.identifier = 0;
+	eapfail.length = host_to_be16(sizeof(eapfail));
+
+	if (!radius_msg_add_eap(msg, (u8 *) &eapfail, sizeof(eapfail))) {
+		RADIUS_DEBUG("Failed to add EAP-Message attribute");
+	}
+
+	if (radius_msg_copy_attr(msg, request, RADIUS_ATTR_PROXY_STATE) < 0) {
+		RADIUS_DEBUG("Failed to copy Proxy-State attribute(s)");
+		radius_msg_free(msg);
+		return -1;
+	}
+
+	if (radius_msg_finish_srv(msg, (u8 *) client->shared_secret,
+				  client->shared_secret_len,
+				  hdr->authenticator) <
+	    0) {
+		RADIUS_DEBUG("Failed to add Message-Authenticator attribute");
+	}
+
+	if (wpa_debug_level <= MSG_MSGDUMP) {
+		radius_msg_dump(msg);
+	}
+
+	data->counters.access_rejects++;
+	client->counters.access_rejects++;
+	buf = radius_msg_get_buf(msg);
+	if (sendto(data->auth_sock, wpabuf_head(buf), wpabuf_len(buf), 0,
+		   (struct sockaddr *) from, sizeof(*from)) < 0) {
+		perror("sendto[RADIUS SRV]");
+		ret = -1;
+	}
+
+	radius_msg_free(msg);
+
+	return ret;
+}
+
+
+static int radius_server_request(struct radius_server_data *data,
+				 struct radius_msg *msg,
+				 struct sockaddr *from, socklen_t fromlen,
+				 struct radius_client *client,
+				 const char *from_addr, int from_port,
+				 struct radius_session *force_sess)
+{
+	u8 *eap = NULL;
+	size_t eap_len;
+	int res, state_included = 0;
+	u8 statebuf[4];
+	unsigned int state;
+	struct radius_session *sess;
+	struct radius_msg *reply;
+	int is_complete = 0;
+
+	if (force_sess)
+		sess = force_sess;
+	else {
+		res = radius_msg_get_attr(msg, RADIUS_ATTR_STATE, statebuf,
+					  sizeof(statebuf));
+		state_included = res >= 0;
+		if (res == sizeof(statebuf)) {
+			state = WPA_GET_BE32(statebuf);
+			sess = radius_server_get_session(client, state);
+		} else {
+			sess = NULL;
+		}
+	}
+
+	if (sess) {
+		RADIUS_DEBUG("Request for session 0x%x", sess->sess_id);
+	} else if (state_included) {
+		RADIUS_DEBUG("State attribute included but no session found");
+		radius_server_reject(data, client, msg, from, fromlen,
+				     from_addr, from_port);
+		return -1;
+	} else {
+		sess = radius_server_get_new_session(data, client, msg);
+		if (sess == NULL) {
+			RADIUS_DEBUG("Could not create a new session");
+			radius_server_reject(data, client, msg, from, fromlen,
+					     from_addr, from_port);
+			return -1;
+		}
+	}
+
+	if (sess->last_from_port == from_port &&
+	    sess->last_identifier == radius_msg_get_hdr(msg)->identifier &&
+	    os_memcmp(sess->last_authenticator,
+		      radius_msg_get_hdr(msg)->authenticator, 16) == 0) {
+		RADIUS_DEBUG("Duplicate message from %s", from_addr);
+		data->counters.dup_access_requests++;
+		client->counters.dup_access_requests++;
+
+		if (sess->last_reply) {
+			struct wpabuf *buf;
+			buf = radius_msg_get_buf(sess->last_reply);
+			res = sendto(data->auth_sock, wpabuf_head(buf),
+				     wpabuf_len(buf), 0,
+				     (struct sockaddr *) from, fromlen);
+			if (res < 0) {
+				perror("sendto[RADIUS SRV]");
+			}
+			return 0;
+		}
+
+		RADIUS_DEBUG("No previous reply available for duplicate "
+			     "message");
+		return -1;
+	}
+		      
+	eap = radius_msg_get_eap(msg, &eap_len);
+	if (eap == NULL) {
+		RADIUS_DEBUG("No EAP-Message in RADIUS packet from %s",
+			     from_addr);
+		data->counters.packets_dropped++;
+		client->counters.packets_dropped++;
+		return -1;
+	}
+
+	RADIUS_DUMP("Received EAP data", eap, eap_len);
+
+	/* FIX: if Code is Request, Success, or Failure, send Access-Reject;
+	 * RFC3579 Sect. 2.6.2.
+	 * Include EAP-Response/Nak with no preferred method if
+	 * code == request.
+	 * If code is not 1-4, discard the packet silently.
+	 * Or is this already done by the EAP state machine? */
+
+	wpabuf_free(sess->eap_if->eapRespData);
+	sess->eap_if->eapRespData = wpabuf_alloc_ext_data(eap, eap_len);
+	if (sess->eap_if->eapRespData == NULL)
+		os_free(eap);
+	eap = NULL;
+	sess->eap_if->eapResp = TRUE;
+	eap_server_sm_step(sess->eap);
+
+	if ((sess->eap_if->eapReq || sess->eap_if->eapSuccess ||
+	     sess->eap_if->eapFail) && sess->eap_if->eapReqData) {
+		RADIUS_DUMP("EAP data from the state machine",
+			    wpabuf_head(sess->eap_if->eapReqData),
+			    wpabuf_len(sess->eap_if->eapReqData));
+	} else if (sess->eap_if->eapFail) {
+		RADIUS_DEBUG("No EAP data from the state machine, but eapFail "
+			     "set");
+	} else if (eap_sm_method_pending(sess->eap)) {
+		radius_msg_free(sess->last_msg);
+		sess->last_msg = msg;
+		sess->last_from_port = from_port;
+		os_free(sess->last_from_addr);
+		sess->last_from_addr = os_strdup(from_addr);
+		sess->last_fromlen = fromlen;
+		os_memcpy(&sess->last_from, from, fromlen);
+		return -2;
+	} else {
+		RADIUS_DEBUG("No EAP data from the state machine - ignore this"
+			     " Access-Request silently (assuming it was a "
+			     "duplicate)");
+		data->counters.packets_dropped++;
+		client->counters.packets_dropped++;
+		return -1;
+	}
+
+	if (sess->eap_if->eapSuccess || sess->eap_if->eapFail)
+		is_complete = 1;
+
+	reply = radius_server_encapsulate_eap(data, client, sess, msg);
+
+	if (reply) {
+		struct wpabuf *buf;
+		struct radius_hdr *hdr;
+
+		RADIUS_DEBUG("Reply to %s:%d", from_addr, from_port);
+		if (wpa_debug_level <= MSG_MSGDUMP) {
+			radius_msg_dump(reply);
+		}
+
+		switch (radius_msg_get_hdr(reply)->code) {
+		case RADIUS_CODE_ACCESS_ACCEPT:
+			data->counters.access_accepts++;
+			client->counters.access_accepts++;
+			break;
+		case RADIUS_CODE_ACCESS_REJECT:
+			data->counters.access_rejects++;
+			client->counters.access_rejects++;
+			break;
+		case RADIUS_CODE_ACCESS_CHALLENGE:
+			data->counters.access_challenges++;
+			client->counters.access_challenges++;
+			break;
+		}
+		buf = radius_msg_get_buf(reply);
+		res = sendto(data->auth_sock, wpabuf_head(buf),
+			     wpabuf_len(buf), 0,
+			     (struct sockaddr *) from, fromlen);
+		if (res < 0) {
+			perror("sendto[RADIUS SRV]");
+		}
+		radius_msg_free(sess->last_reply);
+		sess->last_reply = reply;
+		sess->last_from_port = from_port;
+		hdr = radius_msg_get_hdr(msg);
+		sess->last_identifier = hdr->identifier;
+		os_memcpy(sess->last_authenticator, hdr->authenticator, 16);
+	} else {
+		data->counters.packets_dropped++;
+		client->counters.packets_dropped++;
+	}
+
+	if (is_complete) {
+		RADIUS_DEBUG("Removing completed session 0x%x after timeout",
+			     sess->sess_id);
+		eloop_cancel_timeout(radius_server_session_remove_timeout,
+				     data, sess);
+		eloop_register_timeout(10, 0,
+				       radius_server_session_remove_timeout,
+				       data, sess);
+	}
+
+	return 0;
+}
+
+
+static void radius_server_receive_auth(int sock, void *eloop_ctx,
+				       void *sock_ctx)
+{
+	struct radius_server_data *data = eloop_ctx;
+	u8 *buf = NULL;
+	union {
+		struct sockaddr_storage ss;
+		struct sockaddr_in sin;
+#ifdef CONFIG_IPV6
+		struct sockaddr_in6 sin6;
+#endif /* CONFIG_IPV6 */
+	} from;
+	socklen_t fromlen;
+	int len;
+	struct radius_client *client = NULL;
+	struct radius_msg *msg = NULL;
+	char abuf[50];
+	int from_port = 0;
+
+	buf = os_malloc(RADIUS_MAX_MSG_LEN);
+	if (buf == NULL) {
+		goto fail;
+	}
+
+	fromlen = sizeof(from);
+	len = recvfrom(sock, buf, RADIUS_MAX_MSG_LEN, 0,
+		       (struct sockaddr *) &from.ss, &fromlen);
+	if (len < 0) {
+		perror("recvfrom[radius_server]");
+		goto fail;
+	}
+
+#ifdef CONFIG_IPV6
+	if (data->ipv6) {
+		if (inet_ntop(AF_INET6, &from.sin6.sin6_addr, abuf,
+			      sizeof(abuf)) == NULL)
+			abuf[0] = '\0';
+		from_port = ntohs(from.sin6.sin6_port);
+		RADIUS_DEBUG("Received %d bytes from %s:%d",
+			     len, abuf, from_port);
+
+		client = radius_server_get_client(data,
+						  (struct in_addr *)
+						  &from.sin6.sin6_addr, 1);
+	}
+#endif /* CONFIG_IPV6 */
+
+	if (!data->ipv6) {
+		os_strlcpy(abuf, inet_ntoa(from.sin.sin_addr), sizeof(abuf));
+		from_port = ntohs(from.sin.sin_port);
+		RADIUS_DEBUG("Received %d bytes from %s:%d",
+			     len, abuf, from_port);
+
+		client = radius_server_get_client(data, &from.sin.sin_addr, 0);
+	}
+
+	RADIUS_DUMP("Received data", buf, len);
+
+	if (client == NULL) {
+		RADIUS_DEBUG("Unknown client %s - packet ignored", abuf);
+		data->counters.invalid_requests++;
+		goto fail;
+	}
+
+	msg = radius_msg_parse(buf, len);
+	if (msg == NULL) {
+		RADIUS_DEBUG("Parsing incoming RADIUS frame failed");
+		data->counters.malformed_access_requests++;
+		client->counters.malformed_access_requests++;
+		goto fail;
+	}
+
+	os_free(buf);
+	buf = NULL;
+
+	if (wpa_debug_level <= MSG_MSGDUMP) {
+		radius_msg_dump(msg);
+	}
+
+	if (radius_msg_get_hdr(msg)->code != RADIUS_CODE_ACCESS_REQUEST) {
+		RADIUS_DEBUG("Unexpected RADIUS code %d",
+			     radius_msg_get_hdr(msg)->code);
+		data->counters.unknown_types++;
+		client->counters.unknown_types++;
+		goto fail;
+	}
+
+	data->counters.access_requests++;
+	client->counters.access_requests++;
+
+	if (radius_msg_verify_msg_auth(msg, (u8 *) client->shared_secret,
+				       client->shared_secret_len, NULL)) {
+		RADIUS_DEBUG("Invalid Message-Authenticator from %s", abuf);
+		data->counters.bad_authenticators++;
+		client->counters.bad_authenticators++;
+		goto fail;
+	}
+
+	if (radius_server_request(data, msg, (struct sockaddr *) &from,
+				  fromlen, client, abuf, from_port, NULL) ==
+	    -2)
+		return; /* msg was stored with the session */
+
+fail:
+	radius_msg_free(msg);
+	os_free(buf);
+}
+
+
+static int radius_server_disable_pmtu_discovery(int s)
+{
+	int r = -1;
+#if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
+	/* Turn off Path MTU discovery on IPv4/UDP sockets. */
+	int action = IP_PMTUDISC_DONT;
+	r = setsockopt(s, IPPROTO_IP, IP_MTU_DISCOVER, &action,
+		       sizeof(action));
+	if (r == -1)
+		wpa_printf(MSG_ERROR, "Failed to set IP_MTU_DISCOVER: "
+			   "%s", strerror(errno));
+#endif
+	return r;
+}
+
+
+static int radius_server_open_socket(int port)
+{
+	int s;
+	struct sockaddr_in addr;
+
+	s = socket(PF_INET, SOCK_DGRAM, 0);
+	if (s < 0) {
+		perror("socket");
+		return -1;
+	}
+
+	radius_server_disable_pmtu_discovery(s);
+
+	os_memset(&addr, 0, sizeof(addr));
+	addr.sin_family = AF_INET;
+	addr.sin_port = htons(port);
+	if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
+		perror("bind");
+		close(s);
+		return -1;
+	}
+
+	return s;
+}
+
+
+#ifdef CONFIG_IPV6
+static int radius_server_open_socket6(int port)
+{
+	int s;
+	struct sockaddr_in6 addr;
+
+	s = socket(PF_INET6, SOCK_DGRAM, 0);
+	if (s < 0) {
+		perror("socket[IPv6]");
+		return -1;
+	}
+
+	os_memset(&addr, 0, sizeof(addr));
+	addr.sin6_family = AF_INET6;
+	os_memcpy(&addr.sin6_addr, &in6addr_any, sizeof(in6addr_any));
+	addr.sin6_port = htons(port);
+	if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
+		perror("bind");
+		close(s);
+		return -1;
+	}
+
+	return s;
+}
+#endif /* CONFIG_IPV6 */
+
+
+static void radius_server_free_sessions(struct radius_server_data *data,
+					struct radius_session *sessions)
+{
+	struct radius_session *session, *prev;
+
+	session = sessions;
+	while (session) {
+		prev = session;
+		session = session->next;
+		radius_server_session_free(data, prev);
+	}
+}
+
+
+static void radius_server_free_clients(struct radius_server_data *data,
+				       struct radius_client *clients)
+{
+	struct radius_client *client, *prev;
+
+	client = clients;
+	while (client) {
+		prev = client;
+		client = client->next;
+
+		radius_server_free_sessions(data, prev->sessions);
+		os_free(prev->shared_secret);
+		os_free(prev);
+	}
+}
+
+
+static struct radius_client *
+radius_server_read_clients(const char *client_file, int ipv6)
+{
+	FILE *f;
+	const int buf_size = 1024;
+	char *buf, *pos;
+	struct radius_client *clients, *tail, *entry;
+	int line = 0, mask, failed = 0, i;
+	struct in_addr addr;
+#ifdef CONFIG_IPV6
+	struct in6_addr addr6;
+#endif /* CONFIG_IPV6 */
+	unsigned int val;
+
+	f = fopen(client_file, "r");
+	if (f == NULL) {
+		RADIUS_ERROR("Could not open client file '%s'", client_file);
+		return NULL;
+	}
+
+	buf = os_malloc(buf_size);
+	if (buf == NULL) {
+		fclose(f);
+		return NULL;
+	}
+
+	clients = tail = NULL;
+	while (fgets(buf, buf_size, f)) {
+		/* Configuration file format:
+		 * 192.168.1.0/24 secret
+		 * 192.168.1.2 secret
+		 * fe80::211:22ff:fe33:4455/64 secretipv6
+		 */
+		line++;
+		buf[buf_size - 1] = '\0';
+		pos = buf;
+		while (*pos != '\0' && *pos != '\n')
+			pos++;
+		if (*pos == '\n')
+			*pos = '\0';
+		if (*buf == '\0' || *buf == '#')
+			continue;
+
+		pos = buf;
+		while ((*pos >= '0' && *pos <= '9') || *pos == '.' ||
+		       (*pos >= 'a' && *pos <= 'f') || *pos == ':' ||
+		       (*pos >= 'A' && *pos <= 'F')) {
+			pos++;
+		}
+
+		if (*pos == '\0') {
+			failed = 1;
+			break;
+		}
+
+		if (*pos == '/') {
+			char *end;
+			*pos++ = '\0';
+			mask = strtol(pos, &end, 10);
+			if ((pos == end) ||
+			    (mask < 0 || mask > (ipv6 ? 128 : 32))) {
+				failed = 1;
+				break;
+			}
+			pos = end;
+		} else {
+			mask = ipv6 ? 128 : 32;
+			*pos++ = '\0';
+		}
+
+		if (!ipv6 && inet_aton(buf, &addr) == 0) {
+			failed = 1;
+			break;
+		}
+#ifdef CONFIG_IPV6
+		if (ipv6 && inet_pton(AF_INET6, buf, &addr6) <= 0) {
+			if (inet_pton(AF_INET, buf, &addr) <= 0) {
+				failed = 1;
+				break;
+			}
+			/* Convert IPv4 address to IPv6 */
+			if (mask <= 32)
+				mask += (128 - 32);
+			os_memset(addr6.s6_addr, 0, 10);
+			addr6.s6_addr[10] = 0xff;
+			addr6.s6_addr[11] = 0xff;
+			os_memcpy(addr6.s6_addr + 12, (char *) &addr.s_addr,
+				  4);
+		}
+#endif /* CONFIG_IPV6 */
+
+		while (*pos == ' ' || *pos == '\t') {
+			pos++;
+		}
+
+		if (*pos == '\0') {
+			failed = 1;
+			break;
+		}
+
+		entry = os_zalloc(sizeof(*entry));
+		if (entry == NULL) {
+			failed = 1;
+			break;
+		}
+		entry->shared_secret = os_strdup(pos);
+		if (entry->shared_secret == NULL) {
+			failed = 1;
+			os_free(entry);
+			break;
+		}
+		entry->shared_secret_len = os_strlen(entry->shared_secret);
+		entry->addr.s_addr = addr.s_addr;
+		if (!ipv6) {
+			val = 0;
+			for (i = 0; i < mask; i++)
+				val |= 1 << (31 - i);
+			entry->mask.s_addr = htonl(val);
+		}
+#ifdef CONFIG_IPV6
+		if (ipv6) {
+			int offset = mask / 8;
+
+			os_memcpy(entry->addr6.s6_addr, addr6.s6_addr, 16);
+			os_memset(entry->mask6.s6_addr, 0xff, offset);
+			val = 0;
+			for (i = 0; i < (mask % 8); i++)
+				val |= 1 << (7 - i);
+			if (offset < 16)
+				entry->mask6.s6_addr[offset] = val;
+		}
+#endif /* CONFIG_IPV6 */
+
+		if (tail == NULL) {
+			clients = tail = entry;
+		} else {
+			tail->next = entry;
+			tail = entry;
+		}
+	}
+
+	if (failed) {
+		RADIUS_ERROR("Invalid line %d in '%s'", line, client_file);
+		radius_server_free_clients(NULL, clients);
+		clients = NULL;
+	}
+
+	os_free(buf);
+	fclose(f);
+
+	return clients;
+}
+
+
+/**
+ * radius_server_init - Initialize RADIUS server
+ * @conf: Configuration for the RADIUS server
+ * Returns: Pointer to private RADIUS server context or %NULL on failure
+ *
+ * This initializes a RADIUS server instance and returns a context pointer that
+ * will be used in other calls to the RADIUS server module. The server can be
+ * deinitialize by calling radius_server_deinit().
+ */
+struct radius_server_data *
+radius_server_init(struct radius_server_conf *conf)
+{
+	struct radius_server_data *data;
+
+#ifndef CONFIG_IPV6
+	if (conf->ipv6) {
+		fprintf(stderr, "RADIUS server compiled without IPv6 "
+			"support.\n");
+		return NULL;
+	}
+#endif /* CONFIG_IPV6 */
+
+	data = os_zalloc(sizeof(*data));
+	if (data == NULL)
+		return NULL;
+
+	os_get_time(&data->start_time);
+	data->conf_ctx = conf->conf_ctx;
+	data->eap_sim_db_priv = conf->eap_sim_db_priv;
+	data->ssl_ctx = conf->ssl_ctx;
+	data->msg_ctx = conf->msg_ctx;
+	data->ipv6 = conf->ipv6;
+	if (conf->pac_opaque_encr_key) {
+		data->pac_opaque_encr_key = os_malloc(16);
+		os_memcpy(data->pac_opaque_encr_key, conf->pac_opaque_encr_key,
+			  16);
+	}
+	if (conf->eap_fast_a_id) {
+		data->eap_fast_a_id = os_malloc(conf->eap_fast_a_id_len);
+		if (data->eap_fast_a_id) {
+			os_memcpy(data->eap_fast_a_id, conf->eap_fast_a_id,
+				  conf->eap_fast_a_id_len);
+			data->eap_fast_a_id_len = conf->eap_fast_a_id_len;
+		}
+	}
+	if (conf->eap_fast_a_id_info)
+		data->eap_fast_a_id_info = os_strdup(conf->eap_fast_a_id_info);
+	data->eap_fast_prov = conf->eap_fast_prov;
+	data->pac_key_lifetime = conf->pac_key_lifetime;
+	data->pac_key_refresh_time = conf->pac_key_refresh_time;
+	data->get_eap_user = conf->get_eap_user;
+	data->eap_sim_aka_result_ind = conf->eap_sim_aka_result_ind;
+	data->tnc = conf->tnc;
+	data->wps = conf->wps;
+	data->pwd_group = conf->pwd_group;
+	if (conf->eap_req_id_text) {
+		data->eap_req_id_text = os_malloc(conf->eap_req_id_text_len);
+		if (data->eap_req_id_text) {
+			os_memcpy(data->eap_req_id_text, conf->eap_req_id_text,
+				  conf->eap_req_id_text_len);
+			data->eap_req_id_text_len = conf->eap_req_id_text_len;
+		}
+	}
+
+	data->clients = radius_server_read_clients(conf->client_file,
+						   conf->ipv6);
+	if (data->clients == NULL) {
+		printf("No RADIUS clients configured.\n");
+		radius_server_deinit(data);
+		return NULL;
+	}
+
+#ifdef CONFIG_IPV6
+	if (conf->ipv6)
+		data->auth_sock = radius_server_open_socket6(conf->auth_port);
+	else
+#endif /* CONFIG_IPV6 */
+	data->auth_sock = radius_server_open_socket(conf->auth_port);
+	if (data->auth_sock < 0) {
+		printf("Failed to open UDP socket for RADIUS authentication "
+		       "server\n");
+		radius_server_deinit(data);
+		return NULL;
+	}
+	if (eloop_register_read_sock(data->auth_sock,
+				     radius_server_receive_auth,
+				     data, NULL)) {
+		radius_server_deinit(data);
+		return NULL;
+	}
+
+	return data;
+}
+
+
+/**
+ * radius_server_deinit - Deinitialize RADIUS server
+ * @data: RADIUS server context from radius_server_init()
+ */
+void radius_server_deinit(struct radius_server_data *data)
+{
+	if (data == NULL)
+		return;
+
+	if (data->auth_sock >= 0) {
+		eloop_unregister_read_sock(data->auth_sock);
+		close(data->auth_sock);
+	}
+
+	radius_server_free_clients(data, data->clients);
+
+	os_free(data->pac_opaque_encr_key);
+	os_free(data->eap_fast_a_id);
+	os_free(data->eap_fast_a_id_info);
+	os_free(data->eap_req_id_text);
+	os_free(data);
+}
+
+
+/**
+ * radius_server_get_mib - Get RADIUS server MIB information
+ * @data: RADIUS server context from radius_server_init()
+ * @buf: Buffer for returning the MIB data in text format
+ * @buflen: buf length in octets
+ * Returns: Number of octets written into buf
+ */
+int radius_server_get_mib(struct radius_server_data *data, char *buf,
+			  size_t buflen)
+{
+	int ret, uptime;
+	unsigned int idx;
+	char *end, *pos;
+	struct os_time now;
+	struct radius_client *cli;
+
+	/* RFC 2619 - RADIUS Authentication Server MIB */
+
+	if (data == NULL || buflen == 0)
+		return 0;
+
+	pos = buf;
+	end = buf + buflen;
+
+	os_get_time(&now);
+	uptime = (now.sec - data->start_time.sec) * 100 +
+		((now.usec - data->start_time.usec) / 10000) % 100;
+	ret = os_snprintf(pos, end - pos,
+			  "RADIUS-AUTH-SERVER-MIB\n"
+			  "radiusAuthServIdent=hostapd\n"
+			  "radiusAuthServUpTime=%d\n"
+			  "radiusAuthServResetTime=0\n"
+			  "radiusAuthServConfigReset=4\n",
+			  uptime);
+	if (ret < 0 || ret >= end - pos) {
+		*pos = '\0';
+		return pos - buf;
+	}
+	pos += ret;
+
+	ret = os_snprintf(pos, end - pos,
+			  "radiusAuthServTotalAccessRequests=%u\n"
+			  "radiusAuthServTotalInvalidRequests=%u\n"
+			  "radiusAuthServTotalDupAccessRequests=%u\n"
+			  "radiusAuthServTotalAccessAccepts=%u\n"
+			  "radiusAuthServTotalAccessRejects=%u\n"
+			  "radiusAuthServTotalAccessChallenges=%u\n"
+			  "radiusAuthServTotalMalformedAccessRequests=%u\n"
+			  "radiusAuthServTotalBadAuthenticators=%u\n"
+			  "radiusAuthServTotalPacketsDropped=%u\n"
+			  "radiusAuthServTotalUnknownTypes=%u\n",
+			  data->counters.access_requests,
+			  data->counters.invalid_requests,
+			  data->counters.dup_access_requests,
+			  data->counters.access_accepts,
+			  data->counters.access_rejects,
+			  data->counters.access_challenges,
+			  data->counters.malformed_access_requests,
+			  data->counters.bad_authenticators,
+			  data->counters.packets_dropped,
+			  data->counters.unknown_types);
+	if (ret < 0 || ret >= end - pos) {
+		*pos = '\0';
+		return pos - buf;
+	}
+	pos += ret;
+
+	for (cli = data->clients, idx = 0; cli; cli = cli->next, idx++) {
+		char abuf[50], mbuf[50];
+#ifdef CONFIG_IPV6
+		if (data->ipv6) {
+			if (inet_ntop(AF_INET6, &cli->addr6, abuf,
+				      sizeof(abuf)) == NULL)
+				abuf[0] = '\0';
+			if (inet_ntop(AF_INET6, &cli->mask6, abuf,
+				      sizeof(mbuf)) == NULL)
+				mbuf[0] = '\0';
+		}
+#endif /* CONFIG_IPV6 */
+		if (!data->ipv6) {
+			os_strlcpy(abuf, inet_ntoa(cli->addr), sizeof(abuf));
+			os_strlcpy(mbuf, inet_ntoa(cli->mask), sizeof(mbuf));
+		}
+
+		ret = os_snprintf(pos, end - pos,
+				  "radiusAuthClientIndex=%u\n"
+				  "radiusAuthClientAddress=%s/%s\n"
+				  "radiusAuthServAccessRequests=%u\n"
+				  "radiusAuthServDupAccessRequests=%u\n"
+				  "radiusAuthServAccessAccepts=%u\n"
+				  "radiusAuthServAccessRejects=%u\n"
+				  "radiusAuthServAccessChallenges=%u\n"
+				  "radiusAuthServMalformedAccessRequests=%u\n"
+				  "radiusAuthServBadAuthenticators=%u\n"
+				  "radiusAuthServPacketsDropped=%u\n"
+				  "radiusAuthServUnknownTypes=%u\n",
+				  idx,
+				  abuf, mbuf,
+				  cli->counters.access_requests,
+				  cli->counters.dup_access_requests,
+				  cli->counters.access_accepts,
+				  cli->counters.access_rejects,
+				  cli->counters.access_challenges,
+				  cli->counters.malformed_access_requests,
+				  cli->counters.bad_authenticators,
+				  cli->counters.packets_dropped,
+				  cli->counters.unknown_types);
+		if (ret < 0 || ret >= end - pos) {
+			*pos = '\0';
+			return pos - buf;
+		}
+		pos += ret;
+	}
+
+	return pos - buf;
+}
+
+
+static int radius_server_get_eap_user(void *ctx, const u8 *identity,
+				      size_t identity_len, int phase2,
+				      struct eap_user *user)
+{
+	struct radius_session *sess = ctx;
+	struct radius_server_data *data = sess->server;
+
+	return data->get_eap_user(data->conf_ctx, identity, identity_len,
+				  phase2, user);
+}
+
+
+static const char * radius_server_get_eap_req_id_text(void *ctx, size_t *len)
+{
+	struct radius_session *sess = ctx;
+	struct radius_server_data *data = sess->server;
+	*len = data->eap_req_id_text_len;
+	return data->eap_req_id_text;
+}
+
+
+static struct eapol_callbacks radius_server_eapol_cb =
+{
+	.get_eap_user = radius_server_get_eap_user,
+	.get_eap_req_id_text = radius_server_get_eap_req_id_text,
+};
+
+
+/**
+ * radius_server_eap_pending_cb - Pending EAP data notification
+ * @data: RADIUS server context from radius_server_init()
+ * @ctx: Pending EAP context pointer
+ *
+ * This function is used to notify EAP server module that a pending operation
+ * has been completed and processing of the EAP session can proceed.
+ */
+void radius_server_eap_pending_cb(struct radius_server_data *data, void *ctx)
+{
+	struct radius_client *cli;
+	struct radius_session *s, *sess = NULL;
+	struct radius_msg *msg;
+
+	if (data == NULL)
+		return;
+
+	for (cli = data->clients; cli; cli = cli->next) {
+		for (s = cli->sessions; s; s = s->next) {
+			if (s->eap == ctx && s->last_msg) {
+				sess = s;
+				break;
+			}
+			if (sess)
+				break;
+		}
+		if (sess)
+			break;
+	}
+
+	if (sess == NULL) {
+		RADIUS_DEBUG("No session matched callback ctx");
+		return;
+	}
+
+	msg = sess->last_msg;
+	sess->last_msg = NULL;
+	eap_sm_pending_cb(sess->eap);
+	if (radius_server_request(data, msg,
+				  (struct sockaddr *) &sess->last_from,
+				  sess->last_fromlen, cli,
+				  sess->last_from_addr,
+				  sess->last_from_port, sess) == -2)
+		return; /* msg was stored with the session */
+
+	radius_msg_free(msg);
+}
diff --git a/src/radius/radius_server.h b/src/radius/radius_server.h
new file mode 100644
index 0000000..126e314
--- /dev/null
+++ b/src/radius/radius_server.h
@@ -0,0 +1,217 @@
+/*
+ * RADIUS authentication server
+ * Copyright (c) 2005-2009, Jouni Malinen <j@w1.fi>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ *
+ * Alternatively, this software may be distributed under the terms of BSD
+ * license.
+ *
+ * See README and COPYING for more details.
+ */
+
+#ifndef RADIUS_SERVER_H
+#define RADIUS_SERVER_H
+
+struct radius_server_data;
+struct eap_user;
+
+/**
+ * struct radius_server_conf - RADIUS server configuration
+ */
+struct radius_server_conf {
+	/**
+	 * auth_port - UDP port to listen to as an authentication server
+	 */
+	int auth_port;
+
+	/**
+	 * client_file - RADIUS client configuration file
+	 *
+	 * This file contains the RADIUS clients and the shared secret to be
+	 * used with them in a format where each client is on its own line. The
+	 * first item on the line is the IPv4 or IPv6 address of the client
+	 * with an optional address mask to allow full network to be specified
+	 * (e.g., 192.168.1.2 or 192.168.1.0/24). This is followed by white
+	 * space (space or tabulator) and the shared secret. Lines starting
+	 * with '#' are skipped and can be used as comments.
+	 */
+	char *client_file;
+
+	/**
+	 * conf_ctx - Context pointer for callbacks
+	 *
+	 * This is used as the ctx argument in get_eap_user() calls.
+	 */
+	void *conf_ctx;
+
+	/**
+	 * eap_sim_db_priv - EAP-SIM/AKA database context
+	 *
+	 * This is passed to the EAP-SIM/AKA server implementation as a
+	 * callback context.
+	 */
+	void *eap_sim_db_priv;
+
+	/**
+	 * ssl_ctx - TLS context
+	 *
+	 * This is passed to the EAP server implementation as a callback
+	 * context for TLS operations.
+	 */
+	void *ssl_ctx;
+
+	/**
+	 * pac_opaque_encr_key - PAC-Opaque encryption key for EAP-FAST
+	 *
+	 * This parameter is used to set a key for EAP-FAST to encrypt the
+	 * PAC-Opaque data. It can be set to %NULL if EAP-FAST is not used. If
+	 * set, must point to a 16-octet key.
+	 */
+	u8 *pac_opaque_encr_key;
+
+	/**
+	 * eap_fast_a_id - EAP-FAST authority identity (A-ID)
+	 *
+	 * If EAP-FAST is not used, this can be set to %NULL. In theory, this
+	 * is a variable length field, but due to some existing implementations
+	 * requiring A-ID to be 16 octets in length, it is recommended to use
+	 * that length for the field to provide interoperability with deployed
+	 * peer implementations.
+	 */
+	u8 *eap_fast_a_id;
+
+	/**
+	 * eap_fast_a_id_len - Length of eap_fast_a_id buffer in octets
+	 */
+	size_t eap_fast_a_id_len;
+
+	/**
+	 * eap_fast_a_id_info - EAP-FAST authority identifier information
+	 *
+	 * This A-ID-Info contains a user-friendly name for the A-ID. For
+	 * example, this could be the enterprise and server names in
+	 * human-readable format. This field is encoded as UTF-8. If EAP-FAST
+	 * is not used, this can be set to %NULL.
+	 */
+	char *eap_fast_a_id_info;
+
+	/**
+	 * eap_fast_prov - EAP-FAST provisioning modes
+	 *
+	 * 0 = provisioning disabled, 1 = only anonymous provisioning allowed,
+	 * 2 = only authenticated provisioning allowed, 3 = both provisioning
+	 * modes allowed.
+	 */
+	int eap_fast_prov;
+
+	/**
+	 * pac_key_lifetime - EAP-FAST PAC-Key lifetime in seconds
+	 *
+	 * This is the hard limit on how long a provisioned PAC-Key can be
+	 * used.
+	 */
+	int pac_key_lifetime;
+
+	/**
+	 * pac_key_refresh_time - EAP-FAST PAC-Key refresh time in seconds
+	 *
+	 * This is a soft limit on the PAC-Key. The server will automatically
+	 * generate a new PAC-Key when this number of seconds (or fewer) of the
+	 * lifetime remains.
+	 */
+	int pac_key_refresh_time;
+
+	/**
+	 * eap_sim_aka_result_ind - EAP-SIM/AKA protected success indication
+	 *
+	 * This controls whether the protected success/failure indication
+	 * (AT_RESULT_IND) is used with EAP-SIM and EAP-AKA.
+	 */
+	int eap_sim_aka_result_ind;
+
+	/**
+	 * tnc - Trusted Network Connect (TNC)
+	 *
+	 * This controls whether TNC is enabled and will be required before the
+	 * peer is allowed to connect. Note: This is only used with EAP-TTLS
+	 * and EAP-FAST. If any other EAP method is enabled, the peer will be
+	 * allowed to connect without TNC.
+	 */
+	int tnc;
+
+	/**
+	 * pwd_group - EAP-pwd D-H group
+	 *
+	 * This is used to select which D-H group to use with EAP-pwd.
+	 */
+	u16 pwd_group;
+
+	/**
+	 * wps - Wi-Fi Protected Setup context
+	 *
+	 * If WPS is used with an external RADIUS server (which is quite
+	 * unlikely configuration), this is used to provide a pointer to WPS
+	 * context data. Normally, this can be set to %NULL.
+	 */
+	struct wps_context *wps;
+
+	/**
+	 * ipv6 - Whether to enable IPv6 support in the RADIUS server
+	 */
+	int ipv6;
+
+	/**
+	 * get_eap_user - Callback for fetching EAP user information
+	 * @ctx: Context data from conf_ctx
+	 * @identity: User identity
+	 * @identity_len: identity buffer length in octets
+	 * @phase2: Whether this is for Phase 2 identity
+	 * @user: Data structure for filling in the user information
+	 * Returns: 0 on success, -1 on failure
+	 *
+	 * This is used to fetch information from user database. The callback
+	 * will fill in information about allowed EAP methods and the user
+	 * password. The password field will be an allocated copy of the
+	 * password data and RADIUS server will free it after use.
+	 */
+	int (*get_eap_user)(void *ctx, const u8 *identity, size_t identity_len,
+			    int phase2, struct eap_user *user);
+
+	/**
+	 * eap_req_id_text - Optional data for EAP-Request/Identity
+	 *
+	 * This can be used to configure an optional, displayable message that
+	 * will be sent in EAP-Request/Identity. This string can contain an
+	 * ASCII-0 character (nul) to separate network infromation per RFC
+	 * 4284. The actual string length is explicit provided in
+	 * eap_req_id_text_len since nul character will not be used as a string
+	 * terminator.
+	 */
+	const char *eap_req_id_text;
+
+	/**
+	 * eap_req_id_text_len - Length of eap_req_id_text buffer in octets
+	 */
+	size_t eap_req_id_text_len;
+
+	/*
+	 * msg_ctx - Context data for wpa_msg() calls
+	 */
+	void *msg_ctx;
+};
+
+
+struct radius_server_data *
+radius_server_init(struct radius_server_conf *conf);
+
+void radius_server_deinit(struct radius_server_data *data);
+
+int radius_server_get_mib(struct radius_server_data *data, char *buf,
+			  size_t buflen);
+
+void radius_server_eap_pending_cb(struct radius_server_data *data, void *ctx);
+
+#endif /* RADIUS_SERVER_H */