summaryrefslogtreecommitdiff
path: root/src/utils
diff options
context:
space:
mode:
Diffstat (limited to 'src/utils')
-rw-r--r--src/utils/Makefile4
-rw-r--r--src/utils/base64.c18
-rw-r--r--src/utils/bitfield.c89
-rw-r--r--src/utils/bitfield.h21
-rw-r--r--src/utils/browser-android.c128
-rw-r--r--src/utils/browser-system.c119
-rw-r--r--src/utils/browser-wpadebug.c136
-rw-r--r--src/utils/browser.c219
-rw-r--r--src/utils/browser.h21
-rw-r--r--src/utils/build_config.h27
-rw-r--r--src/utils/common.c496
-rw-r--r--src/utils/common.h201
-rw-r--r--src/utils/edit.c4
-rw-r--r--src/utils/edit_readline.c4
-rw-r--r--src/utils/edit_simple.c2
-rw-r--r--src/utils/eloop.c333
-rw-r--r--src/utils/eloop.h49
-rw-r--r--src/utils/eloop_none.c395
-rw-r--r--src/utils/eloop_win.c224
-rw-r--r--src/utils/ext_password_test.c2
-rw-r--r--src/utils/http-utils.h63
-rw-r--r--src/utils/http_curl.c1641
-rw-r--r--src/utils/ip_addr.c24
-rw-r--r--src/utils/ip_addr.h1
-rw-r--r--src/utils/list.h2
-rw-r--r--src/utils/os.h158
-rw-r--r--src/utils/os_internal.c89
-rw-r--r--src/utils/os_none.c17
-rw-r--r--src/utils/os_unix.c232
-rw-r--r--src/utils/os_win32.c32
-rw-r--r--src/utils/pcsc_funcs.c117
-rw-r--r--src/utils/pcsc_funcs.h11
-rw-r--r--src/utils/platform.h21
-rw-r--r--src/utils/radiotap.c379
-rw-r--r--src/utils/radiotap.h56
-rw-r--r--src/utils/radiotap_iter.h108
-rw-r--r--src/utils/trace.c62
-rw-r--r--src/utils/trace.h1
-rw-r--r--src/utils/utils_module_tests.c423
-rw-r--r--src/utils/uuid.c2
-rw-r--r--src/utils/wpa_debug.c132
-rw-r--r--src/utils/wpa_debug.h68
-rw-r--r--src/utils/wpabuf.c9
-rw-r--r--src/utils/wpabuf.h1
-rw-r--r--src/utils/xml-utils.c471
-rw-r--r--src/utils/xml-utils.h97
-rw-r--r--src/utils/xml_libxml2.c457
47 files changed, 6212 insertions, 954 deletions
diff --git a/src/utils/Makefile b/src/utils/Makefile
index 0f1f191099953..8aad813cfc858 100644
--- a/src/utils/Makefile
+++ b/src/utils/Makefile
@@ -1,7 +1,7 @@
all: libutils.a
clean:
- rm -f *~ *.o *.d libutils.a
+ rm -f *~ *.o *.d *.gcno *.gcda *.gcov libutils.a
install:
@echo Nothing to be made.
@@ -11,9 +11,11 @@ include ../lib.rules
#CFLAGS += -DWPA_TRACE
CFLAGS += -DCONFIG_IPV6
+CFLAGS += -DCONFIG_DEBUG_FILE
LIB_OBJS= \
base64.o \
+ bitfield.o \
common.o \
ip_addr.o \
radiotap.o \
diff --git a/src/utils/base64.c b/src/utils/base64.c
index af1307fc4e650..d44f290e56849 100644
--- a/src/utils/base64.c
+++ b/src/utils/base64.c
@@ -48,9 +48,11 @@ unsigned char * base64_encode(const unsigned char *src, size_t len,
pos = out;
line_len = 0;
while (end - in >= 3) {
- *pos++ = base64_table[in[0] >> 2];
- *pos++ = base64_table[((in[0] & 0x03) << 4) | (in[1] >> 4)];
- *pos++ = base64_table[((in[1] & 0x0f) << 2) | (in[2] >> 6)];
+ *pos++ = base64_table[(in[0] >> 2) & 0x3f];
+ *pos++ = base64_table[(((in[0] & 0x03) << 4) |
+ (in[1] >> 4)) & 0x3f];
+ *pos++ = base64_table[(((in[1] & 0x0f) << 2) |
+ (in[2] >> 6)) & 0x3f];
*pos++ = base64_table[in[2] & 0x3f];
in += 3;
line_len += 4;
@@ -61,14 +63,14 @@ unsigned char * base64_encode(const unsigned char *src, size_t len,
}
if (end - in) {
- *pos++ = base64_table[in[0] >> 2];
+ *pos++ = base64_table[(in[0] >> 2) & 0x3f];
if (end - in == 1) {
- *pos++ = base64_table[(in[0] & 0x03) << 4];
+ *pos++ = base64_table[((in[0] & 0x03) << 4) & 0x3f];
*pos++ = '=';
} else {
- *pos++ = base64_table[((in[0] & 0x03) << 4) |
- (in[1] >> 4)];
- *pos++ = base64_table[(in[1] & 0x0f) << 2];
+ *pos++ = base64_table[(((in[0] & 0x03) << 4) |
+ (in[1] >> 4)) & 0x3f];
+ *pos++ = base64_table[((in[1] & 0x0f) << 2) & 0x3f];
}
*pos++ = '=';
line_len += 4;
diff --git a/src/utils/bitfield.c b/src/utils/bitfield.c
new file mode 100644
index 0000000000000..8dcec3907e9e9
--- /dev/null
+++ b/src/utils/bitfield.c
@@ -0,0 +1,89 @@
+/*
+ * Bitfield
+ * Copyright (c) 2013, Jouni Malinen <j@w1.fi>
+ *
+ * This software may be distributed under the terms of the BSD license.
+ * See README for more details.
+ */
+
+#include "includes.h"
+
+#include "common.h"
+#include "bitfield.h"
+
+
+struct bitfield {
+ u8 *bits;
+ size_t max_bits;
+};
+
+
+struct bitfield * bitfield_alloc(size_t max_bits)
+{
+ struct bitfield *bf;
+
+ bf = os_zalloc(sizeof(*bf) + (max_bits + 7) / 8);
+ if (bf == NULL)
+ return NULL;
+ bf->bits = (u8 *) (bf + 1);
+ bf->max_bits = max_bits;
+ return bf;
+}
+
+
+void bitfield_free(struct bitfield *bf)
+{
+ os_free(bf);
+}
+
+
+void bitfield_set(struct bitfield *bf, size_t bit)
+{
+ if (bit >= bf->max_bits)
+ return;
+ bf->bits[bit / 8] |= BIT(bit % 8);
+}
+
+
+void bitfield_clear(struct bitfield *bf, size_t bit)
+{
+ if (bit >= bf->max_bits)
+ return;
+ bf->bits[bit / 8] &= ~BIT(bit % 8);
+}
+
+
+int bitfield_is_set(struct bitfield *bf, size_t bit)
+{
+ if (bit >= bf->max_bits)
+ return 0;
+ return !!(bf->bits[bit / 8] & BIT(bit % 8));
+}
+
+
+static int first_zero(u8 val)
+{
+ int i;
+ for (i = 0; i < 8; i++) {
+ if (!(val & 0x01))
+ return i;
+ val >>= 1;
+ }
+ return -1;
+}
+
+
+int bitfield_get_first_zero(struct bitfield *bf)
+{
+ size_t i;
+ for (i = 0; i < (bf->max_bits + 7) / 8; i++) {
+ if (bf->bits[i] != 0xff)
+ break;
+ }
+ if (i == (bf->max_bits + 7) / 8)
+ return -1;
+ i = i * 8 + first_zero(bf->bits[i]);
+ if (i >= bf->max_bits)
+ return -1;
+ return i;
+}
diff --git a/src/utils/bitfield.h b/src/utils/bitfield.h
new file mode 100644
index 0000000000000..7050a208c8f68
--- /dev/null
+++ b/src/utils/bitfield.h
@@ -0,0 +1,21 @@
+/*
+ * Bitfield
+ * Copyright (c) 2013, Jouni Malinen <j@w1.fi>
+ *
+ * This software may be distributed under the terms of the BSD license.
+ * See README for more details.
+ */
+
+#ifndef BITFIELD_H
+#define BITFIELD_H
+
+struct bitfield;
+
+struct bitfield * bitfield_alloc(size_t max_bits);
+void bitfield_free(struct bitfield *bf);
+void bitfield_set(struct bitfield *bf, size_t bit);
+void bitfield_clear(struct bitfield *bf, size_t bit);
+int bitfield_is_set(struct bitfield *bf, size_t bit);
+int bitfield_get_first_zero(struct bitfield *bf);
+
+#endif /* BITFIELD_H */
diff --git a/src/utils/browser-android.c b/src/utils/browser-android.c
new file mode 100644
index 0000000000000..9ce1a5cbeae10
--- /dev/null
+++ b/src/utils/browser-android.c
@@ -0,0 +1,128 @@
+/*
+ * Hotspot 2.0 client - Web browser using Android browser
+ * Copyright (c) 2013, Qualcomm Atheros, Inc.
+ *
+ * This software may be distributed under the terms of the BSD license.
+ * See README for more details.
+ */
+
+#include "includes.h"
+
+#include "common.h"
+#include "utils/eloop.h"
+#include "wps/http_server.h"
+#include "browser.h"
+
+
+struct browser_data {
+ int success;
+};
+
+
+static void browser_timeout(void *eloop_data, void *user_ctx)
+{
+ wpa_printf(MSG_INFO, "Timeout on waiting browser interaction to "
+ "complete");
+ eloop_terminate();
+}
+
+
+static void http_req(void *ctx, struct http_request *req)
+{
+ struct browser_data *data = ctx;
+ struct wpabuf *resp;
+ const char *url;
+ int done = 0;
+
+ url = http_request_get_uri(req);
+ wpa_printf(MSG_INFO, "Browser response received: %s", url);
+
+ if (os_strcmp(url, "/") == 0) {
+ data->success = 1;
+ done = 1;
+ } else if (os_strncmp(url, "/osu/", 5) == 0) {
+ data->success = atoi(url + 5);
+ done = 1;
+ }
+
+ resp = wpabuf_alloc(1);
+ if (resp == NULL) {
+ http_request_deinit(req);
+ if (done)
+ eloop_terminate();
+ return;
+ }
+
+ if (done) {
+ eloop_cancel_timeout(browser_timeout, NULL, NULL);
+ eloop_register_timeout(0, 500000, browser_timeout, &data, NULL);
+ }
+
+ http_request_send_and_deinit(req, resp);
+}
+
+
+int hs20_web_browser(const char *url)
+{
+ struct http_server *http;
+ struct in_addr addr;
+ struct browser_data data;
+ pid_t pid;
+
+ wpa_printf(MSG_INFO, "Launching Android browser to %s", url);
+
+ os_memset(&data, 0, sizeof(data));
+
+ if (eloop_init() < 0) {
+ wpa_printf(MSG_ERROR, "eloop_init failed");
+ return -1;
+ }
+ addr.s_addr = htonl((127 << 24) | 1);
+ http = http_server_init(&addr, 12345, http_req, &data);
+ if (http == NULL) {
+ wpa_printf(MSG_ERROR, "http_server_init failed");
+ eloop_destroy();
+ return -1;
+ }
+
+ pid = fork();
+ if (pid < 0) {
+ wpa_printf(MSG_ERROR, "fork: %s", strerror(errno));
+ http_server_deinit(http);
+ eloop_destroy();
+ return -1;
+ }
+
+ if (pid == 0) {
+ /* run the external command in the child process */
+ char *argv[9];
+
+ argv[0] = "browser-android";
+ argv[1] = "start";
+ argv[2] = "-a";
+ argv[3] = "android.intent.action.VIEW";
+ argv[4] = "-d";
+ argv[5] = (void *) url;
+ argv[6] = "-n";
+ argv[7] = "com.android.browser/.BrowserActivity";
+ argv[8] = NULL;
+
+ execv("/system/bin/am", argv);
+ wpa_printf(MSG_ERROR, "execv: %s", strerror(errno));
+ exit(0);
+ return -1;
+ }
+
+ eloop_register_timeout(30, 0, browser_timeout, &data, NULL);
+ eloop_run();
+ eloop_cancel_timeout(browser_timeout, &data, NULL);
+ http_server_deinit(http);
+ eloop_destroy();
+
+ wpa_printf(MSG_INFO, "Closing Android browser");
+ if (system("/system/bin/input keyevent KEYCODE_HOME") != 0) {
+ wpa_printf(MSG_INFO, "Failed to inject keyevent");
+ }
+
+ return data.success;
+}
diff --git a/src/utils/browser-system.c b/src/utils/browser-system.c
new file mode 100644
index 0000000000000..aed39706c2e10
--- /dev/null
+++ b/src/utils/browser-system.c
@@ -0,0 +1,119 @@
+/*
+ * Hotspot 2.0 client - Web browser using system browser
+ * Copyright (c) 2013, Qualcomm Atheros, Inc.
+ *
+ * This software may be distributed under the terms of the BSD license.
+ * See README for more details.
+ */
+
+#include "includes.h"
+
+#include "common.h"
+#include "utils/eloop.h"
+#include "wps/http_server.h"
+#include "browser.h"
+
+
+struct browser_data {
+ int success;
+};
+
+
+static void browser_timeout(void *eloop_data, void *user_ctx)
+{
+ wpa_printf(MSG_INFO, "Timeout on waiting browser interaction to "
+ "complete");
+ eloop_terminate();
+}
+
+
+static void http_req(void *ctx, struct http_request *req)
+{
+ struct browser_data *data = ctx;
+ struct wpabuf *resp;
+ const char *url;
+ int done = 0;
+
+ url = http_request_get_uri(req);
+ wpa_printf(MSG_INFO, "Browser response received: %s", url);
+
+ if (os_strcmp(url, "/") == 0) {
+ data->success = 1;
+ done = 1;
+ } else if (os_strncmp(url, "/osu/", 5) == 0) {
+ data->success = atoi(url + 5);
+ done = 1;
+ }
+
+ resp = wpabuf_alloc(1);
+ if (resp == NULL) {
+ http_request_deinit(req);
+ if (done)
+ eloop_terminate();
+ return;
+ }
+
+ if (done) {
+ eloop_cancel_timeout(browser_timeout, NULL, NULL);
+ eloop_register_timeout(0, 500000, browser_timeout, &data, NULL);
+ }
+
+ http_request_send_and_deinit(req, resp);
+}
+
+
+int hs20_web_browser(const char *url)
+{
+ struct http_server *http;
+ struct in_addr addr;
+ struct browser_data data;
+ pid_t pid;
+
+ wpa_printf(MSG_INFO, "Launching system browser to %s", url);
+
+ os_memset(&data, 0, sizeof(data));
+
+ if (eloop_init() < 0) {
+ wpa_printf(MSG_ERROR, "eloop_init failed");
+ return -1;
+ }
+ addr.s_addr = htonl((127 << 24) | 1);
+ http = http_server_init(&addr, 12345, http_req, &data);
+ if (http == NULL) {
+ wpa_printf(MSG_ERROR, "http_server_init failed");
+ eloop_destroy();
+ return -1;
+ }
+
+ pid = fork();
+ if (pid < 0) {
+ wpa_printf(MSG_ERROR, "fork: %s", strerror(errno));
+ http_server_deinit(http);
+ eloop_destroy();
+ return -1;
+ }
+
+ if (pid == 0) {
+ /* run the external command in the child process */
+ char *argv[3];
+
+ argv[0] = "browser-system";
+ argv[1] = (void *) url;
+ argv[2] = NULL;
+
+ execv("/usr/bin/x-www-browser", argv);
+ wpa_printf(MSG_ERROR, "execv: %s", strerror(errno));
+ exit(0);
+ return -1;
+ }
+
+ eloop_register_timeout(120, 0, browser_timeout, &data, NULL);
+ eloop_run();
+ eloop_cancel_timeout(browser_timeout, &data, NULL);
+ http_server_deinit(http);
+ eloop_destroy();
+
+ /* TODO: Close browser */
+
+ return data.success;
+}
diff --git a/src/utils/browser-wpadebug.c b/src/utils/browser-wpadebug.c
new file mode 100644
index 0000000000000..5fc40fac610e9
--- /dev/null
+++ b/src/utils/browser-wpadebug.c
@@ -0,0 +1,136 @@
+/*
+ * Hotspot 2.0 client - Web browser using wpadebug on Android
+ * Copyright (c) 2013, Qualcomm Atheros, Inc.
+ *
+ * This software may be distributed under the terms of the BSD license.
+ * See README for more details.
+ */
+
+#include "includes.h"
+
+#include "common.h"
+#include "utils/eloop.h"
+#include "wps/http_server.h"
+#include "browser.h"
+
+
+struct browser_data {
+ int success;
+};
+
+
+static void browser_timeout(void *eloop_data, void *user_ctx)
+{
+ wpa_printf(MSG_INFO, "Timeout on waiting browser interaction to "
+ "complete");
+ eloop_terminate();
+}
+
+
+static void http_req(void *ctx, struct http_request *req)
+{
+ struct browser_data *data = ctx;
+ struct wpabuf *resp;
+ const char *url;
+ int done = 0;
+
+ url = http_request_get_uri(req);
+ wpa_printf(MSG_INFO, "Browser response received: %s", url);
+
+ if (os_strcmp(url, "/") == 0) {
+ data->success = 1;
+ done = 1;
+ } else if (os_strncmp(url, "/osu/", 5) == 0) {
+ data->success = atoi(url + 5);
+ done = 1;
+ }
+
+ resp = wpabuf_alloc(100);
+ if (resp == NULL) {
+ http_request_deinit(req);
+ if (done)
+ eloop_terminate();
+ return;
+ }
+ wpabuf_put_str(resp, "User input completed");
+
+ if (done) {
+ eloop_cancel_timeout(browser_timeout, NULL, NULL);
+ eloop_register_timeout(0, 500000, browser_timeout, &data, NULL);
+ }
+
+ http_request_send_and_deinit(req, resp);
+}
+
+
+int hs20_web_browser(const char *url)
+{
+ struct http_server *http;
+ struct in_addr addr;
+ struct browser_data data;
+ pid_t pid;
+
+ wpa_printf(MSG_INFO, "Launching wpadebug browser to %s", url);
+
+ os_memset(&data, 0, sizeof(data));
+
+ if (eloop_init() < 0) {
+ wpa_printf(MSG_ERROR, "eloop_init failed");
+ return -1;
+ }
+ addr.s_addr = htonl((127 << 24) | 1);
+ http = http_server_init(&addr, 12345, http_req, &data);
+ if (http == NULL) {
+ wpa_printf(MSG_ERROR, "http_server_init failed");
+ eloop_destroy();
+ return -1;
+ }
+
+ pid = fork();
+ if (pid < 0) {
+ wpa_printf(MSG_ERROR, "fork: %s", strerror(errno));
+ http_server_deinit(http);
+ eloop_destroy();
+ return -1;
+ }
+
+ if (pid == 0) {
+ /* run the external command in the child process */
+ char *argv[12];
+
+ argv[0] = "browser-wpadebug";
+ argv[1] = "start";
+ argv[2] = "-a";
+ argv[3] = "android.action.MAIN";
+ argv[4] = "-c";
+ argv[5] = "android.intent.category.LAUNCHER";
+ argv[6] = "-n";
+ argv[7] = "w1.fi.wpadebug/.WpaWebViewActivity";
+ argv[8] = "-e";
+ argv[9] = "w1.fi.wpadebug.URL";
+ argv[10] = (void *) url;
+ argv[11] = NULL;
+
+ execv("/system/bin/am", argv);
+ wpa_printf(MSG_ERROR, "execv: %s", strerror(errno));
+ exit(0);
+ return -1;
+ }
+
+ eloop_register_timeout(300, 0, browser_timeout, &data, NULL);
+ eloop_run();
+ eloop_cancel_timeout(browser_timeout, &data, NULL);
+ http_server_deinit(http);
+ eloop_destroy();
+
+ wpa_printf(MSG_INFO, "Closing Android browser");
+ if (os_exec("/system/bin/am",
+ "start -a android.action.MAIN "
+ "-c android.intent.category.LAUNCHER "
+ "-n w1.fi.wpadebug/.WpaWebViewActivity "
+ "-e w1.fi.wpadebug.URL FINISH", 1) != 0) {
+ wpa_printf(MSG_INFO, "Failed to close wpadebug browser");
+ }
+
+ return data.success;
+}
diff --git a/src/utils/browser.c b/src/utils/browser.c
new file mode 100644
index 0000000000000..9cf6152d6cbd8
--- /dev/null
+++ b/src/utils/browser.c
@@ -0,0 +1,219 @@
+/*
+ * Hotspot 2.0 client - Web browser using WebKit
+ * Copyright (c) 2013, Qualcomm Atheros, Inc.
+ *
+ * This software may be distributed under the terms of the BSD license.
+ * See README for more details.
+ */
+
+#include "includes.h"
+#include <webkit/webkit.h>
+
+#include "common.h"
+#include "browser.h"
+
+
+struct browser_context {
+ GtkWidget *win;
+ int success;
+ int progress;
+ char *hover_link;
+ char *title;
+};
+
+static void win_cb_destroy(GtkWidget *win, struct browser_context *ctx)
+{
+ wpa_printf(MSG_DEBUG, "BROWSER:%s", __func__);
+ gtk_main_quit();
+}
+
+
+static void browser_update_title(struct browser_context *ctx)
+{
+ char buf[100];
+
+ if (ctx->hover_link) {
+ gtk_window_set_title(GTK_WINDOW(ctx->win), ctx->hover_link);
+ return;
+ }
+
+ if (ctx->progress == 100) {
+ gtk_window_set_title(GTK_WINDOW(ctx->win),
+ ctx->title ? ctx->title :
+ "Hotspot 2.0 client");
+ return;
+ }
+
+ snprintf(buf, sizeof(buf), "[%d%%] %s", ctx->progress,
+ ctx->title ? ctx->title : "Hotspot 2.0 client");
+ gtk_window_set_title(GTK_WINDOW(ctx->win), buf);
+}
+
+
+static void view_cb_notify_progress(WebKitWebView *view, GParamSpec *pspec,
+ struct browser_context *ctx)
+{
+ ctx->progress = 100 * webkit_web_view_get_progress(view);
+ wpa_printf(MSG_DEBUG, "BROWSER:%s progress=%d", __func__,
+ ctx->progress);
+ browser_update_title(ctx);
+}
+
+
+static void view_cb_notify_load_status(WebKitWebView *view, GParamSpec *pspec,
+ struct browser_context *ctx)
+{
+ int status = webkit_web_view_get_load_status(view);
+ wpa_printf(MSG_DEBUG, "BROWSER:%s load-status=%d uri=%s",
+ __func__, status, webkit_web_view_get_uri(view));
+}
+
+
+static void view_cb_resource_request_starting(WebKitWebView *view,
+ WebKitWebFrame *frame,
+ WebKitWebResource *res,
+ WebKitNetworkRequest *req,
+ WebKitNetworkResponse *resp,
+ struct browser_context *ctx)
+{
+ const gchar *uri = webkit_network_request_get_uri(req);
+ wpa_printf(MSG_DEBUG, "BROWSER:%s uri=%s", __func__, uri);
+ if (g_str_has_suffix(uri, "/favicon.ico"))
+ webkit_network_request_set_uri(req, "about:blank");
+ if (g_str_has_prefix(uri, "osu://")) {
+ ctx->success = atoi(uri + 6);
+ gtk_main_quit();
+ }
+ if (g_str_has_prefix(uri, "http://localhost:12345")) {
+ /*
+ * This is used as a special trigger to indicate that the
+ * user exchange has been completed.
+ */
+ ctx->success = 1;
+ gtk_main_quit();
+ }
+}
+
+
+static gboolean view_cb_mime_type_policy_decision(
+ WebKitWebView *view, WebKitWebFrame *frame, WebKitNetworkRequest *req,
+ gchar *mime, WebKitWebPolicyDecision *policy,
+ struct browser_context *ctx)
+{
+ wpa_printf(MSG_DEBUG, "BROWSER:%s mime=%s", __func__, mime);
+
+ if (!webkit_web_view_can_show_mime_type(view, mime)) {
+ webkit_web_policy_decision_download(policy);
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+
+static gboolean view_cb_download_requested(WebKitWebView *view,
+ WebKitDownload *dl,
+ struct browser_context *ctx)
+{
+ const gchar *uri;
+ uri = webkit_download_get_uri(dl);
+ wpa_printf(MSG_DEBUG, "BROWSER:%s uri=%s", __func__, uri);
+ return FALSE;
+}
+
+
+static void view_cb_hovering_over_link(WebKitWebView *view, gchar *title,
+ gchar *uri, struct browser_context *ctx)
+{
+ wpa_printf(MSG_DEBUG, "BROWSER:%s title=%s uri=%s", __func__, title,
+ uri);
+ os_free(ctx->hover_link);
+ if (uri)
+ ctx->hover_link = os_strdup(uri);
+ else
+ ctx->hover_link = NULL;
+
+ browser_update_title(ctx);
+}
+
+
+static void view_cb_title_changed(WebKitWebView *view, WebKitWebFrame *frame,
+ const char *title,
+ struct browser_context *ctx)
+{
+ wpa_printf(MSG_DEBUG, "BROWSER:%s title=%s", __func__, title);
+ os_free(ctx->title);
+ ctx->title = os_strdup(title);
+ browser_update_title(ctx);
+}
+
+
+int hs20_web_browser(const char *url)
+{
+ GtkWidget *scroll;
+ SoupSession *s;
+ WebKitWebView *view;
+ WebKitWebSettings *settings;
+ struct browser_context ctx;
+
+ memset(&ctx, 0, sizeof(ctx));
+ if (!gtk_init_check(NULL, NULL))
+ return -1;
+
+ s = webkit_get_default_session();
+ g_object_set(G_OBJECT(s), "ssl-ca-file",
+ "/etc/ssl/certs/ca-certificates.crt", NULL);
+ g_object_set(G_OBJECT(s), "ssl-strict", FALSE, NULL);
+
+ ctx.win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
+ gtk_window_set_wmclass(GTK_WINDOW(ctx.win), "Hotspot 2.0 client",
+ "Hotspot 2.0 client");
+ gtk_window_set_default_size(GTK_WINDOW(ctx.win), 800, 600);
+
+ scroll = gtk_scrolled_window_new(NULL, NULL);
+ gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
+ GTK_POLICY_NEVER, GTK_POLICY_NEVER);
+
+ g_signal_connect(G_OBJECT(ctx.win), "destroy",
+ G_CALLBACK(win_cb_destroy), &ctx);
+
+ view = WEBKIT_WEB_VIEW(webkit_web_view_new());
+ g_signal_connect(G_OBJECT(view), "notify::progress",
+ G_CALLBACK(view_cb_notify_progress), &ctx);
+ g_signal_connect(G_OBJECT(view), "notify::load-status",
+ G_CALLBACK(view_cb_notify_load_status), &ctx);
+ g_signal_connect(G_OBJECT(view), "resource-request-starting",
+ G_CALLBACK(view_cb_resource_request_starting), &ctx);
+ g_signal_connect(G_OBJECT(view), "mime-type-policy-decision-requested",
+ G_CALLBACK(view_cb_mime_type_policy_decision), &ctx);
+ g_signal_connect(G_OBJECT(view), "download-requested",
+ G_CALLBACK(view_cb_download_requested), &ctx);
+ g_signal_connect(G_OBJECT(view), "hovering-over-link",
+ G_CALLBACK(view_cb_hovering_over_link), &ctx);
+ g_signal_connect(G_OBJECT(view), "title-changed",
+ G_CALLBACK(view_cb_title_changed), &ctx);
+
+ gtk_container_add(GTK_CONTAINER(scroll), GTK_WIDGET(view));
+ gtk_container_add(GTK_CONTAINER(ctx.win), GTK_WIDGET(scroll));
+
+ gtk_widget_grab_focus(GTK_WIDGET(view));
+ gtk_widget_show_all(ctx.win);
+
+ settings = webkit_web_view_get_settings(view);
+ g_object_set(G_OBJECT(settings), "user-agent",
+ "Mozilla/5.0 (X11; U; Unix; en-US) "
+ "AppleWebKit/537.15 (KHTML, like Gecko) "
+ "hs20-client/1.0", NULL);
+ g_object_set(G_OBJECT(settings), "auto-load-images", TRUE, NULL);
+
+ webkit_web_view_load_uri(view, url);
+
+ gtk_main();
+ gtk_widget_destroy(ctx.win);
+ while (gtk_events_pending())
+ gtk_main_iteration();
+
+ free(ctx.hover_link);
+ free(ctx.title);
+ return ctx.success;
+}
diff --git a/src/utils/browser.h b/src/utils/browser.h
new file mode 100644
index 0000000000000..aaa0eed269f79
--- /dev/null
+++ b/src/utils/browser.h
@@ -0,0 +1,21 @@
+/*
+ * Hotspot 2.0 client - Web browser
+ * Copyright (c) 2013, Qualcomm Atheros, Inc.
+ *
+ * This software may be distributed under the terms of the BSD license.
+ * See README for more details.
+ */
+
+#ifndef BROWSER_H
+#define BROWSER_H
+
+#ifdef CONFIG_NO_BROWSER
+static inline int hs20_web_browser(const char *url)
+{
+ return -1;
+}
+#else /* CONFIG_NO_BROWSER */
+int hs20_web_browser(const char *url);
+#endif /* CONFIG_NO_BROWSER */
+
+#endif /* BROWSER_H */
diff --git a/src/utils/build_config.h b/src/utils/build_config.h
index f947388552dbe..c6f4e4379ae69 100644
--- a/src/utils/build_config.h
+++ b/src/utils/build_config.h
@@ -47,31 +47,4 @@
#endif /* USE_INTERNAL_CRYPTO */
#endif /* CONFIG_WIN32_DEFAULTS */
-#ifdef CONFIG_XCODE_DEFAULTS
-#define CONFIG_DRIVER_OSX
-#define CONFIG_BACKEND_FILE
-#define IEEE8021X_EAPOL
-#define PKCS12_FUNCS
-#define CONFIG_CTRL_IFACE
-#define CONFIG_CTRL_IFACE_UNIX
-#define CONFIG_DEBUG_FILE
-#define EAP_MD5
-#define EAP_TLS
-#define EAP_MSCHAPv2
-#define EAP_PEAP
-#define EAP_TTLS
-#define EAP_GTC
-#define EAP_OTP
-#define EAP_LEAP
-#define EAP_TNC
-#define CONFIG_WPS
-#define EAP_WSC
-
-#ifdef USE_INTERNAL_CRYPTO
-#define CONFIG_TLS_INTERNAL_CLIENT
-#define CONFIG_INTERNAL_LIBTOMMATH
-#define CONFIG_CRYPTO_INTERNAL
-#endif /* USE_INTERNAL_CRYPTO */
-#endif /* CONFIG_XCODE_DEFAULTS */
-
#endif /* BUILD_CONFIG_H */
diff --git a/src/utils/common.c b/src/utils/common.c
index e63698491444b..5fd795f3f3036 100644
--- a/src/utils/common.c
+++ b/src/utils/common.c
@@ -36,6 +36,25 @@ int hex2byte(const char *hex)
}
+static const char * hwaddr_parse(const char *txt, u8 *addr)
+{
+ size_t i;
+
+ for (i = 0; i < ETH_ALEN; i++) {
+ int a;
+
+ a = hex2byte(txt);
+ if (a < 0)
+ return NULL;
+ txt += 2;
+ addr[i] = a;
+ if (i < ETH_ALEN - 1 && *txt++ != ':')
+ return NULL;
+ }
+ return txt;
+}
+
+
/**
* hwaddr_aton - Convert ASCII string to MAC address (colon-delimited format)
* @txt: MAC address as a string (e.g., "00:11:22:33:44:55")
@@ -44,25 +63,46 @@ int hex2byte(const char *hex)
*/
int hwaddr_aton(const char *txt, u8 *addr)
{
- int i;
+ return hwaddr_parse(txt, addr) ? 0 : -1;
+}
- for (i = 0; i < 6; i++) {
- int a, b;
- a = hex2num(*txt++);
- if (a < 0)
- return -1;
- b = hex2num(*txt++);
- if (b < 0)
- return -1;
- *addr++ = (a << 4) | b;
- if (i < 5 && *txt++ != ':')
+/**
+ * hwaddr_masked_aton - Convert ASCII string with optional mask to MAC address (colon-delimited format)
+ * @txt: MAC address with optional mask as a string (e.g., "00:11:22:33:44:55/ff:ff:ff:ff:00:00")
+ * @addr: Buffer for the MAC address (ETH_ALEN = 6 bytes)
+ * @mask: Buffer for the MAC address mask (ETH_ALEN = 6 bytes)
+ * @maskable: Flag to indicate whether a mask is allowed
+ * Returns: 0 on success, -1 on failure (e.g., string not a MAC address)
+ */
+int hwaddr_masked_aton(const char *txt, u8 *addr, u8 *mask, u8 maskable)
+{
+ const char *r;
+
+ /* parse address part */
+ r = hwaddr_parse(txt, addr);
+ if (!r)
+ return -1;
+
+ /* check for optional mask */
+ if (*r == '\0' || isspace(*r)) {
+ /* no mask specified, assume default */
+ os_memset(mask, 0xff, ETH_ALEN);
+ } else if (maskable && *r == '/') {
+ /* mask specified and allowed */
+ r = hwaddr_parse(r + 1, mask);
+ /* parser error? */
+ if (!r)
return -1;
+ } else {
+ /* mask specified but not allowed or trailing garbage */
+ return -1;
}
return 0;
}
+
/**
* hwaddr_compact_aton - Convert ASCII string to MAC address (no colon delimitors format)
* @txt: MAC address as a string (e.g., "001122334455")
@@ -144,6 +184,30 @@ int hexstr2bin(const char *hex, u8 *buf, size_t len)
}
+int hwaddr_mask_txt(char *buf, size_t len, const u8 *addr, const u8 *mask)
+{
+ size_t i;
+ int print_mask = 0;
+ int res;
+
+ for (i = 0; i < ETH_ALEN; i++) {
+ if (mask[i] != 0xff) {
+ print_mask = 1;
+ break;
+ }
+ }
+
+ if (print_mask)
+ res = os_snprintf(buf, len, MACSTR "/" MACSTR,
+ MAC2STR(addr), MAC2STR(mask));
+ else
+ res = os_snprintf(buf, len, MACSTR, MAC2STR(addr));
+ if (os_snprintf_error(len, res))
+ return -1;
+ return res;
+}
+
+
/**
* inc_byte_array - Increment arbitrary length byte array by one
* @counter: Pointer to byte array
@@ -183,6 +247,35 @@ void wpa_get_ntp_timestamp(u8 *buf)
os_memcpy(buf + 4, (u8 *) &tmp, 4);
}
+/**
+ * wpa_scnprintf - Simpler-to-use snprintf function
+ * @buf: Output buffer
+ * @size: Buffer size
+ * @fmt: format
+ *
+ * Simpler snprintf version that doesn't require further error checks - the
+ * return value only indicates how many bytes were actually written, excluding
+ * the NULL byte (i.e., 0 on error, size-1 if buffer is not big enough).
+ */
+int wpa_scnprintf(char *buf, size_t size, const char *fmt, ...)
+{
+ va_list ap;
+ int ret;
+
+ if (!size)
+ return 0;
+
+ va_start(ap, fmt);
+ ret = vsnprintf(buf, size, fmt, ap);
+ va_end(ap);
+
+ if (ret < 0)
+ return 0;
+ if ((size_t) ret >= size)
+ return size - 1;
+
+ return ret;
+}
static inline int _wpa_snprintf_hex(char *buf, size_t buf_size, const u8 *data,
size_t len, int uppercase)
@@ -195,7 +288,7 @@ static inline int _wpa_snprintf_hex(char *buf, size_t buf_size, const u8 *data,
for (i = 0; i < len; i++) {
ret = os_snprintf(pos, end - pos, uppercase ? "%02X" : "%02x",
data[i]);
- if (ret < 0 || ret >= end - pos) {
+ if (os_snprintf_error(end - pos, ret)) {
end[-1] = '\0';
return pos - buf;
}
@@ -350,7 +443,7 @@ void printf_encode(char *txt, size_t maxlen, const u8 *data, size_t len)
size_t i;
for (i = 0; i < len; i++) {
- if (txt + 4 > end)
+ if (txt + 4 >= end)
break;
switch (data[i]) {
@@ -362,7 +455,7 @@ void printf_encode(char *txt, size_t maxlen, const u8 *data, size_t len)
*txt++ = '\\';
*txt++ = '\\';
break;
- case '\e':
+ case '\033':
*txt++ = '\\';
*txt++ = 'e';
break;
@@ -400,7 +493,7 @@ size_t printf_decode(u8 *buf, size_t maxlen, const char *str)
int val;
while (*pos) {
- if (len == maxlen)
+ if (len + 1 >= maxlen)
break;
switch (*pos) {
case '\\':
@@ -427,7 +520,7 @@ size_t printf_decode(u8 *buf, size_t maxlen, const char *str)
pos++;
break;
case 'e':
- buf[len++] = '\e';
+ buf[len++] = '\033';
pos++;
break;
case 'x':
@@ -468,6 +561,8 @@ size_t printf_decode(u8 *buf, size_t maxlen, const char *str)
break;
}
}
+ if (maxlen > len)
+ buf[len] = '\0';
return len;
}
@@ -517,11 +612,9 @@ char * wpa_config_parse_string(const char *value, size_t *len)
if (pos == NULL || pos[1] != '\0')
return NULL;
*len = pos - value;
- str = os_malloc(*len + 1);
+ str = dup_binstr(value, *len);
if (str == NULL)
return NULL;
- os_memcpy(str, value, *len);
- str[*len] = '\0';
return str;
} else if (*value == 'P' && value[1] == '"') {
const char *pos;
@@ -532,11 +625,9 @@ char * wpa_config_parse_string(const char *value, size_t *len)
if (pos == NULL || pos[1] != '\0')
return NULL;
tlen = pos - value;
- tstr = os_malloc(tlen + 1);
+ tstr = dup_binstr(value, tlen);
if (tstr == NULL)
return NULL;
- os_memcpy(tstr, value, tlen);
- tstr[tlen] = '\0';
str = os_malloc(tlen + 1);
if (str == NULL) {
@@ -610,3 +701,364 @@ size_t merge_byte_arrays(u8 *res, size_t res_len,
return len;
}
+
+
+char * dup_binstr(const void *src, size_t len)
+{
+ char *res;
+
+ if (src == NULL)
+ return NULL;
+ res = os_malloc(len + 1);
+ if (res == NULL)
+ return NULL;
+ os_memcpy(res, src, len);
+ res[len] = '\0';
+
+ return res;
+}
+
+
+int freq_range_list_parse(struct wpa_freq_range_list *res, const char *value)
+{
+ struct wpa_freq_range *freq = NULL, *n;
+ unsigned int count = 0;
+ const char *pos, *pos2, *pos3;
+
+ /*
+ * Comma separated list of frequency ranges.
+ * For example: 2412-2432,2462,5000-6000
+ */
+ pos = value;
+ while (pos && pos[0]) {
+ n = os_realloc_array(freq, count + 1,
+ sizeof(struct wpa_freq_range));
+ if (n == NULL) {
+ os_free(freq);
+ return -1;
+ }
+ freq = n;
+ freq[count].min = atoi(pos);
+ pos2 = os_strchr(pos, '-');
+ pos3 = os_strchr(pos, ',');
+ if (pos2 && (!pos3 || pos2 < pos3)) {
+ pos2++;
+ freq[count].max = atoi(pos2);
+ } else
+ freq[count].max = freq[count].min;
+ pos = pos3;
+ if (pos)
+ pos++;
+ count++;
+ }
+
+ os_free(res->range);
+ res->range = freq;
+ res->num = count;
+
+ return 0;
+}
+
+
+int freq_range_list_includes(const struct wpa_freq_range_list *list,
+ unsigned int freq)
+{
+ unsigned int i;
+
+ if (list == NULL)
+ return 0;
+
+ for (i = 0; i < list->num; i++) {
+ if (freq >= list->range[i].min && freq <= list->range[i].max)
+ return 1;
+ }
+
+ return 0;
+}
+
+
+char * freq_range_list_str(const struct wpa_freq_range_list *list)
+{
+ char *buf, *pos, *end;
+ size_t maxlen;
+ unsigned int i;
+ int res;
+
+ if (list->num == 0)
+ return NULL;
+
+ maxlen = list->num * 30;
+ buf = os_malloc(maxlen);
+ if (buf == NULL)
+ return NULL;
+ pos = buf;
+ end = buf + maxlen;
+
+ for (i = 0; i < list->num; i++) {
+ struct wpa_freq_range *range = &list->range[i];
+
+ if (range->min == range->max)
+ res = os_snprintf(pos, end - pos, "%s%u",
+ i == 0 ? "" : ",", range->min);
+ else
+ res = os_snprintf(pos, end - pos, "%s%u-%u",
+ i == 0 ? "" : ",",
+ range->min, range->max);
+ if (os_snprintf_error(end - pos, res)) {
+ os_free(buf);
+ return NULL;
+ }
+ pos += res;
+ }
+
+ return buf;
+}
+
+
+int int_array_len(const int *a)
+{
+ int i;
+ for (i = 0; a && a[i]; i++)
+ ;
+ return i;
+}
+
+
+void int_array_concat(int **res, const int *a)
+{
+ int reslen, alen, i;
+ int *n;
+
+ reslen = int_array_len(*res);
+ alen = int_array_len(a);
+
+ n = os_realloc_array(*res, reslen + alen + 1, sizeof(int));
+ if (n == NULL) {
+ os_free(*res);
+ *res = NULL;
+ return;
+ }
+ for (i = 0; i <= alen; i++)
+ n[reslen + i] = a[i];
+ *res = n;
+}
+
+
+static int freq_cmp(const void *a, const void *b)
+{
+ int _a = *(int *) a;
+ int _b = *(int *) b;
+
+ if (_a == 0)
+ return 1;
+ if (_b == 0)
+ return -1;
+ return _a - _b;
+}
+
+
+void int_array_sort_unique(int *a)
+{
+ int alen;
+ int i, j;
+
+ if (a == NULL)
+ return;
+
+ alen = int_array_len(a);
+ qsort(a, alen, sizeof(int), freq_cmp);
+
+ i = 0;
+ j = 1;
+ while (a[i] && a[j]) {
+ if (a[i] == a[j]) {
+ j++;
+ continue;
+ }
+ a[++i] = a[j++];
+ }
+ if (a[i])
+ i++;
+ a[i] = 0;
+}
+
+
+void int_array_add_unique(int **res, int a)
+{
+ int reslen;
+ int *n;
+
+ for (reslen = 0; *res && (*res)[reslen]; reslen++) {
+ if ((*res)[reslen] == a)
+ return; /* already in the list */
+ }
+
+ n = os_realloc_array(*res, reslen + 2, sizeof(int));
+ if (n == NULL) {
+ os_free(*res);
+ *res = NULL;
+ return;
+ }
+
+ n[reslen] = a;
+ n[reslen + 1] = 0;
+
+ *res = n;
+}
+
+
+void str_clear_free(char *str)
+{
+ if (str) {
+ size_t len = os_strlen(str);
+ os_memset(str, 0, len);
+ os_free(str);
+ }
+}
+
+
+void bin_clear_free(void *bin, size_t len)
+{
+ if (bin) {
+ os_memset(bin, 0, len);
+ os_free(bin);
+ }
+}
+
+
+int random_mac_addr(u8 *addr)
+{
+ if (os_get_random(addr, ETH_ALEN) < 0)
+ return -1;
+ addr[0] &= 0xfe; /* unicast */
+ addr[0] |= 0x02; /* locally administered */
+ return 0;
+}
+
+
+int random_mac_addr_keep_oui(u8 *addr)
+{
+ if (os_get_random(addr + 3, 3) < 0)
+ return -1;
+ addr[0] &= 0xfe; /* unicast */
+ addr[0] |= 0x02; /* locally administered */
+ return 0;
+}
+
+
+/**
+ * str_token - Get next token from a string
+ * @buf: String to tokenize. Note that the string might be modified.
+ * @delim: String of delimiters
+ * @context: Pointer to save our context. Should be initialized with
+ * NULL on the first call, and passed for any further call.
+ * Returns: The next token, NULL if there are no more valid tokens.
+ */
+char * str_token(char *str, const char *delim, char **context)
+{
+ char *end, *pos = str;
+
+ if (*context)
+ pos = *context;
+
+ while (*pos && os_strchr(delim, *pos))
+ pos++;
+ if (!*pos)
+ return NULL;
+
+ end = pos + 1;
+ while (*end && !os_strchr(delim, *end))
+ end++;
+
+ if (*end)
+ *end++ = '\0';
+
+ *context = end;
+ return pos;
+}
+
+
+size_t utf8_unescape(const char *inp, size_t in_size,
+ char *outp, size_t out_size)
+{
+ size_t res_size = 0;
+
+ if (!inp || !outp)
+ return 0;
+
+ if (!in_size)
+ in_size = os_strlen(inp);
+
+ /* Advance past leading single quote */
+ if (*inp == '\'' && in_size) {
+ inp++;
+ in_size--;
+ }
+
+ while (in_size--) {
+ if (res_size >= out_size)
+ return 0;
+
+ switch (*inp) {
+ case '\'':
+ /* Terminate on bare single quote */
+ *outp = '\0';
+ return res_size;
+
+ case '\\':
+ if (!in_size--)
+ return 0;
+ inp++;
+ /* fall through */
+
+ default:
+ *outp++ = *inp++;
+ res_size++;
+ }
+ }
+
+ /* NUL terminate if space allows */
+ if (res_size < out_size)
+ *outp = '\0';
+
+ return res_size;
+}
+
+
+size_t utf8_escape(const char *inp, size_t in_size,
+ char *outp, size_t out_size)
+{
+ size_t res_size = 0;
+
+ if (!inp || !outp)
+ return 0;
+
+ /* inp may or may not be NUL terminated, but must be if 0 size
+ * is specified */
+ if (!in_size)
+ in_size = os_strlen(inp);
+
+ while (in_size--) {
+ if (res_size++ >= out_size)
+ return 0;
+
+ switch (*inp) {
+ case '\\':
+ case '\'':
+ if (res_size++ >= out_size)
+ return 0;
+ *outp++ = '\\';
+ /* fall through */
+
+ default:
+ *outp++ = *inp++;
+ break;
+ }
+ }
+
+ /* NUL terminate if space allows */
+ if (res_size < out_size)
+ *outp = '\0';
+
+ return res_size;
+}
diff --git a/src/utils/common.h b/src/utils/common.h
index 5fc916c0ab934..576e8e7e2d4eb 100644
--- a/src/utils/common.h
+++ b/src/utils/common.h
@@ -164,6 +164,7 @@ static inline unsigned int wpa_swap_32(unsigned int v)
#define be_to_host16(n) wpa_swap_16(n)
#define host_to_be16(n) wpa_swap_16(n)
#define le_to_host32(n) (n)
+#define host_to_le32(n) (n)
#define be_to_host32(n) wpa_swap_32(n)
#define host_to_be32(n) wpa_swap_32(n)
@@ -205,6 +206,7 @@ static inline unsigned int wpa_swap_32(unsigned int v)
#define be_to_host16(n) (n)
#define host_to_be16(n) (n)
#define le_to_host32(n) bswap_32(n)
+#define host_to_le32(n) bswap_32(n)
#define be_to_host32(n) (n)
#define host_to_be32(n) (n)
#define le_to_host64(n) bswap_64(n)
@@ -224,74 +226,113 @@ static inline unsigned int wpa_swap_32(unsigned int v)
/* Macros for handling unaligned memory accesses */
-#define WPA_GET_BE16(a) ((u16) (((a)[0] << 8) | (a)[1]))
-#define WPA_PUT_BE16(a, val) \
- do { \
- (a)[0] = ((u16) (val)) >> 8; \
- (a)[1] = ((u16) (val)) & 0xff; \
- } while (0)
+static inline u16 WPA_GET_BE16(const u8 *a)
+{
+ return (a[0] << 8) | a[1];
+}
-#define WPA_GET_LE16(a) ((u16) (((a)[1] << 8) | (a)[0]))
-#define WPA_PUT_LE16(a, val) \
- do { \
- (a)[1] = ((u16) (val)) >> 8; \
- (a)[0] = ((u16) (val)) & 0xff; \
- } while (0)
+static inline void WPA_PUT_BE16(u8 *a, u16 val)
+{
+ a[0] = val >> 8;
+ a[1] = val & 0xff;
+}
+
+static inline u16 WPA_GET_LE16(const u8 *a)
+{
+ return (a[1] << 8) | a[0];
+}
+
+static inline void WPA_PUT_LE16(u8 *a, u16 val)
+{
+ a[1] = val >> 8;
+ a[0] = val & 0xff;
+}
+
+static inline u32 WPA_GET_BE24(const u8 *a)
+{
+ return (a[0] << 16) | (a[1] << 8) | a[2];
+}
+
+static inline void WPA_PUT_BE24(u8 *a, u32 val)
+{
+ a[0] = (val >> 16) & 0xff;
+ a[1] = (val >> 8) & 0xff;
+ a[2] = val & 0xff;
+}
+
+static inline u32 WPA_GET_BE32(const u8 *a)
+{
+ return (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3];
+}
+
+static inline void WPA_PUT_BE32(u8 *a, u32 val)
+{
+ a[0] = (val >> 24) & 0xff;
+ a[1] = (val >> 16) & 0xff;
+ a[2] = (val >> 8) & 0xff;
+ a[3] = val & 0xff;
+}
+
+static inline u32 WPA_GET_LE32(const u8 *a)
+{
+ return (a[3] << 24) | (a[2] << 16) | (a[1] << 8) | a[0];
+}
-#define WPA_GET_BE24(a) ((((u32) (a)[0]) << 16) | (((u32) (a)[1]) << 8) | \
- ((u32) (a)[2]))
-#define WPA_PUT_BE24(a, val) \
- do { \
- (a)[0] = (u8) ((((u32) (val)) >> 16) & 0xff); \
- (a)[1] = (u8) ((((u32) (val)) >> 8) & 0xff); \
- (a)[2] = (u8) (((u32) (val)) & 0xff); \
- } while (0)
+static inline void WPA_PUT_LE32(u8 *a, u32 val)
+{
+ a[3] = (val >> 24) & 0xff;
+ a[2] = (val >> 16) & 0xff;
+ a[1] = (val >> 8) & 0xff;
+ a[0] = val & 0xff;
+}
-#define WPA_GET_BE32(a) ((((u32) (a)[0]) << 24) | (((u32) (a)[1]) << 16) | \
- (((u32) (a)[2]) << 8) | ((u32) (a)[3]))
-#define WPA_PUT_BE32(a, val) \
- do { \
- (a)[0] = (u8) ((((u32) (val)) >> 24) & 0xff); \
- (a)[1] = (u8) ((((u32) (val)) >> 16) & 0xff); \
- (a)[2] = (u8) ((((u32) (val)) >> 8) & 0xff); \
- (a)[3] = (u8) (((u32) (val)) & 0xff); \
- } while (0)
+static inline u64 WPA_GET_BE64(const u8 *a)
+{
+ return (((u64) a[0]) << 56) | (((u64) a[1]) << 48) |
+ (((u64) a[2]) << 40) | (((u64) a[3]) << 32) |
+ (((u64) a[4]) << 24) | (((u64) a[5]) << 16) |
+ (((u64) a[6]) << 8) | ((u64) a[7]);
+}
-#define WPA_GET_LE32(a) ((((u32) (a)[3]) << 24) | (((u32) (a)[2]) << 16) | \
- (((u32) (a)[1]) << 8) | ((u32) (a)[0]))
-#define WPA_PUT_LE32(a, val) \
- do { \
- (a)[3] = (u8) ((((u32) (val)) >> 24) & 0xff); \
- (a)[2] = (u8) ((((u32) (val)) >> 16) & 0xff); \
- (a)[1] = (u8) ((((u32) (val)) >> 8) & 0xff); \
- (a)[0] = (u8) (((u32) (val)) & 0xff); \
- } while (0)
+static inline void WPA_PUT_BE64(u8 *a, u64 val)
+{
+ a[0] = val >> 56;
+ a[1] = val >> 48;
+ a[2] = val >> 40;
+ a[3] = val >> 32;
+ a[4] = val >> 24;
+ a[5] = val >> 16;
+ a[6] = val >> 8;
+ a[7] = val & 0xff;
+}
-#define WPA_GET_BE64(a) ((((u64) (a)[0]) << 56) | (((u64) (a)[1]) << 48) | \
- (((u64) (a)[2]) << 40) | (((u64) (a)[3]) << 32) | \
- (((u64) (a)[4]) << 24) | (((u64) (a)[5]) << 16) | \
- (((u64) (a)[6]) << 8) | ((u64) (a)[7]))
-#define WPA_PUT_BE64(a, val) \
- do { \
- (a)[0] = (u8) (((u64) (val)) >> 56); \
- (a)[1] = (u8) (((u64) (val)) >> 48); \
- (a)[2] = (u8) (((u64) (val)) >> 40); \
- (a)[3] = (u8) (((u64) (val)) >> 32); \
- (a)[4] = (u8) (((u64) (val)) >> 24); \
- (a)[5] = (u8) (((u64) (val)) >> 16); \
- (a)[6] = (u8) (((u64) (val)) >> 8); \
- (a)[7] = (u8) (((u64) (val)) & 0xff); \
- } while (0)
+static inline u64 WPA_GET_LE64(const u8 *a)
+{
+ return (((u64) a[7]) << 56) | (((u64) a[6]) << 48) |
+ (((u64) a[5]) << 40) | (((u64) a[4]) << 32) |
+ (((u64) a[3]) << 24) | (((u64) a[2]) << 16) |
+ (((u64) a[1]) << 8) | ((u64) a[0]);
+}
-#define WPA_GET_LE64(a) ((((u64) (a)[7]) << 56) | (((u64) (a)[6]) << 48) | \
- (((u64) (a)[5]) << 40) | (((u64) (a)[4]) << 32) | \
- (((u64) (a)[3]) << 24) | (((u64) (a)[2]) << 16) | \
- (((u64) (a)[1]) << 8) | ((u64) (a)[0]))
+static inline void WPA_PUT_LE64(u8 *a, u64 val)
+{
+ a[7] = val >> 56;
+ a[6] = val >> 48;
+ a[5] = val >> 40;
+ a[4] = val >> 32;
+ a[3] = val >> 24;
+ a[2] = val >> 16;
+ a[1] = val >> 8;
+ a[0] = val & 0xff;
+}
#ifndef ETH_ALEN
#define ETH_ALEN 6
#endif
+#ifndef ETH_HLEN
+#define ETH_HLEN 14
+#endif
#ifndef IFNAMSIZ
#define IFNAMSIZ 16
#endif
@@ -422,17 +463,29 @@ typedef u64 __bitwise le64;
#endif /* __GNUC__ */
#endif /* __must_check */
+#ifndef __maybe_unused
+#if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
+#define __maybe_unused __attribute__((unused))
+#else
+#define __maybe_unused
+#endif /* __GNUC__ */
+#endif /* __must_check */
+
int hwaddr_aton(const char *txt, u8 *addr);
+int hwaddr_masked_aton(const char *txt, u8 *addr, u8 *mask, u8 maskable);
int hwaddr_compact_aton(const char *txt, u8 *addr);
int hwaddr_aton2(const char *txt, u8 *addr);
int hex2byte(const char *hex);
int hexstr2bin(const char *hex, u8 *buf, size_t len);
void inc_byte_array(u8 *counter, size_t len);
void wpa_get_ntp_timestamp(u8 *buf);
+int wpa_scnprintf(char *buf, size_t size, const char *fmt, ...);
int wpa_snprintf_hex(char *buf, size_t buf_size, const u8 *data, size_t len);
int wpa_snprintf_hex_uppercase(char *buf, size_t buf_size, const u8 *data,
size_t len);
+int hwaddr_mask_txt(char *buf, size_t len, const u8 *addr, const u8 *mask);
+
#ifdef CONFIG_NATIVE_WINDOWS
void wpa_unicode2ascii_inplace(TCHAR *str);
TCHAR * wpa_strdup_tchar(const char *str);
@@ -451,6 +504,7 @@ int is_hex(const u8 *data, size_t len);
size_t merge_byte_arrays(u8 *res, size_t res_len,
const u8 *src1, size_t src1_len,
const u8 *src2, size_t src2_len);
+char * dup_binstr(const void *src, size_t len);
static inline int is_zero_ether_addr(const u8 *a)
{
@@ -467,6 +521,39 @@ static inline int is_broadcast_ether_addr(const u8 *a)
#include "wpa_debug.h"
+struct wpa_freq_range_list {
+ struct wpa_freq_range {
+ unsigned int min;
+ unsigned int max;
+ } *range;
+ unsigned int num;
+};
+
+int freq_range_list_parse(struct wpa_freq_range_list *res, const char *value);
+int freq_range_list_includes(const struct wpa_freq_range_list *list,
+ unsigned int freq);
+char * freq_range_list_str(const struct wpa_freq_range_list *list);
+
+int int_array_len(const int *a);
+void int_array_concat(int **res, const int *a);
+void int_array_sort_unique(int *a);
+void int_array_add_unique(int **res, int a);
+
+#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
+
+void str_clear_free(char *str);
+void bin_clear_free(void *bin, size_t len);
+
+int random_mac_addr(u8 *addr);
+int random_mac_addr_keep_oui(u8 *addr);
+
+char * str_token(char *str, const char *delim, char **context);
+size_t utf8_escape(const char *inp, size_t in_size,
+ char *outp, size_t out_size);
+size_t utf8_unescape(const char *inp, size_t in_size,
+ char *outp, size_t out_size);
+
+
/*
* gcc 4.4 ends up generating strict-aliasing warnings about some very common
* networking socket uses that do not really result in a real problem and
diff --git a/src/utils/edit.c b/src/utils/edit.c
index b01e08dfc2a92..d340bfadd1f13 100644
--- a/src/utils/edit.c
+++ b/src/utils/edit.c
@@ -14,7 +14,7 @@
#include "list.h"
#include "edit.h"
-#define CMD_BUF_LEN 256
+#define CMD_BUF_LEN 4096
static char cmdbuf[CMD_BUF_LEN];
static int cmdbuf_pos = 0;
static int cmdbuf_len = 0;
@@ -345,7 +345,7 @@ static void insert_char(int c)
static void process_cmd(void)
{
-
+ currbuf_valid = 0;
if (cmdbuf_len == 0) {
printf("\n%s> ", ps2 ? ps2 : "");
fflush(stdout);
diff --git a/src/utils/edit_readline.c b/src/utils/edit_readline.c
index add26fa33737a..c2a5bcaa17852 100644
--- a/src/utils/edit_readline.c
+++ b/src/utils/edit_readline.c
@@ -167,9 +167,9 @@ void edit_deinit(const char *history_file,
if (filter_cb && filter_cb(edit_cb_ctx, p)) {
h = remove_history(where_history());
if (h) {
- os_free(h->line);
+ free(h->line);
free(h->data);
- os_free(h);
+ free(h);
} else
next_history();
} else
diff --git a/src/utils/edit_simple.c b/src/utils/edit_simple.c
index a095ea6abec5a..13173cb19361a 100644
--- a/src/utils/edit_simple.c
+++ b/src/utils/edit_simple.c
@@ -13,7 +13,7 @@
#include "edit.h"
-#define CMD_BUF_LEN 256
+#define CMD_BUF_LEN 4096
static char cmdbuf[CMD_BUF_LEN];
static int cmdbuf_pos = 0;
static const char *ps2 = NULL;
diff --git a/src/utils/eloop.c b/src/utils/eloop.c
index d01ae64f8a628..4a565ebdbd0a9 100644
--- a/src/utils/eloop.c
+++ b/src/utils/eloop.c
@@ -7,17 +7,28 @@
*/
#include "includes.h"
+#include <assert.h>
#include "common.h"
#include "trace.h"
#include "list.h"
#include "eloop.h"
+#if defined(CONFIG_ELOOP_POLL) && defined(CONFIG_ELOOP_EPOLL)
+#error Do not define both of poll and epoll
+#endif
+
+#if !defined(CONFIG_ELOOP_POLL) && !defined(CONFIG_ELOOP_EPOLL)
+#define CONFIG_ELOOP_SELECT
+#endif
+
#ifdef CONFIG_ELOOP_POLL
-#include <assert.h>
#include <poll.h>
#endif /* CONFIG_ELOOP_POLL */
+#ifdef CONFIG_ELOOP_EPOLL
+#include <sys/epoll.h>
+#endif /* CONFIG_ELOOP_EPOLL */
struct eloop_sock {
int sock;
@@ -31,7 +42,7 @@ struct eloop_sock {
struct eloop_timeout {
struct dl_list list;
- struct os_time time;
+ struct os_reltime time;
void *eloop_data;
void *user_data;
eloop_timeout_handler handler;
@@ -50,7 +61,11 @@ struct eloop_signal {
struct eloop_sock_table {
int count;
struct eloop_sock *table;
+#ifdef CONFIG_ELOOP_EPOLL
+ eloop_event_type type;
+#else /* CONFIG_ELOOP_EPOLL */
int changed;
+#endif /* CONFIG_ELOOP_EPOLL */
};
struct eloop_data {
@@ -63,6 +78,13 @@ struct eloop_data {
struct pollfd *pollfds;
struct pollfd **pollfds_map;
#endif /* CONFIG_ELOOP_POLL */
+#ifdef CONFIG_ELOOP_EPOLL
+ int epollfd;
+ int epoll_max_event_num;
+ int epoll_max_fd;
+ struct eloop_sock *epoll_table;
+ struct epoll_event *epoll_events;
+#endif /* CONFIG_ELOOP_EPOLL */
struct eloop_sock_table readers;
struct eloop_sock_table writers;
struct eloop_sock_table exceptions;
@@ -75,7 +97,6 @@ struct eloop_data {
int pending_terminate;
int terminate;
- int reader_table_changed;
};
static struct eloop_data eloop;
@@ -128,6 +149,17 @@ int eloop_init(void)
{
os_memset(&eloop, 0, sizeof(eloop));
dl_list_init(&eloop.timeout);
+#ifdef CONFIG_ELOOP_EPOLL
+ eloop.epollfd = epoll_create1(0);
+ if (eloop.epollfd < 0) {
+ wpa_printf(MSG_ERROR, "%s: epoll_create1 failed. %s\n",
+ __func__, strerror(errno));
+ return -1;
+ }
+ eloop.readers.type = EVENT_TYPE_READ;
+ eloop.writers.type = EVENT_TYPE_WRITE;
+ eloop.exceptions.type = EVENT_TYPE_EXCEPTION;
+#endif /* CONFIG_ELOOP_EPOLL */
#ifdef WPA_TRACE
signal(SIGSEGV, eloop_sigsegv_handler);
#endif /* WPA_TRACE */
@@ -139,6 +171,11 @@ static int eloop_sock_table_add_sock(struct eloop_sock_table *table,
int sock, eloop_sock_handler handler,
void *eloop_data, void *user_data)
{
+#ifdef CONFIG_ELOOP_EPOLL
+ struct eloop_sock *temp_table;
+ struct epoll_event ev, *temp_events;
+ int next;
+#endif /* CONFIG_ELOOP_EPOLL */
struct eloop_sock *tmp;
int new_max_sock;
@@ -174,12 +211,41 @@ static int eloop_sock_table_add_sock(struct eloop_sock_table *table,
eloop.pollfds = n;
}
#endif /* CONFIG_ELOOP_POLL */
+#ifdef CONFIG_ELOOP_EPOLL
+ if (new_max_sock >= eloop.epoll_max_fd) {
+ next = eloop.epoll_max_fd == 0 ? 16 : eloop.epoll_max_fd * 2;
+ temp_table = os_realloc_array(eloop.epoll_table, next,
+ sizeof(struct eloop_sock));
+ if (temp_table == NULL)
+ return -1;
+
+ eloop.epoll_max_fd = next;
+ eloop.epoll_table = temp_table;
+ }
+
+ if (eloop.count + 1 > eloop.epoll_max_event_num) {
+ next = eloop.epoll_max_event_num == 0 ? 8 :
+ eloop.epoll_max_event_num * 2;
+ temp_events = os_realloc_array(eloop.epoll_events, next,
+ sizeof(struct epoll_event));
+ if (temp_events == NULL) {
+ wpa_printf(MSG_ERROR, "%s: malloc for epoll failed. "
+ "%s\n", __func__, strerror(errno));
+ return -1;
+ }
+
+ eloop.epoll_max_event_num = next;
+ eloop.epoll_events = temp_events;
+ }
+#endif /* CONFIG_ELOOP_EPOLL */
eloop_trace_sock_remove_ref(table);
tmp = os_realloc_array(table->table, table->count + 1,
sizeof(struct eloop_sock));
- if (tmp == NULL)
+ if (tmp == NULL) {
+ eloop_trace_sock_add_ref(table);
return -1;
+ }
tmp[table->count].sock = sock;
tmp[table->count].eloop_data = eloop_data;
@@ -190,9 +256,38 @@ static int eloop_sock_table_add_sock(struct eloop_sock_table *table,
table->table = tmp;
eloop.max_sock = new_max_sock;
eloop.count++;
+#ifndef CONFIG_ELOOP_EPOLL
table->changed = 1;
+#endif /* CONFIG_ELOOP_EPOLL */
eloop_trace_sock_add_ref(table);
+#ifdef CONFIG_ELOOP_EPOLL
+ os_memset(&ev, 0, sizeof(ev));
+ switch (table->type) {
+ case EVENT_TYPE_READ:
+ ev.events = EPOLLIN;
+ break;
+ case EVENT_TYPE_WRITE:
+ ev.events = EPOLLOUT;
+ break;
+ /*
+ * Exceptions are always checked when using epoll, but I suppose it's
+ * possible that someone registered a socket *only* for exception
+ * handling.
+ */
+ case EVENT_TYPE_EXCEPTION:
+ ev.events = EPOLLERR | EPOLLHUP;
+ break;
+ }
+ ev.data.fd = sock;
+ if (epoll_ctl(eloop.epollfd, EPOLL_CTL_ADD, sock, &ev) < 0) {
+ wpa_printf(MSG_ERROR, "%s: epoll_ctl(ADD) for fd=%d "
+ "failed. %s\n", __func__, sock, strerror(errno));
+ return -1;
+ }
+ os_memcpy(&eloop.epoll_table[sock], &table->table[table->count - 1],
+ sizeof(struct eloop_sock));
+#endif /* CONFIG_ELOOP_EPOLL */
return 0;
}
@@ -219,8 +314,18 @@ static void eloop_sock_table_remove_sock(struct eloop_sock_table *table,
}
table->count--;
eloop.count--;
+#ifndef CONFIG_ELOOP_EPOLL
table->changed = 1;
+#endif /* CONFIG_ELOOP_EPOLL */
eloop_trace_sock_add_ref(table);
+#ifdef CONFIG_ELOOP_EPOLL
+ if (epoll_ctl(eloop.epollfd, EPOLL_CTL_DEL, sock, NULL) < 0) {
+ wpa_printf(MSG_ERROR, "%s: epoll_ctl(DEL) for fd=%d "
+ "failed. %s\n", __func__, sock, strerror(errno));
+ return;
+ }
+ os_memset(&eloop.epoll_table[sock], 0, sizeof(struct eloop_sock));
+#endif /* CONFIG_ELOOP_EPOLL */
}
@@ -362,7 +467,9 @@ static void eloop_sock_table_dispatch(struct eloop_sock_table *readers,
max_pollfd_map, POLLERR | POLLHUP);
}
-#else /* CONFIG_ELOOP_POLL */
+#endif /* CONFIG_ELOOP_POLL */
+
+#ifdef CONFIG_ELOOP_SELECT
static void eloop_sock_table_set_fds(struct eloop_sock_table *table,
fd_set *fds)
@@ -374,8 +481,10 @@ static void eloop_sock_table_set_fds(struct eloop_sock_table *table,
if (table->table == NULL)
return;
- for (i = 0; i < table->count; i++)
+ for (i = 0; i < table->count; i++) {
+ assert(table->table[i].sock >= 0);
FD_SET(table->table[i].sock, fds);
+ }
}
@@ -399,7 +508,24 @@ static void eloop_sock_table_dispatch(struct eloop_sock_table *table,
}
}
-#endif /* CONFIG_ELOOP_POLL */
+#endif /* CONFIG_ELOOP_SELECT */
+
+
+#ifdef CONFIG_ELOOP_EPOLL
+static void eloop_sock_table_dispatch(struct epoll_event *events, int nfds)
+{
+ struct eloop_sock *table;
+ int i;
+
+ for (i = 0; i < nfds; i++) {
+ table = &eloop.epoll_table[events[i].data.fd];
+ if (table->handler == NULL)
+ continue;
+ table->handler(table->sock, table->eloop_data,
+ table->user_data);
+ }
+}
+#endif /* CONFIG_ELOOP_EPOLL */
static void eloop_sock_table_destroy(struct eloop_sock_table *table)
@@ -459,6 +585,7 @@ int eloop_register_sock(int sock, eloop_event_type type,
{
struct eloop_sock_table *table;
+ assert(sock >= 0);
table = eloop_get_sock_table(type);
return eloop_sock_table_add_sock(table, sock, handler,
eloop_data, user_data);
@@ -484,7 +611,7 @@ int eloop_register_timeout(unsigned int secs, unsigned int usecs,
timeout = os_zalloc(sizeof(*timeout));
if (timeout == NULL)
return -1;
- if (os_get_time(&timeout->time) < 0) {
+ if (os_get_reltime(&timeout->time) < 0) {
os_free(timeout);
return -1;
}
@@ -514,7 +641,7 @@ int eloop_register_timeout(unsigned int secs, unsigned int usecs,
/* Maintain timeouts in order of increasing time */
dl_list_for_each(tmp, &eloop.timeout, struct eloop_timeout, list) {
- if (os_time_before(&timeout->time, &tmp->time)) {
+ if (os_reltime_before(&timeout->time, &tmp->time)) {
dl_list_add(tmp->list.prev, &timeout->list);
return 0;
}
@@ -556,6 +683,33 @@ int eloop_cancel_timeout(eloop_timeout_handler handler,
}
+int eloop_cancel_timeout_one(eloop_timeout_handler handler,
+ void *eloop_data, void *user_data,
+ struct os_reltime *remaining)
+{
+ struct eloop_timeout *timeout, *prev;
+ int removed = 0;
+ struct os_reltime now;
+
+ os_get_reltime(&now);
+ remaining->sec = remaining->usec = 0;
+
+ dl_list_for_each_safe(timeout, prev, &eloop.timeout,
+ struct eloop_timeout, list) {
+ if (timeout->handler == handler &&
+ (timeout->eloop_data == eloop_data) &&
+ (timeout->user_data == user_data)) {
+ removed = 1;
+ if (os_reltime_before(&now, &timeout->time))
+ os_reltime_sub(&timeout->time, &now, remaining);
+ eloop_remove_timeout(timeout);
+ break;
+ }
+ }
+ return removed;
+}
+
+
int eloop_is_timeout_registered(eloop_timeout_handler handler,
void *eloop_data, void *user_data)
{
@@ -572,6 +726,70 @@ int eloop_is_timeout_registered(eloop_timeout_handler handler,
}
+int eloop_deplete_timeout(unsigned int req_secs, unsigned int req_usecs,
+ eloop_timeout_handler handler, void *eloop_data,
+ void *user_data)
+{
+ struct os_reltime now, requested, remaining;
+ struct eloop_timeout *tmp;
+
+ dl_list_for_each(tmp, &eloop.timeout, struct eloop_timeout, list) {
+ if (tmp->handler == handler &&
+ tmp->eloop_data == eloop_data &&
+ tmp->user_data == user_data) {
+ requested.sec = req_secs;
+ requested.usec = req_usecs;
+ os_get_reltime(&now);
+ os_reltime_sub(&tmp->time, &now, &remaining);
+ if (os_reltime_before(&requested, &remaining)) {
+ eloop_cancel_timeout(handler, eloop_data,
+ user_data);
+ eloop_register_timeout(requested.sec,
+ requested.usec,
+ handler, eloop_data,
+ user_data);
+ return 1;
+ }
+ return 0;
+ }
+ }
+
+ return -1;
+}
+
+
+int eloop_replenish_timeout(unsigned int req_secs, unsigned int req_usecs,
+ eloop_timeout_handler handler, void *eloop_data,
+ void *user_data)
+{
+ struct os_reltime now, requested, remaining;
+ struct eloop_timeout *tmp;
+
+ dl_list_for_each(tmp, &eloop.timeout, struct eloop_timeout, list) {
+ if (tmp->handler == handler &&
+ tmp->eloop_data == eloop_data &&
+ tmp->user_data == user_data) {
+ requested.sec = req_secs;
+ requested.usec = req_usecs;
+ os_get_reltime(&now);
+ os_reltime_sub(&tmp->time, &now, &remaining);
+ if (os_reltime_before(&remaining, &requested)) {
+ eloop_cancel_timeout(handler, eloop_data,
+ user_data);
+ eloop_register_timeout(requested.sec,
+ requested.usec,
+ handler, eloop_data,
+ user_data);
+ return 1;
+ }
+ return 0;
+ }
+ }
+
+ return -1;
+}
+
+
#ifndef CONFIG_NATIVE_WINDOWS
static void eloop_handle_alarm(int sig)
{
@@ -682,20 +900,24 @@ void eloop_run(void)
#ifdef CONFIG_ELOOP_POLL
int num_poll_fds;
int timeout_ms = 0;
-#else /* CONFIG_ELOOP_POLL */
+#endif /* CONFIG_ELOOP_POLL */
+#ifdef CONFIG_ELOOP_SELECT
fd_set *rfds, *wfds, *efds;
struct timeval _tv;
-#endif /* CONFIG_ELOOP_POLL */
+#endif /* CONFIG_ELOOP_SELECT */
+#ifdef CONFIG_ELOOP_EPOLL
+ int timeout_ms = -1;
+#endif /* CONFIG_ELOOP_EPOLL */
int res;
- struct os_time tv, now;
+ struct os_reltime tv, now;
-#ifndef CONFIG_ELOOP_POLL
+#ifdef CONFIG_ELOOP_SELECT
rfds = os_malloc(sizeof(*rfds));
wfds = os_malloc(sizeof(*wfds));
efds = os_malloc(sizeof(*efds));
if (rfds == NULL || wfds == NULL || efds == NULL)
goto out;
-#endif /* CONFIG_ELOOP_POLL */
+#endif /* CONFIG_ELOOP_SELECT */
while (!eloop.terminate &&
(!dl_list_empty(&eloop.timeout) || eloop.readers.count > 0 ||
@@ -704,17 +926,18 @@ void eloop_run(void)
timeout = dl_list_first(&eloop.timeout, struct eloop_timeout,
list);
if (timeout) {
- os_get_time(&now);
- if (os_time_before(&now, &timeout->time))
- os_time_sub(&timeout->time, &now, &tv);
+ os_get_reltime(&now);
+ if (os_reltime_before(&now, &timeout->time))
+ os_reltime_sub(&timeout->time, &now, &tv);
else
tv.sec = tv.usec = 0;
-#ifdef CONFIG_ELOOP_POLL
+#if defined(CONFIG_ELOOP_POLL) || defined(CONFIG_ELOOP_EPOLL)
timeout_ms = tv.sec * 1000 + tv.usec / 1000;
-#else /* CONFIG_ELOOP_POLL */
+#endif /* defined(CONFIG_ELOOP_POLL) || defined(CONFIG_ELOOP_EPOLL) */
+#ifdef CONFIG_ELOOP_SELECT
_tv.tv_sec = tv.sec;
_tv.tv_usec = tv.usec;
-#endif /* CONFIG_ELOOP_POLL */
+#endif /* CONFIG_ELOOP_SELECT */
}
#ifdef CONFIG_ELOOP_POLL
@@ -724,30 +947,44 @@ void eloop_run(void)
eloop.max_pollfd_map);
res = poll(eloop.pollfds, num_poll_fds,
timeout ? timeout_ms : -1);
-
- if (res < 0 && errno != EINTR && errno != 0) {
- perror("poll");
- goto out;
- }
-#else /* CONFIG_ELOOP_POLL */
+#endif /* CONFIG_ELOOP_POLL */
+#ifdef CONFIG_ELOOP_SELECT
eloop_sock_table_set_fds(&eloop.readers, rfds);
eloop_sock_table_set_fds(&eloop.writers, wfds);
eloop_sock_table_set_fds(&eloop.exceptions, efds);
res = select(eloop.max_sock + 1, rfds, wfds, efds,
timeout ? &_tv : NULL);
+#endif /* CONFIG_ELOOP_SELECT */
+#ifdef CONFIG_ELOOP_EPOLL
+ if (eloop.count == 0) {
+ res = 0;
+ } else {
+ res = epoll_wait(eloop.epollfd, eloop.epoll_events,
+ eloop.count, timeout_ms);
+ }
+#endif /* CONFIG_ELOOP_EPOLL */
if (res < 0 && errno != EINTR && errno != 0) {
- perror("select");
+ wpa_printf(MSG_ERROR, "eloop: %s: %s",
+#ifdef CONFIG_ELOOP_POLL
+ "poll"
+#endif /* CONFIG_ELOOP_POLL */
+#ifdef CONFIG_ELOOP_SELECT
+ "select"
+#endif /* CONFIG_ELOOP_SELECT */
+#ifdef CONFIG_ELOOP_EPOLL
+ "epoll"
+#endif /* CONFIG_ELOOP_EPOLL */
+ , strerror(errno));
goto out;
}
-#endif /* CONFIG_ELOOP_POLL */
eloop_process_pending_signals();
/* check if some registered timeouts have occurred */
timeout = dl_list_first(&eloop.timeout, struct eloop_timeout,
list);
if (timeout) {
- os_get_time(&now);
- if (!os_time_before(&now, &timeout->time)) {
+ os_get_reltime(&now);
+ if (!os_reltime_before(&now, &timeout->time)) {
void *eloop_data = timeout->eloop_data;
void *user_data = timeout->user_data;
eloop_timeout_handler handler =
@@ -765,19 +1002,24 @@ void eloop_run(void)
eloop_sock_table_dispatch(&eloop.readers, &eloop.writers,
&eloop.exceptions, eloop.pollfds_map,
eloop.max_pollfd_map);
-#else /* CONFIG_ELOOP_POLL */
+#endif /* CONFIG_ELOOP_POLL */
+#ifdef CONFIG_ELOOP_SELECT
eloop_sock_table_dispatch(&eloop.readers, rfds);
eloop_sock_table_dispatch(&eloop.writers, wfds);
eloop_sock_table_dispatch(&eloop.exceptions, efds);
-#endif /* CONFIG_ELOOP_POLL */
+#endif /* CONFIG_ELOOP_SELECT */
+#ifdef CONFIG_ELOOP_EPOLL
+ eloop_sock_table_dispatch(eloop.epoll_events, res);
+#endif /* CONFIG_ELOOP_EPOLL */
}
+ eloop.terminate = 0;
out:
-#ifndef CONFIG_ELOOP_POLL
+#ifdef CONFIG_ELOOP_SELECT
os_free(rfds);
os_free(wfds);
os_free(efds);
-#endif /* CONFIG_ELOOP_POLL */
+#endif /* CONFIG_ELOOP_SELECT */
return;
}
@@ -791,9 +1033,9 @@ void eloop_terminate(void)
void eloop_destroy(void)
{
struct eloop_timeout *timeout, *prev;
- struct os_time now;
+ struct os_reltime now;
- os_get_time(&now);
+ os_get_reltime(&now);
dl_list_for_each_safe(timeout, prev, &eloop.timeout,
struct eloop_timeout, list) {
int sec, usec;
@@ -821,6 +1063,11 @@ void eloop_destroy(void)
os_free(eloop.pollfds);
os_free(eloop.pollfds_map);
#endif /* CONFIG_ELOOP_POLL */
+#ifdef CONFIG_ELOOP_EPOLL
+ os_free(eloop.epoll_table);
+ os_free(eloop.epoll_events);
+ close(eloop.epollfd);
+#endif /* CONFIG_ELOOP_EPOLL */
}
@@ -843,7 +1090,13 @@ void eloop_wait_for_read_sock(int sock)
pfd.events = POLLIN;
poll(&pfd, 1, -1);
-#else /* CONFIG_ELOOP_POLL */
+#endif /* CONFIG_ELOOP_POLL */
+#if defined(CONFIG_ELOOP_SELECT) || defined(CONFIG_ELOOP_EPOLL)
+ /*
+ * We can use epoll() here. But epoll() requres 4 system calls.
+ * epoll_create1(), epoll_ctl() for ADD, epoll_wait, and close() for
+ * epoll fd. So select() is better for performance here.
+ */
fd_set rfds;
if (sock < 0)
@@ -852,5 +1105,9 @@ void eloop_wait_for_read_sock(int sock)
FD_ZERO(&rfds);
FD_SET(sock, &rfds);
select(sock + 1, &rfds, NULL, NULL, NULL);
-#endif /* CONFIG_ELOOP_POLL */
+#endif /* defined(CONFIG_ELOOP_SELECT) || defined(CONFIG_ELOOP_EPOLL) */
}
+
+#ifdef CONFIG_ELOOP_SELECT
+#undef CONFIG_ELOOP_SELECT
+#endif /* CONFIG_ELOOP_SELECT */
diff --git a/src/utils/eloop.h b/src/utils/eloop.h
index db03a735596f8..07b8c0dc33520 100644
--- a/src/utils/eloop.h
+++ b/src/utils/eloop.h
@@ -195,6 +195,21 @@ int eloop_cancel_timeout(eloop_timeout_handler handler,
void *eloop_data, void *user_data);
/**
+ * eloop_cancel_timeout_one - Cancel a single timeout
+ * @handler: Matching callback function
+ * @eloop_data: Matching eloop_data
+ * @user_data: Matching user_data
+ * @remaining: Time left on the cancelled timer
+ * Returns: Number of cancelled timeouts
+ *
+ * Cancel matching <handler,eloop_data,user_data> timeout registered with
+ * eloop_register_timeout() and return the remaining time left.
+ */
+int eloop_cancel_timeout_one(eloop_timeout_handler handler,
+ void *eloop_data, void *user_data,
+ struct os_reltime *remaining);
+
+/**
* eloop_is_timeout_registered - Check if a timeout is already registered
* @handler: Matching callback function
* @eloop_data: Matching eloop_data
@@ -208,6 +223,40 @@ int eloop_is_timeout_registered(eloop_timeout_handler handler,
void *eloop_data, void *user_data);
/**
+ * eloop_deplete_timeout - Deplete a timeout that is already registered
+ * @req_secs: Requested number of seconds to the timeout
+ * @req_usecs: Requested number of microseconds to the timeout
+ * @handler: Matching callback function
+ * @eloop_data: Matching eloop_data
+ * @user_data: Matching user_data
+ * Returns: 1 if the timeout is depleted, 0 if no change is made, -1 if no
+ * timeout matched
+ *
+ * Find a registered matching <handler,eloop_data,user_data> timeout. If found,
+ * deplete the timeout if remaining time is more than the requested time.
+ */
+int eloop_deplete_timeout(unsigned int req_secs, unsigned int req_usecs,
+ eloop_timeout_handler handler, void *eloop_data,
+ void *user_data);
+
+/**
+ * eloop_replenish_timeout - Replenish a timeout that is already registered
+ * @req_secs: Requested number of seconds to the timeout
+ * @req_usecs: Requested number of microseconds to the timeout
+ * @handler: Matching callback function
+ * @eloop_data: Matching eloop_data
+ * @user_data: Matching user_data
+ * Returns: 1 if the timeout is replenished, 0 if no change is made, -1 if no
+ * timeout matched
+ *
+ * Find a registered matching <handler,eloop_data,user_data> timeout. If found,
+ * replenish the timeout if remaining time is less than the requested time.
+ */
+int eloop_replenish_timeout(unsigned int req_secs, unsigned int req_usecs,
+ eloop_timeout_handler handler, void *eloop_data,
+ void *user_data);
+
+/**
* eloop_register_signal - Register handler for signals
* @sig: Signal number (e.g., SIGHUP)
* @handler: Callback function to be called when the signal is received
diff --git a/src/utils/eloop_none.c b/src/utils/eloop_none.c
deleted file mode 100644
index c67ece4d715ee..0000000000000
--- a/src/utils/eloop_none.c
+++ /dev/null
@@ -1,395 +0,0 @@
-/*
- * Event loop - empty template (basic structure, but no OS specific operations)
- * Copyright (c) 2002-2005, Jouni Malinen <j@w1.fi>
- *
- * This software may be distributed under the terms of the BSD license.
- * See README for more details.
- */
-
-#include "includes.h"
-
-#include "common.h"
-#include "eloop.h"
-
-
-struct eloop_sock {
- int sock;
- void *eloop_data;
- void *user_data;
- void (*handler)(int sock, void *eloop_ctx, void *sock_ctx);
-};
-
-struct eloop_timeout {
- struct os_time time;
- void *eloop_data;
- void *user_data;
- void (*handler)(void *eloop_ctx, void *sock_ctx);
- struct eloop_timeout *next;
-};
-
-struct eloop_signal {
- int sig;
- void *user_data;
- void (*handler)(int sig, void *eloop_ctx, void *signal_ctx);
- int signaled;
-};
-
-struct eloop_data {
- int max_sock, reader_count;
- struct eloop_sock *readers;
-
- struct eloop_timeout *timeout;
-
- int signal_count;
- struct eloop_signal *signals;
- int signaled;
- int pending_terminate;
-
- int terminate;
- int reader_table_changed;
-};
-
-static struct eloop_data eloop;
-
-
-int eloop_init(void)
-{
- memset(&eloop, 0, sizeof(eloop));
- return 0;
-}
-
-
-int eloop_register_read_sock(int sock,
- void (*handler)(int sock, void *eloop_ctx,
- void *sock_ctx),
- void *eloop_data, void *user_data)
-{
- struct eloop_sock *tmp;
-
- tmp = (struct eloop_sock *)
- realloc(eloop.readers,
- (eloop.reader_count + 1) * sizeof(struct eloop_sock));
- if (tmp == NULL)
- return -1;
-
- tmp[eloop.reader_count].sock = sock;
- tmp[eloop.reader_count].eloop_data = eloop_data;
- tmp[eloop.reader_count].user_data = user_data;
- tmp[eloop.reader_count].handler = handler;
- eloop.reader_count++;
- eloop.readers = tmp;
- if (sock > eloop.max_sock)
- eloop.max_sock = sock;
- eloop.reader_table_changed = 1;
-
- return 0;
-}
-
-
-void eloop_unregister_read_sock(int sock)
-{
- int i;
-
- if (eloop.readers == NULL || eloop.reader_count == 0)
- return;
-
- for (i = 0; i < eloop.reader_count; i++) {
- if (eloop.readers[i].sock == sock)
- break;
- }
- if (i == eloop.reader_count)
- return;
- if (i != eloop.reader_count - 1) {
- memmove(&eloop.readers[i], &eloop.readers[i + 1],
- (eloop.reader_count - i - 1) *
- sizeof(struct eloop_sock));
- }
- eloop.reader_count--;
- eloop.reader_table_changed = 1;
-}
-
-
-int eloop_register_timeout(unsigned int secs, unsigned int usecs,
- void (*handler)(void *eloop_ctx, void *timeout_ctx),
- void *eloop_data, void *user_data)
-{
- struct eloop_timeout *timeout, *tmp, *prev;
-
- timeout = (struct eloop_timeout *) malloc(sizeof(*timeout));
- if (timeout == NULL)
- return -1;
- os_get_time(&timeout->time);
- timeout->time.sec += secs;
- timeout->time.usec += usecs;
- while (timeout->time.usec >= 1000000) {
- timeout->time.sec++;
- timeout->time.usec -= 1000000;
- }
- timeout->eloop_data = eloop_data;
- timeout->user_data = user_data;
- timeout->handler = handler;
- timeout->next = NULL;
-
- if (eloop.timeout == NULL) {
- eloop.timeout = timeout;
- return 0;
- }
-
- prev = NULL;
- tmp = eloop.timeout;
- while (tmp != NULL) {
- if (os_time_before(&timeout->time, &tmp->time))
- break;
- prev = tmp;
- tmp = tmp->next;
- }
-
- if (prev == NULL) {
- timeout->next = eloop.timeout;
- eloop.timeout = timeout;
- } else {
- timeout->next = prev->next;
- prev->next = timeout;
- }
-
- return 0;
-}
-
-
-int eloop_cancel_timeout(void (*handler)(void *eloop_ctx, void *sock_ctx),
- void *eloop_data, void *user_data)
-{
- struct eloop_timeout *timeout, *prev, *next;
- int removed = 0;
-
- prev = NULL;
- timeout = eloop.timeout;
- while (timeout != NULL) {
- next = timeout->next;
-
- if (timeout->handler == handler &&
- (timeout->eloop_data == eloop_data ||
- eloop_data == ELOOP_ALL_CTX) &&
- (timeout->user_data == user_data ||
- user_data == ELOOP_ALL_CTX)) {
- if (prev == NULL)
- eloop.timeout = next;
- else
- prev->next = next;
- free(timeout);
- removed++;
- } else
- prev = timeout;
-
- timeout = next;
- }
-
- return removed;
-}
-
-
-int eloop_is_timeout_registered(void (*handler)(void *eloop_ctx,
- void *timeout_ctx),
- void *eloop_data, void *user_data)
-{
- struct eloop_timeout *tmp;
-
- tmp = eloop.timeout;
- while (tmp != NULL) {
- if (tmp->handler == handler &&
- tmp->eloop_data == eloop_data &&
- tmp->user_data == user_data)
- return 1;
-
- tmp = tmp->next;
- }
-
- return 0;
-}
-
-
-/* TODO: replace with suitable signal handler */
-#if 0
-static void eloop_handle_signal(int sig)
-{
- int i;
-
- eloop.signaled++;
- for (i = 0; i < eloop.signal_count; i++) {
- if (eloop.signals[i].sig == sig) {
- eloop.signals[i].signaled++;
- break;
- }
- }
-}
-#endif
-
-
-static void eloop_process_pending_signals(void)
-{
- int i;
-
- if (eloop.signaled == 0)
- return;
- eloop.signaled = 0;
-
- if (eloop.pending_terminate) {
- eloop.pending_terminate = 0;
- }
-
- for (i = 0; i < eloop.signal_count; i++) {
- if (eloop.signals[i].signaled) {
- eloop.signals[i].signaled = 0;
- eloop.signals[i].handler(eloop.signals[i].sig,
- eloop.user_data,
- eloop.signals[i].user_data);
- }
- }
-}
-
-
-int eloop_register_signal(int sig,
- void (*handler)(int sig, void *eloop_ctx,
- void *signal_ctx),
- void *user_data)
-{
- struct eloop_signal *tmp;
-
- tmp = (struct eloop_signal *)
- realloc(eloop.signals,
- (eloop.signal_count + 1) *
- sizeof(struct eloop_signal));
- if (tmp == NULL)
- return -1;
-
- tmp[eloop.signal_count].sig = sig;
- tmp[eloop.signal_count].user_data = user_data;
- tmp[eloop.signal_count].handler = handler;
- tmp[eloop.signal_count].signaled = 0;
- eloop.signal_count++;
- eloop.signals = tmp;
-
- /* TODO: register signal handler */
-
- return 0;
-}
-
-
-int eloop_register_signal_terminate(void (*handler)(int sig, void *eloop_ctx,
- void *signal_ctx),
- void *user_data)
-{
-#if 0
- /* TODO: for example */
- int ret = eloop_register_signal(SIGINT, handler, user_data);
- if (ret == 0)
- ret = eloop_register_signal(SIGTERM, handler, user_data);
- return ret;
-#endif
- return 0;
-}
-
-
-int eloop_register_signal_reconfig(void (*handler)(int sig, void *eloop_ctx,
- void *signal_ctx),
- void *user_data)
-{
-#if 0
- /* TODO: for example */
- return eloop_register_signal(SIGHUP, handler, user_data);
-#endif
- return 0;
-}
-
-
-void eloop_run(void)
-{
- int i;
- struct os_time tv, now;
-
- while (!eloop.terminate &&
- (eloop.timeout || eloop.reader_count > 0)) {
- if (eloop.timeout) {
- os_get_time(&now);
- if (os_time_before(&now, &eloop.timeout->time))
- os_time_sub(&eloop.timeout->time, &now, &tv);
- else
- tv.sec = tv.usec = 0;
- }
-
- /*
- * TODO: wait for any event (read socket ready, timeout (tv),
- * signal
- */
- os_sleep(1, 0); /* just a dummy wait for testing */
-
- eloop_process_pending_signals();
-
- /* check if some registered timeouts have occurred */
- if (eloop.timeout) {
- struct eloop_timeout *tmp;
-
- os_get_time(&now);
- if (!os_time_before(&now, &eloop.timeout->time)) {
- tmp = eloop.timeout;
- eloop.timeout = eloop.timeout->next;
- tmp->handler(tmp->eloop_data,
- tmp->user_data);
- free(tmp);
- }
-
- }
-
- eloop.reader_table_changed = 0;
- for (i = 0; i < eloop.reader_count; i++) {
- /*
- * TODO: call each handler that has pending data to
- * read
- */
- if (0 /* TODO: eloop.readers[i].sock ready */) {
- eloop.readers[i].handler(
- eloop.readers[i].sock,
- eloop.readers[i].eloop_data,
- eloop.readers[i].user_data);
- if (eloop.reader_table_changed)
- break;
- }
- }
- }
-}
-
-
-void eloop_terminate(void)
-{
- eloop.terminate = 1;
-}
-
-
-void eloop_destroy(void)
-{
- struct eloop_timeout *timeout, *prev;
-
- timeout = eloop.timeout;
- while (timeout != NULL) {
- prev = timeout;
- timeout = timeout->next;
- free(prev);
- }
- free(eloop.readers);
- free(eloop.signals);
-}
-
-
-int eloop_terminated(void)
-{
- return eloop.terminate;
-}
-
-
-void eloop_wait_for_read_sock(int sock)
-{
- /*
- * TODO: wait for the file descriptor to have something available for
- * reading
- */
-}
diff --git a/src/utils/eloop_win.c b/src/utils/eloop_win.c
index 1fafeb2d98146..de47fb21837c2 100644
--- a/src/utils/eloop_win.c
+++ b/src/utils/eloop_win.c
@@ -1,6 +1,6 @@
/*
* Event loop based on Windows events and WaitForMultipleObjects
- * Copyright (c) 2002-2006, Jouni Malinen <j@w1.fi>
+ * Copyright (c) 2002-2009, Jouni Malinen <j@w1.fi>
*
* This software may be distributed under the terms of the BSD license.
* See README for more details.
@@ -10,6 +10,7 @@
#include <winsock2.h>
#include "common.h"
+#include "list.h"
#include "eloop.h"
@@ -29,11 +30,11 @@ struct eloop_event {
};
struct eloop_timeout {
- struct os_time time;
+ struct dl_list list;
+ struct os_reltime time;
void *eloop_data;
void *user_data;
eloop_timeout_handler handler;
- struct eloop_timeout *next;
};
struct eloop_signal {
@@ -51,7 +52,7 @@ struct eloop_data {
size_t event_count;
struct eloop_event *events;
- struct eloop_timeout *timeout;
+ struct dl_list timeout;
int signal_count;
struct eloop_signal *signals;
@@ -74,6 +75,7 @@ static struct eloop_data eloop;
int eloop_init(void)
{
os_memset(&eloop, 0, sizeof(eloop));
+ dl_list_init(&eloop.timeout);
eloop.num_handles = 1;
eloop.handles = os_malloc(eloop.num_handles *
sizeof(eloop.handles[0]));
@@ -236,13 +238,16 @@ int eloop_register_timeout(unsigned int secs, unsigned int usecs,
eloop_timeout_handler handler,
void *eloop_data, void *user_data)
{
- struct eloop_timeout *timeout, *tmp, *prev;
+ struct eloop_timeout *timeout, *tmp;
os_time_t now_sec;
- timeout = os_malloc(sizeof(*timeout));
+ timeout = os_zalloc(sizeof(*timeout));
if (timeout == NULL)
return -1;
- os_get_time(&timeout->time);
+ if (os_get_reltime(&timeout->time) < 0) {
+ os_free(timeout);
+ return -1;
+ }
now_sec = timeout->time.sec;
timeout->time.sec += secs;
if (timeout->time.sec < now_sec) {
@@ -263,85 +268,156 @@ int eloop_register_timeout(unsigned int secs, unsigned int usecs,
timeout->eloop_data = eloop_data;
timeout->user_data = user_data;
timeout->handler = handler;
- timeout->next = NULL;
- if (eloop.timeout == NULL) {
- eloop.timeout = timeout;
- return 0;
+ /* Maintain timeouts in order of increasing time */
+ dl_list_for_each(tmp, &eloop.timeout, struct eloop_timeout, list) {
+ if (os_reltime_before(&timeout->time, &tmp->time)) {
+ dl_list_add(tmp->list.prev, &timeout->list);
+ return 0;
+ }
}
+ dl_list_add_tail(&eloop.timeout, &timeout->list);
- prev = NULL;
- tmp = eloop.timeout;
- while (tmp != NULL) {
- if (os_time_before(&timeout->time, &tmp->time))
- break;
- prev = tmp;
- tmp = tmp->next;
- }
+ return 0;
+}
- if (prev == NULL) {
- timeout->next = eloop.timeout;
- eloop.timeout = timeout;
- } else {
- timeout->next = prev->next;
- prev->next = timeout;
- }
- return 0;
+static void eloop_remove_timeout(struct eloop_timeout *timeout)
+{
+ dl_list_del(&timeout->list);
+ os_free(timeout);
}
int eloop_cancel_timeout(eloop_timeout_handler handler,
void *eloop_data, void *user_data)
{
- struct eloop_timeout *timeout, *prev, *next;
+ struct eloop_timeout *timeout, *prev;
int removed = 0;
- prev = NULL;
- timeout = eloop.timeout;
- while (timeout != NULL) {
- next = timeout->next;
-
+ dl_list_for_each_safe(timeout, prev, &eloop.timeout,
+ struct eloop_timeout, list) {
if (timeout->handler == handler &&
(timeout->eloop_data == eloop_data ||
eloop_data == ELOOP_ALL_CTX) &&
(timeout->user_data == user_data ||
user_data == ELOOP_ALL_CTX)) {
- if (prev == NULL)
- eloop.timeout = next;
- else
- prev->next = next;
- os_free(timeout);
+ eloop_remove_timeout(timeout);
removed++;
- } else
- prev = timeout;
-
- timeout = next;
+ }
}
return removed;
}
+int eloop_cancel_timeout_one(eloop_timeout_handler handler,
+ void *eloop_data, void *user_data,
+ struct os_reltime *remaining)
+{
+ struct eloop_timeout *timeout, *prev;
+ int removed = 0;
+ struct os_reltime now;
+
+ os_get_reltime(&now);
+ remaining->sec = remaining->usec = 0;
+
+ dl_list_for_each_safe(timeout, prev, &eloop.timeout,
+ struct eloop_timeout, list) {
+ if (timeout->handler == handler &&
+ (timeout->eloop_data == eloop_data) &&
+ (timeout->user_data == user_data)) {
+ removed = 1;
+ if (os_reltime_before(&now, &timeout->time))
+ os_reltime_sub(&timeout->time, &now, remaining);
+ eloop_remove_timeout(timeout);
+ break;
+ }
+ }
+ return removed;
+}
+
+
int eloop_is_timeout_registered(eloop_timeout_handler handler,
void *eloop_data, void *user_data)
{
struct eloop_timeout *tmp;
- tmp = eloop.timeout;
- while (tmp != NULL) {
+ dl_list_for_each(tmp, &eloop.timeout, struct eloop_timeout, list) {
if (tmp->handler == handler &&
tmp->eloop_data == eloop_data &&
tmp->user_data == user_data)
return 1;
-
- tmp = tmp->next;
}
return 0;
}
+int eloop_deplete_timeout(unsigned int req_secs, unsigned int req_usecs,
+ eloop_timeout_handler handler, void *eloop_data,
+ void *user_data)
+{
+ struct os_reltime now, requested, remaining;
+ struct eloop_timeout *tmp;
+
+ dl_list_for_each(tmp, &eloop.timeout, struct eloop_timeout, list) {
+ if (tmp->handler == handler &&
+ tmp->eloop_data == eloop_data &&
+ tmp->user_data == user_data) {
+ requested.sec = req_secs;
+ requested.usec = req_usecs;
+ os_get_reltime(&now);
+ os_reltime_sub(&tmp->time, &now, &remaining);
+ if (os_reltime_before(&requested, &remaining)) {
+ eloop_cancel_timeout(handler, eloop_data,
+ user_data);
+ eloop_register_timeout(requested.sec,
+ requested.usec,
+ handler, eloop_data,
+ user_data);
+ return 1;
+ }
+ return 0;
+ }
+ }
+
+ return -1;
+}
+
+
+int eloop_replenish_timeout(unsigned int req_secs, unsigned int req_usecs,
+ eloop_timeout_handler handler, void *eloop_data,
+ void *user_data)
+{
+ struct os_reltime now, requested, remaining;
+ struct eloop_timeout *tmp;
+
+ dl_list_for_each(tmp, &eloop.timeout, struct eloop_timeout, list) {
+ if (tmp->handler == handler &&
+ tmp->eloop_data == eloop_data &&
+ tmp->user_data == user_data) {
+ requested.sec = req_secs;
+ requested.usec = req_usecs;
+ os_get_reltime(&now);
+ os_reltime_sub(&tmp->time, &now, &remaining);
+ if (os_reltime_before(&remaining, &requested)) {
+ eloop_cancel_timeout(handler, eloop_data,
+ user_data);
+ eloop_register_timeout(requested.sec,
+ requested.usec,
+ handler, eloop_data,
+ user_data);
+ return 1;
+ }
+ return 0;
+ }
+ }
+
+ return -1;
+}
+
+
/* TODO: replace with suitable signal handler */
#if 0
static void eloop_handle_signal(int sig)
@@ -456,18 +532,21 @@ int eloop_register_signal_reconfig(eloop_signal_handler handler,
void eloop_run(void)
{
- struct os_time tv, now;
- DWORD count, ret, timeout, err;
+ struct os_reltime tv, now;
+ DWORD count, ret, timeout_val, err;
size_t i;
while (!eloop.terminate &&
- (eloop.timeout || eloop.reader_count > 0 ||
+ (!dl_list_empty(&eloop.timeout) || eloop.reader_count > 0 ||
eloop.event_count > 0)) {
+ struct eloop_timeout *timeout;
tv.sec = tv.usec = 0;
- if (eloop.timeout) {
- os_get_time(&now);
- if (os_time_before(&now, &eloop.timeout->time))
- os_time_sub(&eloop.timeout->time, &now, &tv);
+ timeout = dl_list_first(&eloop.timeout, struct eloop_timeout,
+ list);
+ if (timeout) {
+ os_get_reltime(&now);
+ if (os_reltime_before(&now, &timeout->time))
+ os_reltime_sub(&timeout->time, &now, &tv);
}
count = 0;
@@ -480,10 +559,10 @@ void eloop_run(void)
if (eloop.term_event)
eloop.handles[count++] = eloop.term_event;
- if (eloop.timeout)
- timeout = tv.sec * 1000 + tv.usec / 1000;
+ if (timeout)
+ timeout_val = tv.sec * 1000 + tv.usec / 1000;
else
- timeout = INFINITE;
+ timeout_val = INFINITE;
if (count > MAXIMUM_WAIT_OBJECTS) {
printf("WaitForMultipleObjects: Too many events: "
@@ -493,26 +572,27 @@ void eloop_run(void)
}
#ifdef _WIN32_WCE
ret = WaitForMultipleObjects(count, eloop.handles, FALSE,
- timeout);
+ timeout_val);
#else /* _WIN32_WCE */
ret = WaitForMultipleObjectsEx(count, eloop.handles, FALSE,
- timeout, TRUE);
+ timeout_val, TRUE);
#endif /* _WIN32_WCE */
err = GetLastError();
eloop_process_pending_signals();
/* check if some registered timeouts have occurred */
- if (eloop.timeout) {
- struct eloop_timeout *tmp;
-
- os_get_time(&now);
- if (!os_time_before(&now, &eloop.timeout->time)) {
- tmp = eloop.timeout;
- eloop.timeout = eloop.timeout->next;
- tmp->handler(tmp->eloop_data,
- tmp->user_data);
- os_free(tmp);
+ timeout = dl_list_first(&eloop.timeout, struct eloop_timeout,
+ list);
+ if (timeout) {
+ os_get_reltime(&now);
+ if (!os_reltime_before(&now, &timeout->time)) {
+ void *eloop_data = timeout->eloop_data;
+ void *user_data = timeout->user_data;
+ eloop_timeout_handler handler =
+ timeout->handler;
+ eloop_remove_timeout(timeout);
+ handler(eloop_data, user_data);
}
}
@@ -571,11 +651,9 @@ void eloop_destroy(void)
{
struct eloop_timeout *timeout, *prev;
- timeout = eloop.timeout;
- while (timeout != NULL) {
- prev = timeout;
- timeout = timeout->next;
- os_free(prev);
+ dl_list_for_each_safe(timeout, prev, &eloop.timeout,
+ struct eloop_timeout, list) {
+ eloop_remove_timeout(timeout);
}
os_free(eloop.readers);
os_free(eloop.signals);
diff --git a/src/utils/ext_password_test.c b/src/utils/ext_password_test.c
index 3801bb85449fe..b3a4552d1c2c4 100644
--- a/src/utils/ext_password_test.c
+++ b/src/utils/ext_password_test.c
@@ -36,7 +36,7 @@ static void ext_password_test_deinit(void *ctx)
{
struct ext_password_test_data *data = ctx;
- os_free(data->params);
+ str_clear_free(data->params);
os_free(data);
}
diff --git a/src/utils/http-utils.h b/src/utils/http-utils.h
new file mode 100644
index 0000000000000..8d4399a372404
--- /dev/null
+++ b/src/utils/http-utils.h
@@ -0,0 +1,63 @@
+/*
+ * HTTP wrapper
+ * Copyright (c) 2012-2013, Qualcomm Atheros, Inc.
+ *
+ * This software may be distributed under the terms of the BSD license.
+ * See README for more details.
+ */
+
+#ifndef HTTP_UTILS_H
+#define HTTP_UTILS_H
+
+struct http_ctx;
+
+struct http_othername {
+ char *oid;
+ u8 *data;
+ size_t len;
+};
+
+#define HTTP_MAX_CERT_LOGO_HASH 32
+
+struct http_logo {
+ char *alg_oid;
+ u8 *hash;
+ size_t hash_len;
+ char *uri;
+};
+
+struct http_cert {
+ char **dnsname;
+ unsigned int num_dnsname;
+ struct http_othername *othername;
+ unsigned int num_othername;
+ struct http_logo *logo;
+ unsigned int num_logo;
+};
+
+int soap_init_client(struct http_ctx *ctx, const char *address,
+ const char *ca_fname, const char *username,
+ const char *password, const char *client_cert,
+ const char *client_key);
+int soap_reinit_client(struct http_ctx *ctx);
+xml_node_t * soap_send_receive(struct http_ctx *ctx, xml_node_t *node);
+
+struct http_ctx * http_init_ctx(void *upper_ctx, struct xml_node_ctx *xml_ctx);
+void http_ocsp_set(struct http_ctx *ctx, int val);
+void http_deinit_ctx(struct http_ctx *ctx);
+
+int http_download_file(struct http_ctx *ctx, const char *url,
+ const char *fname, const char *ca_fname);
+char * http_post(struct http_ctx *ctx, const char *url, const char *data,
+ const char *content_type, const char *ext_hdr,
+ const char *ca_fname,
+ const char *username, const char *password,
+ const char *client_cert, const char *client_key,
+ size_t *resp_len);
+void http_set_cert_cb(struct http_ctx *ctx,
+ int (*cb)(void *ctx, struct http_cert *cert),
+ void *cb_ctx);
+const char * http_get_err(struct http_ctx *ctx);
+void http_parse_x509_certificate(struct http_ctx *ctx, const char *fname);
+
+#endif /* HTTP_UTILS_H */
diff --git a/src/utils/http_curl.c b/src/utils/http_curl.c
new file mode 100644
index 0000000000000..b38cf796ca2ac
--- /dev/null
+++ b/src/utils/http_curl.c
@@ -0,0 +1,1641 @@
+/*
+ * HTTP wrapper for libcurl
+ * Copyright (c) 2012-2014, Qualcomm Atheros, Inc.
+ *
+ * This software may be distributed under the terms of the BSD license.
+ * See README for more details.
+ */
+
+#include "includes.h"
+#include <curl/curl.h>
+#ifdef EAP_TLS_OPENSSL
+#include <openssl/ssl.h>
+#include <openssl/asn1.h>
+#include <openssl/asn1t.h>
+#include <openssl/x509v3.h>
+
+#ifdef SSL_set_tlsext_status_type
+#ifndef OPENSSL_NO_TLSEXT
+#define HAVE_OCSP
+#include <openssl/err.h>
+#include <openssl/ocsp.h>
+#endif /* OPENSSL_NO_TLSEXT */
+#endif /* SSL_set_tlsext_status_type */
+#endif /* EAP_TLS_OPENSSL */
+
+#include "common.h"
+#include "xml-utils.h"
+#include "http-utils.h"
+
+
+struct http_ctx {
+ void *ctx;
+ struct xml_node_ctx *xml;
+ CURL *curl;
+ struct curl_slist *curl_hdr;
+ char *svc_address;
+ char *svc_ca_fname;
+ char *svc_username;
+ char *svc_password;
+ char *svc_client_cert;
+ char *svc_client_key;
+ char *curl_buf;
+ size_t curl_buf_len;
+
+ int (*cert_cb)(void *ctx, struct http_cert *cert);
+ void *cert_cb_ctx;
+
+ enum {
+ NO_OCSP, OPTIONAL_OCSP, MANDATORY_OCSP
+ } ocsp;
+ X509 *peer_cert;
+ X509 *peer_issuer;
+ X509 *peer_issuer_issuer;
+
+ const char *last_err;
+};
+
+
+static void clear_curl(struct http_ctx *ctx)
+{
+ if (ctx->curl) {
+ curl_easy_cleanup(ctx->curl);
+ ctx->curl = NULL;
+ }
+ if (ctx->curl_hdr) {
+ curl_slist_free_all(ctx->curl_hdr);
+ ctx->curl_hdr = NULL;
+ }
+}
+
+
+static void clone_str(char **dst, const char *src)
+{
+ os_free(*dst);
+ if (src)
+ *dst = os_strdup(src);
+ else
+ *dst = NULL;
+}
+
+
+static void debug_dump(struct http_ctx *ctx, const char *title,
+ const char *buf, size_t len)
+{
+ char *txt;
+ size_t i;
+
+ for (i = 0; i < len; i++) {
+ if (buf[i] < 32 && buf[i] != '\t' && buf[i] != '\n' &&
+ buf[i] != '\r') {
+ wpa_hexdump_ascii(MSG_MSGDUMP, title, buf, len);
+ return;
+ }
+ }
+
+ txt = os_malloc(len + 1);
+ if (txt == NULL)
+ return;
+ os_memcpy(txt, buf, len);
+ txt[len] = '\0';
+ while (len > 0) {
+ len--;
+ if (txt[len] == '\n' || txt[len] == '\r')
+ txt[len] = '\0';
+ else
+ break;
+ }
+ wpa_printf(MSG_MSGDUMP, "%s[%s]", title, txt);
+ os_free(txt);
+}
+
+
+static int curl_cb_debug(CURL *curl, curl_infotype info, char *buf, size_t len,
+ void *userdata)
+{
+ struct http_ctx *ctx = userdata;
+ switch (info) {
+ case CURLINFO_TEXT:
+ debug_dump(ctx, "CURLINFO_TEXT", buf, len);
+ break;
+ case CURLINFO_HEADER_IN:
+ debug_dump(ctx, "CURLINFO_HEADER_IN", buf, len);
+ break;
+ case CURLINFO_HEADER_OUT:
+ debug_dump(ctx, "CURLINFO_HEADER_OUT", buf, len);
+ break;
+ case CURLINFO_DATA_IN:
+ debug_dump(ctx, "CURLINFO_DATA_IN", buf, len);
+ break;
+ case CURLINFO_DATA_OUT:
+ debug_dump(ctx, "CURLINFO_DATA_OUT", buf, len);
+ break;
+ case CURLINFO_SSL_DATA_IN:
+ wpa_printf(MSG_DEBUG, "debug - CURLINFO_SSL_DATA_IN - %d",
+ (int) len);
+ break;
+ case CURLINFO_SSL_DATA_OUT:
+ wpa_printf(MSG_DEBUG, "debug - CURLINFO_SSL_DATA_OUT - %d",
+ (int) len);
+ break;
+ case CURLINFO_END:
+ wpa_printf(MSG_DEBUG, "debug - CURLINFO_END - %d",
+ (int) len);
+ break;
+ }
+ return 0;
+}
+
+
+static size_t curl_cb_write(void *ptr, size_t size, size_t nmemb,
+ void *userdata)
+{
+ struct http_ctx *ctx = userdata;
+ char *n;
+ n = os_realloc(ctx->curl_buf, ctx->curl_buf_len + size * nmemb + 1);
+ if (n == NULL)
+ return 0;
+ ctx->curl_buf = n;
+ os_memcpy(n + ctx->curl_buf_len, ptr, size * nmemb);
+ n[ctx->curl_buf_len + size * nmemb] = '\0';
+ ctx->curl_buf_len += size * nmemb;
+ return size * nmemb;
+}
+
+
+#ifdef EAP_TLS_OPENSSL
+
+static void debug_dump_cert(const char *title, X509 *cert)
+{
+ BIO *out;
+ char *txt;
+ size_t rlen;
+
+ out = BIO_new(BIO_s_mem());
+ if (!out)
+ return;
+
+ X509_print_ex(out, cert, XN_FLAG_COMPAT, X509_FLAG_COMPAT);
+ rlen = BIO_ctrl_pending(out);
+ txt = os_malloc(rlen + 1);
+ if (txt) {
+ int res = BIO_read(out, txt, rlen);
+ if (res > 0) {
+ txt[res] = '\0';
+ wpa_printf(MSG_MSGDUMP, "%s:\n%s", title, txt);
+ }
+ os_free(txt);
+ }
+ BIO_free(out);
+}
+
+
+static void add_alt_name_othername(struct http_ctx *ctx, struct http_cert *cert,
+ OTHERNAME *o)
+{
+ char txt[100];
+ int res;
+ struct http_othername *on;
+ ASN1_TYPE *val;
+
+ on = os_realloc_array(cert->othername, cert->num_othername + 1,
+ sizeof(struct http_othername));
+ if (on == NULL)
+ return;
+ cert->othername = on;
+ on = &on[cert->num_othername];
+ os_memset(on, 0, sizeof(*on));
+
+ res = OBJ_obj2txt(txt, sizeof(txt), o->type_id, 1);
+ if (res < 0 || res >= (int) sizeof(txt))
+ return;
+
+ on->oid = os_strdup(txt);
+ if (on->oid == NULL)
+ return;
+
+ val = o->value;
+ on->data = val->value.octet_string->data;
+ on->len = val->value.octet_string->length;
+
+ cert->num_othername++;
+}
+
+
+static void add_alt_name_dns(struct http_ctx *ctx, struct http_cert *cert,
+ ASN1_STRING *name)
+{
+ char *buf;
+ char **n;
+
+ buf = NULL;
+ if (ASN1_STRING_to_UTF8((unsigned char **) &buf, name) < 0)
+ return;
+
+ n = os_realloc_array(cert->dnsname, cert->num_dnsname + 1,
+ sizeof(char *));
+ if (n == NULL)
+ return;
+
+ cert->dnsname = n;
+ n[cert->num_dnsname] = buf;
+ cert->num_dnsname++;
+}
+
+
+static void add_alt_name(struct http_ctx *ctx, struct http_cert *cert,
+ const GENERAL_NAME *name)
+{
+ switch (name->type) {
+ case GEN_OTHERNAME:
+ add_alt_name_othername(ctx, cert, name->d.otherName);
+ break;
+ case GEN_DNS:
+ add_alt_name_dns(ctx, cert, name->d.dNSName);
+ break;
+ }
+}
+
+
+static void add_alt_names(struct http_ctx *ctx, struct http_cert *cert,
+ GENERAL_NAMES *names)
+{
+ int num, i;
+
+ num = sk_GENERAL_NAME_num(names);
+ for (i = 0; i < num; i++) {
+ const GENERAL_NAME *name;
+ name = sk_GENERAL_NAME_value(names, i);
+ add_alt_name(ctx, cert, name);
+ }
+}
+
+
+/* RFC 3709 */
+
+typedef struct {
+ X509_ALGOR *hashAlg;
+ ASN1_OCTET_STRING *hashValue;
+} HashAlgAndValue;
+
+typedef struct {
+ STACK_OF(HashAlgAndValue) *refStructHash;
+ STACK_OF(ASN1_IA5STRING) *refStructURI;
+} LogotypeReference;
+
+typedef struct {
+ ASN1_IA5STRING *mediaType;
+ STACK_OF(HashAlgAndValue) *logotypeHash;
+ STACK_OF(ASN1_IA5STRING) *logotypeURI;
+} LogotypeDetails;
+
+typedef struct {
+ int type;
+ union {
+ ASN1_INTEGER *numBits;
+ ASN1_INTEGER *tableSize;
+ } d;
+} LogotypeImageResolution;
+
+typedef struct {
+ ASN1_INTEGER *type; /* LogotypeImageType ::= INTEGER */
+ ASN1_INTEGER *fileSize;
+ ASN1_INTEGER *xSize;
+ ASN1_INTEGER *ySize;
+ LogotypeImageResolution *resolution;
+ ASN1_IA5STRING *language;
+} LogotypeImageInfo;
+
+typedef struct {
+ LogotypeDetails *imageDetails;
+ LogotypeImageInfo *imageInfo;
+} LogotypeImage;
+
+typedef struct {
+ ASN1_INTEGER *fileSize;
+ ASN1_INTEGER *playTime;
+ ASN1_INTEGER *channels;
+ ASN1_INTEGER *sampleRate;
+ ASN1_IA5STRING *language;
+} LogotypeAudioInfo;
+
+typedef struct {
+ LogotypeDetails *audioDetails;
+ LogotypeAudioInfo *audioInfo;
+} LogotypeAudio;
+
+typedef struct {
+ STACK_OF(LogotypeImage) *image;
+ STACK_OF(LogotypeAudio) *audio;
+} LogotypeData;
+
+typedef struct {
+ int type;
+ union {
+ LogotypeData *direct;
+ LogotypeReference *indirect;
+ } d;
+} LogotypeInfo;
+
+typedef struct {
+ ASN1_OBJECT *logotypeType;
+ LogotypeInfo *info;
+} OtherLogotypeInfo;
+
+typedef struct {
+ STACK_OF(LogotypeInfo) *communityLogos;
+ LogotypeInfo *issuerLogo;
+ LogotypeInfo *subjectLogo;
+ STACK_OF(OtherLogotypeInfo) *otherLogos;
+} LogotypeExtn;
+
+ASN1_SEQUENCE(HashAlgAndValue) = {
+ ASN1_SIMPLE(HashAlgAndValue, hashAlg, X509_ALGOR),
+ ASN1_SIMPLE(HashAlgAndValue, hashValue, ASN1_OCTET_STRING)
+} ASN1_SEQUENCE_END(HashAlgAndValue);
+
+ASN1_SEQUENCE(LogotypeReference) = {
+ ASN1_SEQUENCE_OF(LogotypeReference, refStructHash, HashAlgAndValue),
+ ASN1_SEQUENCE_OF(LogotypeReference, refStructURI, ASN1_IA5STRING)
+} ASN1_SEQUENCE_END(LogotypeReference);
+
+ASN1_SEQUENCE(LogotypeDetails) = {
+ ASN1_SIMPLE(LogotypeDetails, mediaType, ASN1_IA5STRING),
+ ASN1_SEQUENCE_OF(LogotypeDetails, logotypeHash, HashAlgAndValue),
+ ASN1_SEQUENCE_OF(LogotypeDetails, logotypeURI, ASN1_IA5STRING)
+} ASN1_SEQUENCE_END(LogotypeDetails);
+
+ASN1_CHOICE(LogotypeImageResolution) = {
+ ASN1_IMP(LogotypeImageResolution, d.numBits, ASN1_INTEGER, 1),
+ ASN1_IMP(LogotypeImageResolution, d.tableSize, ASN1_INTEGER, 2)
+} ASN1_CHOICE_END(LogotypeImageResolution);
+
+ASN1_SEQUENCE(LogotypeImageInfo) = {
+ ASN1_IMP_OPT(LogotypeImageInfo, type, ASN1_INTEGER, 0),
+ ASN1_SIMPLE(LogotypeImageInfo, fileSize, ASN1_INTEGER),
+ ASN1_SIMPLE(LogotypeImageInfo, xSize, ASN1_INTEGER),
+ ASN1_SIMPLE(LogotypeImageInfo, ySize, ASN1_INTEGER),
+ ASN1_OPT(LogotypeImageInfo, resolution, LogotypeImageResolution),
+ ASN1_IMP_OPT(LogotypeImageInfo, language, ASN1_IA5STRING, 4),
+} ASN1_SEQUENCE_END(LogotypeImageInfo);
+
+ASN1_SEQUENCE(LogotypeImage) = {
+ ASN1_SIMPLE(LogotypeImage, imageDetails, LogotypeDetails),
+ ASN1_OPT(LogotypeImage, imageInfo, LogotypeImageInfo)
+} ASN1_SEQUENCE_END(LogotypeImage);
+
+ASN1_SEQUENCE(LogotypeAudioInfo) = {
+ ASN1_SIMPLE(LogotypeAudioInfo, fileSize, ASN1_INTEGER),
+ ASN1_SIMPLE(LogotypeAudioInfo, playTime, ASN1_INTEGER),
+ ASN1_SIMPLE(LogotypeAudioInfo, channels, ASN1_INTEGER),
+ ASN1_IMP_OPT(LogotypeAudioInfo, sampleRate, ASN1_INTEGER, 3),
+ ASN1_IMP_OPT(LogotypeAudioInfo, language, ASN1_IA5STRING, 4)
+} ASN1_SEQUENCE_END(LogotypeAudioInfo);
+
+ASN1_SEQUENCE(LogotypeAudio) = {
+ ASN1_SIMPLE(LogotypeAudio, audioDetails, LogotypeDetails),
+ ASN1_OPT(LogotypeAudio, audioInfo, LogotypeAudioInfo)
+} ASN1_SEQUENCE_END(LogotypeAudio);
+
+ASN1_SEQUENCE(LogotypeData) = {
+ ASN1_SEQUENCE_OF_OPT(LogotypeData, image, LogotypeImage),
+ ASN1_IMP_SEQUENCE_OF_OPT(LogotypeData, audio, LogotypeAudio, 1)
+} ASN1_SEQUENCE_END(LogotypeData);
+
+ASN1_CHOICE(LogotypeInfo) = {
+ ASN1_IMP(LogotypeInfo, d.direct, LogotypeData, 0),
+ ASN1_IMP(LogotypeInfo, d.indirect, LogotypeReference, 1)
+} ASN1_CHOICE_END(LogotypeInfo);
+
+ASN1_SEQUENCE(OtherLogotypeInfo) = {
+ ASN1_SIMPLE(OtherLogotypeInfo, logotypeType, ASN1_OBJECT),
+ ASN1_SIMPLE(OtherLogotypeInfo, info, LogotypeInfo)
+} ASN1_SEQUENCE_END(OtherLogotypeInfo);
+
+ASN1_SEQUENCE(LogotypeExtn) = {
+ ASN1_EXP_SEQUENCE_OF_OPT(LogotypeExtn, communityLogos, LogotypeInfo, 0),
+ ASN1_EXP_OPT(LogotypeExtn, issuerLogo, LogotypeInfo, 1),
+ ASN1_EXP_OPT(LogotypeExtn, issuerLogo, LogotypeInfo, 2),
+ ASN1_EXP_SEQUENCE_OF_OPT(LogotypeExtn, otherLogos, OtherLogotypeInfo, 3)
+} ASN1_SEQUENCE_END(LogotypeExtn);
+
+IMPLEMENT_ASN1_FUNCTIONS(LogotypeExtn);
+
+#define sk_LogotypeInfo_num(st) SKM_sk_num(LogotypeInfo, (st))
+#define sk_LogotypeInfo_value(st, i) SKM_sk_value(LogotypeInfo, (st), (i))
+#define sk_LogotypeImage_num(st) SKM_sk_num(LogotypeImage, (st))
+#define sk_LogotypeImage_value(st, i) SKM_sk_value(LogotypeImage, (st), (i))
+#define sk_LogotypeAudio_num(st) SKM_sk_num(LogotypeAudio, (st))
+#define sk_LogotypeAudio_value(st, i) SKM_sk_value(LogotypeAudio, (st), (i))
+#define sk_HashAlgAndValue_num(st) SKM_sk_num(HashAlgAndValue, (st))
+#define sk_HashAlgAndValue_value(st, i) SKM_sk_value(HashAlgAndValue, (st), (i))
+#define sk_ASN1_IA5STRING_num(st) SKM_sk_num(ASN1_IA5STRING, (st))
+#define sk_ASN1_IA5STRING_value(st, i) SKM_sk_value(ASN1_IA5STRING, (st), (i))
+
+
+static void add_logo(struct http_ctx *ctx, struct http_cert *hcert,
+ HashAlgAndValue *hash, ASN1_IA5STRING *uri)
+{
+ char txt[100];
+ int res, len;
+ struct http_logo *n;
+
+ if (hash == NULL || uri == NULL)
+ return;
+
+ res = OBJ_obj2txt(txt, sizeof(txt), hash->hashAlg->algorithm, 1);
+ if (res < 0 || res >= (int) sizeof(txt))
+ return;
+
+ n = os_realloc_array(hcert->logo, hcert->num_logo + 1,
+ sizeof(struct http_logo));
+ if (n == NULL)
+ return;
+ hcert->logo = n;
+ n = &hcert->logo[hcert->num_logo];
+ os_memset(n, 0, sizeof(*n));
+
+ n->alg_oid = os_strdup(txt);
+ if (n->alg_oid == NULL)
+ return;
+
+ n->hash_len = ASN1_STRING_length(hash->hashValue);
+ n->hash = os_malloc(n->hash_len);
+ if (n->hash == NULL) {
+ os_free(n->alg_oid);
+ return;
+ }
+ os_memcpy(n->hash, ASN1_STRING_data(hash->hashValue), n->hash_len);
+
+ len = ASN1_STRING_length(uri);
+ n->uri = os_malloc(len + 1);
+ if (n->uri == NULL) {
+ os_free(n->alg_oid);
+ os_free(n->hash);
+ return;
+ }
+ os_memcpy(n->uri, ASN1_STRING_data(uri), len);
+ n->uri[len] = '\0';
+
+ hcert->num_logo++;
+}
+
+
+static void add_logo_direct(struct http_ctx *ctx, struct http_cert *hcert,
+ LogotypeData *data)
+{
+ int i, num;
+
+ if (data->image == NULL)
+ return;
+
+ num = sk_LogotypeImage_num(data->image);
+ for (i = 0; i < num; i++) {
+ LogotypeImage *image;
+ LogotypeDetails *details;
+ int j, hash_num, uri_num;
+ HashAlgAndValue *found_hash = NULL;
+
+ image = sk_LogotypeImage_value(data->image, i);
+ if (image == NULL)
+ continue;
+
+ details = image->imageDetails;
+ if (details == NULL)
+ continue;
+
+ hash_num = sk_HashAlgAndValue_num(details->logotypeHash);
+ for (j = 0; j < hash_num; j++) {
+ HashAlgAndValue *hash;
+ char txt[100];
+ int res;
+ hash = sk_HashAlgAndValue_value(details->logotypeHash,
+ j);
+ if (hash == NULL)
+ continue;
+ res = OBJ_obj2txt(txt, sizeof(txt),
+ hash->hashAlg->algorithm, 1);
+ if (res < 0 || res >= (int) sizeof(txt))
+ continue;
+ if (os_strcmp(txt, "2.16.840.1.101.3.4.2.1") == 0) {
+ found_hash = hash;
+ break;
+ }
+ }
+
+ if (!found_hash) {
+ wpa_printf(MSG_DEBUG, "OpenSSL: No SHA256 hash found for the logo");
+ continue;
+ }
+
+ uri_num = sk_ASN1_IA5STRING_num(details->logotypeURI);
+ for (j = 0; j < uri_num; j++) {
+ ASN1_IA5STRING *uri;
+ uri = sk_ASN1_IA5STRING_value(details->logotypeURI, j);
+ add_logo(ctx, hcert, found_hash, uri);
+ }
+ }
+}
+
+
+static void add_logo_indirect(struct http_ctx *ctx, struct http_cert *hcert,
+ LogotypeReference *ref)
+{
+ int j, hash_num, uri_num;
+
+ hash_num = sk_HashAlgAndValue_num(ref->refStructHash);
+ uri_num = sk_ASN1_IA5STRING_num(ref->refStructURI);
+ if (hash_num != uri_num) {
+ wpa_printf(MSG_INFO, "Unexpected LogotypeReference array size difference %d != %d",
+ hash_num, uri_num);
+ return;
+ }
+
+ for (j = 0; j < hash_num; j++) {
+ HashAlgAndValue *hash;
+ ASN1_IA5STRING *uri;
+ hash = sk_HashAlgAndValue_value(ref->refStructHash, j);
+ uri = sk_ASN1_IA5STRING_value(ref->refStructURI, j);
+ add_logo(ctx, hcert, hash, uri);
+ }
+}
+
+
+static void i2r_HashAlgAndValue(HashAlgAndValue *hash, BIO *out, int indent)
+{
+ int i;
+ const unsigned char *data;
+
+ BIO_printf(out, "%*shashAlg: ", indent, "");
+ i2a_ASN1_OBJECT(out, hash->hashAlg->algorithm);
+ BIO_printf(out, "\n");
+
+ BIO_printf(out, "%*shashValue: ", indent, "");
+ data = hash->hashValue->data;
+ for (i = 0; i < hash->hashValue->length; i++)
+ BIO_printf(out, "%s%02x", i > 0 ? ":" : "", data[i]);
+ BIO_printf(out, "\n");
+}
+
+static void i2r_LogotypeDetails(LogotypeDetails *details, BIO *out, int indent)
+{
+ int i, num;
+
+ BIO_printf(out, "%*sLogotypeDetails\n", indent, "");
+ if (details->mediaType) {
+ BIO_printf(out, "%*smediaType: ", indent, "");
+ ASN1_STRING_print(out, details->mediaType);
+ BIO_printf(out, "\n");
+ }
+
+ num = details->logotypeHash ?
+ sk_HashAlgAndValue_num(details->logotypeHash) : 0;
+ for (i = 0; i < num; i++) {
+ HashAlgAndValue *hash;
+ hash = sk_HashAlgAndValue_value(details->logotypeHash, i);
+ i2r_HashAlgAndValue(hash, out, indent);
+ }
+
+ num = details->logotypeURI ?
+ sk_ASN1_IA5STRING_num(details->logotypeURI) : 0;
+ for (i = 0; i < num; i++) {
+ ASN1_IA5STRING *uri;
+ uri = sk_ASN1_IA5STRING_value(details->logotypeURI, i);
+ BIO_printf(out, "%*slogotypeURI: ", indent, "");
+ ASN1_STRING_print(out, uri);
+ BIO_printf(out, "\n");
+ }
+}
+
+static void i2r_LogotypeImageInfo(LogotypeImageInfo *info, BIO *out, int indent)
+{
+ long val;
+
+ BIO_printf(out, "%*sLogotypeImageInfo\n", indent, "");
+ if (info->type) {
+ val = ASN1_INTEGER_get(info->type);
+ BIO_printf(out, "%*stype: %ld\n", indent, "", val);
+ } else {
+ BIO_printf(out, "%*stype: default (1)\n", indent, "");
+ }
+ val = ASN1_INTEGER_get(info->xSize);
+ BIO_printf(out, "%*sxSize: %ld\n", indent, "", val);
+ val = ASN1_INTEGER_get(info->ySize);
+ BIO_printf(out, "%*sySize: %ld\n", indent, "", val);
+ if (info->resolution) {
+ BIO_printf(out, "%*sresolution\n", indent, "");
+ /* TODO */
+ }
+ if (info->language) {
+ BIO_printf(out, "%*slanguage: ", indent, "");
+ ASN1_STRING_print(out, info->language);
+ BIO_printf(out, "\n");
+ }
+}
+
+static void i2r_LogotypeImage(LogotypeImage *image, BIO *out, int indent)
+{
+ BIO_printf(out, "%*sLogotypeImage\n", indent, "");
+ if (image->imageDetails) {
+ i2r_LogotypeDetails(image->imageDetails, out, indent + 4);
+ }
+ if (image->imageInfo) {
+ i2r_LogotypeImageInfo(image->imageInfo, out, indent + 4);
+ }
+}
+
+static void i2r_LogotypeData(LogotypeData *data, const char *title, BIO *out,
+ int indent)
+{
+ int i, num;
+
+ BIO_printf(out, "%*s%s - LogotypeData\n", indent, "", title);
+
+ num = data->image ? sk_LogotypeImage_num(data->image) : 0;
+ for (i = 0; i < num; i++) {
+ LogotypeImage *image = sk_LogotypeImage_value(data->image, i);
+ i2r_LogotypeImage(image, out, indent + 4);
+ }
+
+ num = data->audio ? sk_LogotypeAudio_num(data->audio) : 0;
+ for (i = 0; i < num; i++) {
+ BIO_printf(out, "%*saudio: TODO\n", indent, "");
+ }
+}
+
+static void i2r_LogotypeReference(LogotypeReference *ref, const char *title,
+ BIO *out, int indent)
+{
+ int i, hash_num, uri_num;
+
+ BIO_printf(out, "%*s%s - LogotypeReference\n", indent, "", title);
+
+ hash_num = ref->refStructHash ?
+ sk_HashAlgAndValue_num(ref->refStructHash) : 0;
+ uri_num = ref->refStructURI ?
+ sk_ASN1_IA5STRING_num(ref->refStructURI) : 0;
+ if (hash_num != uri_num) {
+ BIO_printf(out, "%*sUnexpected LogotypeReference array size difference %d != %d\n",
+ indent, "", hash_num, uri_num);
+ return;
+ }
+
+ for (i = 0; i < hash_num; i++) {
+ HashAlgAndValue *hash;
+ ASN1_IA5STRING *uri;
+
+ hash = sk_HashAlgAndValue_value(ref->refStructHash, i);
+ i2r_HashAlgAndValue(hash, out, indent);
+
+ uri = sk_ASN1_IA5STRING_value(ref->refStructURI, i);
+ BIO_printf(out, "%*srefStructURI: ", indent, "");
+ ASN1_STRING_print(out, uri);
+ BIO_printf(out, "\n");
+ }
+}
+
+static void i2r_LogotypeInfo(LogotypeInfo *info, const char *title, BIO *out,
+ int indent)
+{
+ switch (info->type) {
+ case 0:
+ i2r_LogotypeData(info->d.direct, title, out, indent);
+ break;
+ case 1:
+ i2r_LogotypeReference(info->d.indirect, title, out, indent);
+ break;
+ }
+}
+
+static void debug_print_logotypeext(LogotypeExtn *logo)
+{
+ BIO *out;
+ int i, num;
+ int indent = 0;
+
+ out = BIO_new_fp(stdout, BIO_NOCLOSE);
+ if (out == NULL)
+ return;
+
+ if (logo->communityLogos) {
+ num = sk_LogotypeInfo_num(logo->communityLogos);
+ for (i = 0; i < num; i++) {
+ LogotypeInfo *info;
+ info = sk_LogotypeInfo_value(logo->communityLogos, i);
+ i2r_LogotypeInfo(info, "communityLogo", out, indent);
+ }
+ }
+
+ if (logo->issuerLogo) {
+ i2r_LogotypeInfo(logo->issuerLogo, "issuerLogo", out, indent );
+ }
+
+ if (logo->subjectLogo) {
+ i2r_LogotypeInfo(logo->subjectLogo, "subjectLogo", out, indent);
+ }
+
+ if (logo->otherLogos) {
+ BIO_printf(out, "%*sotherLogos - TODO\n", indent, "");
+ }
+
+ BIO_free(out);
+}
+
+
+static void add_logotype_ext(struct http_ctx *ctx, struct http_cert *hcert,
+ X509 *cert)
+{
+ ASN1_OBJECT *obj;
+ int pos;
+ X509_EXTENSION *ext;
+ ASN1_OCTET_STRING *os;
+ LogotypeExtn *logo;
+ const unsigned char *data;
+ int i, num;
+
+ obj = OBJ_txt2obj("1.3.6.1.5.5.7.1.12", 0);
+ if (obj == NULL)
+ return;
+
+ pos = X509_get_ext_by_OBJ(cert, obj, -1);
+ if (pos < 0) {
+ wpa_printf(MSG_INFO, "No logotype extension included");
+ return;
+ }
+
+ wpa_printf(MSG_INFO, "Parsing logotype extension");
+ ext = X509_get_ext(cert, pos);
+ if (!ext) {
+ wpa_printf(MSG_INFO, "Could not get logotype extension");
+ return;
+ }
+
+ os = X509_EXTENSION_get_data(ext);
+ if (os == NULL) {
+ wpa_printf(MSG_INFO, "Could not get logotype extension data");
+ return;
+ }
+
+ wpa_hexdump(MSG_DEBUG, "logotypeExtn",
+ ASN1_STRING_data(os), ASN1_STRING_length(os));
+
+ data = ASN1_STRING_data(os);
+ logo = d2i_LogotypeExtn(NULL, &data, ASN1_STRING_length(os));
+ if (logo == NULL) {
+ wpa_printf(MSG_INFO, "Failed to parse logotypeExtn");
+ return;
+ }
+
+ if (wpa_debug_level < MSG_INFO)
+ debug_print_logotypeext(logo);
+
+ if (!logo->communityLogos) {
+ wpa_printf(MSG_INFO, "No communityLogos included");
+ LogotypeExtn_free(logo);
+ return;
+ }
+
+ num = sk_LogotypeInfo_num(logo->communityLogos);
+ for (i = 0; i < num; i++) {
+ LogotypeInfo *info;
+ info = sk_LogotypeInfo_value(logo->communityLogos, i);
+ switch (info->type) {
+ case 0:
+ add_logo_direct(ctx, hcert, info->d.direct);
+ break;
+ case 1:
+ add_logo_indirect(ctx, hcert, info->d.indirect);
+ break;
+ }
+ }
+
+ LogotypeExtn_free(logo);
+}
+
+
+static void parse_cert(struct http_ctx *ctx, struct http_cert *hcert,
+ X509 *cert, GENERAL_NAMES **names)
+{
+ os_memset(hcert, 0, sizeof(*hcert));
+
+ *names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
+ if (*names)
+ add_alt_names(ctx, hcert, *names);
+
+ add_logotype_ext(ctx, hcert, cert);
+}
+
+
+static void parse_cert_free(struct http_cert *hcert, GENERAL_NAMES *names)
+{
+ unsigned int i;
+
+ for (i = 0; i < hcert->num_dnsname; i++)
+ OPENSSL_free(hcert->dnsname[i]);
+ os_free(hcert->dnsname);
+
+ for (i = 0; i < hcert->num_othername; i++)
+ os_free(hcert->othername[i].oid);
+ os_free(hcert->othername);
+
+ for (i = 0; i < hcert->num_logo; i++) {
+ os_free(hcert->logo[i].alg_oid);
+ os_free(hcert->logo[i].hash);
+ os_free(hcert->logo[i].uri);
+ }
+ os_free(hcert->logo);
+
+ sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
+}
+
+
+static int validate_server_cert(struct http_ctx *ctx, X509 *cert)
+{
+ GENERAL_NAMES *names;
+ struct http_cert hcert;
+ int ret;
+
+ if (ctx->cert_cb == NULL)
+ return 0;
+
+ if (0) {
+ BIO *out;
+ out = BIO_new_fp(stdout, BIO_NOCLOSE);
+ X509_print_ex(out, cert, XN_FLAG_COMPAT, X509_FLAG_COMPAT);
+ BIO_free(out);
+ }
+
+ parse_cert(ctx, &hcert, cert, &names);
+ ret = ctx->cert_cb(ctx->cert_cb_ctx, &hcert);
+ parse_cert_free(&hcert, names);
+
+ return ret;
+}
+
+
+void http_parse_x509_certificate(struct http_ctx *ctx, const char *fname)
+{
+ BIO *in, *out;
+ X509 *cert;
+ GENERAL_NAMES *names;
+ struct http_cert hcert;
+ unsigned int i;
+
+ in = BIO_new_file(fname, "r");
+ if (in == NULL) {
+ wpa_printf(MSG_ERROR, "Could not read '%s'", fname);
+ return;
+ }
+
+ cert = d2i_X509_bio(in, NULL);
+ BIO_free(in);
+
+ if (cert == NULL) {
+ wpa_printf(MSG_ERROR, "Could not parse certificate");
+ return;
+ }
+
+ out = BIO_new_fp(stdout, BIO_NOCLOSE);
+ if (out) {
+ X509_print_ex(out, cert, XN_FLAG_COMPAT,
+ X509_FLAG_COMPAT);
+ BIO_free(out);
+ }
+
+ wpa_printf(MSG_INFO, "Additional parsing information:");
+ parse_cert(ctx, &hcert, cert, &names);
+ for (i = 0; i < hcert.num_othername; i++) {
+ if (os_strcmp(hcert.othername[i].oid,
+ "1.3.6.1.4.1.40808.1.1.1") == 0) {
+ char *name = os_zalloc(hcert.othername[i].len + 1);
+ if (name) {
+ os_memcpy(name, hcert.othername[i].data,
+ hcert.othername[i].len);
+ wpa_printf(MSG_INFO,
+ "id-wfa-hotspot-friendlyName: %s",
+ name);
+ os_free(name);
+ }
+ wpa_hexdump_ascii(MSG_INFO,
+ "id-wfa-hotspot-friendlyName",
+ hcert.othername[i].data,
+ hcert.othername[i].len);
+ } else {
+ wpa_printf(MSG_INFO, "subjAltName[othername]: oid=%s",
+ hcert.othername[i].oid);
+ wpa_hexdump_ascii(MSG_INFO, "unknown othername",
+ hcert.othername[i].data,
+ hcert.othername[i].len);
+ }
+ }
+ parse_cert_free(&hcert, names);
+
+ X509_free(cert);
+}
+
+
+static int curl_cb_ssl_verify(int preverify_ok, X509_STORE_CTX *x509_ctx)
+{
+ struct http_ctx *ctx;
+ X509 *cert;
+ int err, depth;
+ char buf[256];
+ X509_NAME *name;
+ const char *err_str;
+ SSL *ssl;
+ SSL_CTX *ssl_ctx;
+
+ ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
+ SSL_get_ex_data_X509_STORE_CTX_idx());
+ ssl_ctx = ssl->ctx;
+ ctx = SSL_CTX_get_app_data(ssl_ctx);
+
+ wpa_printf(MSG_DEBUG, "curl_cb_ssl_verify");
+
+ err = X509_STORE_CTX_get_error(x509_ctx);
+ err_str = X509_verify_cert_error_string(err);
+ depth = X509_STORE_CTX_get_error_depth(x509_ctx);
+ cert = X509_STORE_CTX_get_current_cert(x509_ctx);
+ if (!cert) {
+ wpa_printf(MSG_INFO, "No server certificate available");
+ ctx->last_err = "No server certificate available";
+ return 0;
+ }
+
+ if (depth == 0)
+ ctx->peer_cert = cert;
+ else if (depth == 1)
+ ctx->peer_issuer = cert;
+ else if (depth == 2)
+ ctx->peer_issuer_issuer = cert;
+
+ name = X509_get_subject_name(cert);
+ X509_NAME_oneline(name, buf, sizeof(buf));
+ wpa_printf(MSG_INFO, "Server certificate chain - depth=%d err=%d (%s) subject=%s",
+ depth, err, err_str, buf);
+ debug_dump_cert("Server certificate chain - certificate", cert);
+
+ if (depth == 0 && preverify_ok && validate_server_cert(ctx, cert) < 0)
+ return 0;
+
+ if (!preverify_ok)
+ ctx->last_err = "TLS validation failed";
+
+ return preverify_ok;
+}
+
+
+#ifdef HAVE_OCSP
+
+static void ocsp_debug_print_resp(OCSP_RESPONSE *rsp)
+{
+ BIO *out;
+ size_t rlen;
+ char *txt;
+ int res;
+
+ out = BIO_new(BIO_s_mem());
+ if (!out)
+ return;
+
+ OCSP_RESPONSE_print(out, rsp, 0);
+ rlen = BIO_ctrl_pending(out);
+ txt = os_malloc(rlen + 1);
+ if (!txt) {
+ BIO_free(out);
+ return;
+ }
+
+ res = BIO_read(out, txt, rlen);
+ if (res > 0) {
+ txt[res] = '\0';
+ wpa_printf(MSG_MSGDUMP, "OpenSSL: OCSP Response\n%s", txt);
+ }
+ os_free(txt);
+ BIO_free(out);
+}
+
+
+static void tls_show_errors(const char *func, const char *txt)
+{
+ unsigned long err;
+
+ wpa_printf(MSG_DEBUG, "OpenSSL: %s - %s %s",
+ func, txt, ERR_error_string(ERR_get_error(), NULL));
+
+ while ((err = ERR_get_error())) {
+ wpa_printf(MSG_DEBUG, "OpenSSL: pending error: %s",
+ ERR_error_string(err, NULL));
+ }
+}
+
+
+static int ocsp_resp_cb(SSL *s, void *arg)
+{
+ struct http_ctx *ctx = arg;
+ const unsigned char *p;
+ int len, status, reason;
+ OCSP_RESPONSE *rsp;
+ OCSP_BASICRESP *basic;
+ OCSP_CERTID *id;
+ ASN1_GENERALIZEDTIME *produced_at, *this_update, *next_update;
+ X509_STORE *store;
+ STACK_OF(X509) *certs = NULL;
+
+ len = SSL_get_tlsext_status_ocsp_resp(s, &p);
+ if (!p) {
+ wpa_printf(MSG_DEBUG, "OpenSSL: No OCSP response received");
+ if (ctx->ocsp == MANDATORY_OCSP)
+ ctx->last_err = "No OCSP response received";
+ return (ctx->ocsp == MANDATORY_OCSP) ? 0 : 1;
+ }
+
+ wpa_hexdump(MSG_DEBUG, "OpenSSL: OCSP response", p, len);
+
+ rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
+ if (!rsp) {
+ wpa_printf(MSG_INFO, "OpenSSL: Failed to parse OCSP response");
+ ctx->last_err = "Failed to parse OCSP response";
+ return 0;
+ }
+
+ ocsp_debug_print_resp(rsp);
+
+ status = OCSP_response_status(rsp);
+ if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
+ wpa_printf(MSG_INFO, "OpenSSL: OCSP responder error %d (%s)",
+ status, OCSP_response_status_str(status));
+ ctx->last_err = "OCSP responder error";
+ return 0;
+ }
+
+ basic = OCSP_response_get1_basic(rsp);
+ if (!basic) {
+ wpa_printf(MSG_INFO, "OpenSSL: Could not find BasicOCSPResponse");
+ ctx->last_err = "Could not find BasicOCSPResponse";
+ return 0;
+ }
+
+ store = SSL_CTX_get_cert_store(s->ctx);
+ if (ctx->peer_issuer) {
+ wpa_printf(MSG_DEBUG, "OpenSSL: Add issuer");
+ debug_dump_cert("OpenSSL: Issuer certificate",
+ ctx->peer_issuer);
+
+ if (X509_STORE_add_cert(store, ctx->peer_issuer) != 1) {
+ tls_show_errors(__func__,
+ "OpenSSL: Could not add issuer to certificate store");
+ }
+ certs = sk_X509_new_null();
+ if (certs) {
+ X509 *cert;
+ cert = X509_dup(ctx->peer_issuer);
+ if (cert && !sk_X509_push(certs, cert)) {
+ tls_show_errors(
+ __func__,
+ "OpenSSL: Could not add issuer to OCSP responder trust store");
+ X509_free(cert);
+ sk_X509_free(certs);
+ certs = NULL;
+ }
+ if (certs && ctx->peer_issuer_issuer) {
+ cert = X509_dup(ctx->peer_issuer_issuer);
+ if (cert && !sk_X509_push(certs, cert)) {
+ tls_show_errors(
+ __func__,
+ "OpenSSL: Could not add issuer's issuer to OCSP responder trust store");
+ X509_free(cert);
+ }
+ }
+ }
+ }
+
+ status = OCSP_basic_verify(basic, certs, store, OCSP_TRUSTOTHER);
+ sk_X509_pop_free(certs, X509_free);
+ if (status <= 0) {
+ tls_show_errors(__func__,
+ "OpenSSL: OCSP response failed verification");
+ OCSP_BASICRESP_free(basic);
+ OCSP_RESPONSE_free(rsp);
+ ctx->last_err = "OCSP response failed verification";
+ return 0;
+ }
+
+ wpa_printf(MSG_DEBUG, "OpenSSL: OCSP response verification succeeded");
+
+ if (!ctx->peer_cert) {
+ wpa_printf(MSG_DEBUG, "OpenSSL: Peer certificate not available for OCSP status check");
+ OCSP_BASICRESP_free(basic);
+ OCSP_RESPONSE_free(rsp);
+ ctx->last_err = "Peer certificate not available for OCSP status check";
+ return 0;
+ }
+
+ if (!ctx->peer_issuer) {
+ wpa_printf(MSG_DEBUG, "OpenSSL: Peer issuer certificate not available for OCSP status check");
+ OCSP_BASICRESP_free(basic);
+ OCSP_RESPONSE_free(rsp);
+ ctx->last_err = "Peer issuer certificate not available for OCSP status check";
+ return 0;
+ }
+
+ id = OCSP_cert_to_id(NULL, ctx->peer_cert, ctx->peer_issuer);
+ if (!id) {
+ wpa_printf(MSG_DEBUG, "OpenSSL: Could not create OCSP certificate identifier");
+ OCSP_BASICRESP_free(basic);
+ OCSP_RESPONSE_free(rsp);
+ ctx->last_err = "Could not create OCSP certificate identifier";
+ return 0;
+ }
+
+ if (!OCSP_resp_find_status(basic, id, &status, &reason, &produced_at,
+ &this_update, &next_update)) {
+ wpa_printf(MSG_INFO, "OpenSSL: Could not find current server certificate from OCSP response%s",
+ (ctx->ocsp == MANDATORY_OCSP) ? "" :
+ " (OCSP not required)");
+ OCSP_BASICRESP_free(basic);
+ OCSP_RESPONSE_free(rsp);
+ if (ctx->ocsp == MANDATORY_OCSP)
+
+ ctx->last_err = "Could not find current server certificate from OCSP response";
+ return (ctx->ocsp == MANDATORY_OCSP) ? 0 : 1;
+ }
+
+ if (!OCSP_check_validity(this_update, next_update, 5 * 60, -1)) {
+ tls_show_errors(__func__, "OpenSSL: OCSP status times invalid");
+ OCSP_BASICRESP_free(basic);
+ OCSP_RESPONSE_free(rsp);
+ ctx->last_err = "OCSP status times invalid";
+ return 0;
+ }
+
+ OCSP_BASICRESP_free(basic);
+ OCSP_RESPONSE_free(rsp);
+
+ wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status for server certificate: %s",
+ OCSP_cert_status_str(status));
+
+ if (status == V_OCSP_CERTSTATUS_GOOD)
+ return 1;
+ if (status == V_OCSP_CERTSTATUS_REVOKED) {
+ ctx->last_err = "Server certificate has been revoked";
+ return 0;
+ }
+ if (ctx->ocsp == MANDATORY_OCSP) {
+ wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP required");
+ ctx->last_err = "OCSP status unknown";
+ return 0;
+ }
+ wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP was not required, so allow connection to continue");
+ return 1;
+}
+
+
+static SSL_METHOD patch_ssl_method;
+static const SSL_METHOD *real_ssl_method;
+
+static int curl_patch_ssl_new(SSL *s)
+{
+ SSL_CTX *ssl = s->ctx;
+ int ret;
+
+ ssl->method = real_ssl_method;
+ s->method = real_ssl_method;
+
+ ret = s->method->ssl_new(s);
+ SSL_set_tlsext_status_type(s, TLSEXT_STATUSTYPE_ocsp);
+
+ return ret;
+}
+
+#endif /* HAVE_OCSP */
+
+
+static CURLcode curl_cb_ssl(CURL *curl, void *sslctx, void *parm)
+{
+ struct http_ctx *ctx = parm;
+ SSL_CTX *ssl = sslctx;
+
+ wpa_printf(MSG_DEBUG, "curl_cb_ssl");
+ SSL_CTX_set_app_data(ssl, ctx);
+ SSL_CTX_set_verify(ssl, SSL_VERIFY_PEER, curl_cb_ssl_verify);
+
+#ifdef HAVE_OCSP
+ if (ctx->ocsp != NO_OCSP) {
+ SSL_CTX_set_tlsext_status_cb(ssl, ocsp_resp_cb);
+ SSL_CTX_set_tlsext_status_arg(ssl, ctx);
+
+ /*
+ * Use a temporary SSL_METHOD to get a callback on SSL_new()
+ * from libcurl since there is no proper callback registration
+ * available for this.
+ */
+ os_memset(&patch_ssl_method, 0, sizeof(patch_ssl_method));
+ patch_ssl_method.ssl_new = curl_patch_ssl_new;
+ real_ssl_method = ssl->method;
+ ssl->method = &patch_ssl_method;
+ }
+#endif /* HAVE_OCSP */
+
+ return CURLE_OK;
+}
+
+#endif /* EAP_TLS_OPENSSL */
+
+
+static CURL * setup_curl_post(struct http_ctx *ctx, const char *address,
+ const char *ca_fname, const char *username,
+ const char *password, const char *client_cert,
+ const char *client_key)
+{
+ CURL *curl;
+
+ wpa_printf(MSG_DEBUG, "Start HTTP client: address=%s ca_fname=%s "
+ "username=%s", address, ca_fname, username);
+
+ curl = curl_easy_init();
+ if (curl == NULL)
+ return NULL;
+
+ curl_easy_setopt(curl, CURLOPT_URL, address);
+ curl_easy_setopt(curl, CURLOPT_POST, 1L);
+ if (ca_fname) {
+ curl_easy_setopt(curl, CURLOPT_CAINFO, ca_fname);
+ curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
+#ifdef EAP_TLS_OPENSSL
+ curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, curl_cb_ssl);
+ curl_easy_setopt(curl, CURLOPT_SSL_CTX_DATA, ctx);
+#endif /* EAP_TLS_OPENSSL */
+ } else {
+ curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
+ }
+ if (client_cert && client_key) {
+ curl_easy_setopt(curl, CURLOPT_SSLCERT, client_cert);
+ curl_easy_setopt(curl, CURLOPT_SSLKEY, client_key);
+ }
+ /* TODO: use curl_easy_getinfo() with CURLINFO_CERTINFO to fetch
+ * information about the server certificate */
+ curl_easy_setopt(curl, CURLOPT_CERTINFO, 1L);
+ curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_cb_debug);
+ curl_easy_setopt(curl, CURLOPT_DEBUGDATA, ctx);
+ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_cb_write);
+ curl_easy_setopt(curl, CURLOPT_WRITEDATA, ctx);
+ curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
+ if (username) {
+ curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_ANYSAFE);
+ curl_easy_setopt(curl, CURLOPT_USERNAME, username);
+ curl_easy_setopt(curl, CURLOPT_PASSWORD, password);
+ }
+
+ return curl;
+}
+
+
+static int post_init_client(struct http_ctx *ctx, const char *address,
+ const char *ca_fname, const char *username,
+ const char *password, const char *client_cert,
+ const char *client_key)
+{
+ char *pos;
+ int count;
+
+ clone_str(&ctx->svc_address, address);
+ clone_str(&ctx->svc_ca_fname, ca_fname);
+ clone_str(&ctx->svc_username, username);
+ clone_str(&ctx->svc_password, password);
+ clone_str(&ctx->svc_client_cert, client_cert);
+ clone_str(&ctx->svc_client_key, client_key);
+
+ /*
+ * Workaround for Apache "Hostname 'FOO' provided via SNI and hostname
+ * 'foo' provided via HTTP are different.
+ */
+ for (count = 0, pos = ctx->svc_address; count < 3 && pos && *pos;
+ pos++) {
+ if (*pos == '/')
+ count++;
+ *pos = tolower(*pos);
+ }
+
+ ctx->curl = setup_curl_post(ctx, ctx->svc_address, ca_fname, username,
+ password, client_cert, client_key);
+ if (ctx->curl == NULL)
+ return -1;
+
+ return 0;
+}
+
+
+int soap_init_client(struct http_ctx *ctx, const char *address,
+ const char *ca_fname, const char *username,
+ const char *password, const char *client_cert,
+ const char *client_key)
+{
+ if (post_init_client(ctx, address, ca_fname, username, password,
+ client_cert, client_key) < 0)
+ return -1;
+
+ ctx->curl_hdr = curl_slist_append(ctx->curl_hdr,
+ "Content-Type: application/soap+xml");
+ ctx->curl_hdr = curl_slist_append(ctx->curl_hdr, "SOAPAction: ");
+ ctx->curl_hdr = curl_slist_append(ctx->curl_hdr, "Expect:");
+ curl_easy_setopt(ctx->curl, CURLOPT_HTTPHEADER, ctx->curl_hdr);
+
+ return 0;
+}
+
+
+int soap_reinit_client(struct http_ctx *ctx)
+{
+ char *address = NULL;
+ char *ca_fname = NULL;
+ char *username = NULL;
+ char *password = NULL;
+ char *client_cert = NULL;
+ char *client_key = NULL;
+ int ret;
+
+ clear_curl(ctx);
+
+ clone_str(&address, ctx->svc_address);
+ clone_str(&ca_fname, ctx->svc_ca_fname);
+ clone_str(&username, ctx->svc_username);
+ clone_str(&password, ctx->svc_password);
+ clone_str(&client_cert, ctx->svc_client_cert);
+ clone_str(&client_key, ctx->svc_client_key);
+
+ ret = soap_init_client(ctx, address, ca_fname, username, password,
+ client_cert, client_key);
+ os_free(address);
+ os_free(ca_fname);
+ str_clear_free(username);
+ str_clear_free(password);
+ os_free(client_cert);
+ os_free(client_key);
+ return ret;
+}
+
+
+static void free_curl_buf(struct http_ctx *ctx)
+{
+ os_free(ctx->curl_buf);
+ ctx->curl_buf = NULL;
+ ctx->curl_buf_len = 0;
+}
+
+
+xml_node_t * soap_send_receive(struct http_ctx *ctx, xml_node_t *node)
+{
+ char *str;
+ xml_node_t *envelope, *ret, *resp, *n;
+ CURLcode res;
+ long http = 0;
+
+ ctx->last_err = NULL;
+
+ wpa_printf(MSG_DEBUG, "SOAP: Sending message");
+ envelope = soap_build_envelope(ctx->xml, node);
+ str = xml_node_to_str(ctx->xml, envelope);
+ xml_node_free(ctx->xml, envelope);
+ wpa_printf(MSG_MSGDUMP, "SOAP[%s]", str);
+
+ curl_easy_setopt(ctx->curl, CURLOPT_POSTFIELDS, str);
+ free_curl_buf(ctx);
+
+ res = curl_easy_perform(ctx->curl);
+ if (res != CURLE_OK) {
+ if (!ctx->last_err)
+ ctx->last_err = curl_easy_strerror(res);
+ wpa_printf(MSG_ERROR, "curl_easy_perform() failed: %s",
+ ctx->last_err);
+ os_free(str);
+ free_curl_buf(ctx);
+ return NULL;
+ }
+ os_free(str);
+
+ curl_easy_getinfo(ctx->curl, CURLINFO_RESPONSE_CODE, &http);
+ wpa_printf(MSG_DEBUG, "SOAP: Server response code %ld", http);
+ if (http != 200) {
+ ctx->last_err = "HTTP download failed";
+ wpa_printf(MSG_INFO, "HTTP download failed - code %ld", http);
+ free_curl_buf(ctx);
+ return NULL;
+ }
+
+ if (ctx->curl_buf == NULL)
+ return NULL;
+
+ wpa_printf(MSG_MSGDUMP, "Server response:\n%s", ctx->curl_buf);
+ resp = xml_node_from_buf(ctx->xml, ctx->curl_buf);
+ free_curl_buf(ctx);
+ if (resp == NULL) {
+ wpa_printf(MSG_INFO, "Could not parse SOAP response");
+ ctx->last_err = "Could not parse SOAP response";
+ return NULL;
+ }
+
+ ret = soap_get_body(ctx->xml, resp);
+ if (ret == NULL) {
+ wpa_printf(MSG_INFO, "Could not get SOAP body");
+ ctx->last_err = "Could not get SOAP body";
+ return NULL;
+ }
+
+ wpa_printf(MSG_DEBUG, "SOAP body localname: '%s'",
+ xml_node_get_localname(ctx->xml, ret));
+ n = xml_node_copy(ctx->xml, ret);
+ xml_node_free(ctx->xml, resp);
+
+ return n;
+}
+
+
+struct http_ctx * http_init_ctx(void *upper_ctx, struct xml_node_ctx *xml_ctx)
+{
+ struct http_ctx *ctx;
+
+ ctx = os_zalloc(sizeof(*ctx));
+ if (ctx == NULL)
+ return NULL;
+ ctx->ctx = upper_ctx;
+ ctx->xml = xml_ctx;
+ ctx->ocsp = OPTIONAL_OCSP;
+
+ curl_global_init(CURL_GLOBAL_ALL);
+
+ return ctx;
+}
+
+
+void http_ocsp_set(struct http_ctx *ctx, int val)
+{
+ if (val == 0)
+ ctx->ocsp = NO_OCSP;
+ else if (val == 1)
+ ctx->ocsp = OPTIONAL_OCSP;
+ if (val == 2)
+ ctx->ocsp = MANDATORY_OCSP;
+}
+
+
+void http_deinit_ctx(struct http_ctx *ctx)
+{
+ clear_curl(ctx);
+ os_free(ctx->curl_buf);
+ curl_global_cleanup();
+
+ os_free(ctx->svc_address);
+ os_free(ctx->svc_ca_fname);
+ str_clear_free(ctx->svc_username);
+ str_clear_free(ctx->svc_password);
+ os_free(ctx->svc_client_cert);
+ os_free(ctx->svc_client_key);
+
+ os_free(ctx);
+}
+
+
+int http_download_file(struct http_ctx *ctx, const char *url,
+ const char *fname, const char *ca_fname)
+{
+ CURL *curl;
+ FILE *f;
+ CURLcode res;
+ long http = 0;
+
+ ctx->last_err = NULL;
+
+ wpa_printf(MSG_DEBUG, "curl: Download file from %s to %s (ca=%s)",
+ url, fname, ca_fname);
+ curl = curl_easy_init();
+ if (curl == NULL)
+ return -1;
+
+ f = fopen(fname, "wb");
+ if (f == NULL) {
+ curl_easy_cleanup(curl);
+ return -1;
+ }
+
+ curl_easy_setopt(curl, CURLOPT_URL, url);
+ if (ca_fname) {
+ curl_easy_setopt(curl, CURLOPT_CAINFO, ca_fname);
+ curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
+ curl_easy_setopt(curl, CURLOPT_CERTINFO, 1L);
+ } else {
+ curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
+ }
+ curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_cb_debug);
+ curl_easy_setopt(curl, CURLOPT_DEBUGDATA, ctx);
+ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite);
+ curl_easy_setopt(curl, CURLOPT_WRITEDATA, f);
+ curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
+
+ res = curl_easy_perform(curl);
+ if (res != CURLE_OK) {
+ if (!ctx->last_err)
+ ctx->last_err = curl_easy_strerror(res);
+ wpa_printf(MSG_ERROR, "curl_easy_perform() failed: %s",
+ ctx->last_err);
+ curl_easy_cleanup(curl);
+ fclose(f);
+ return -1;
+ }
+
+ curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http);
+ wpa_printf(MSG_DEBUG, "curl: Server response code %ld", http);
+ if (http != 200) {
+ ctx->last_err = "HTTP download failed";
+ wpa_printf(MSG_INFO, "HTTP download failed - code %ld", http);
+ curl_easy_cleanup(curl);
+ fclose(f);
+ return -1;
+ }
+
+ curl_easy_cleanup(curl);
+ fclose(f);
+
+ return 0;
+}
+
+
+char * http_post(struct http_ctx *ctx, const char *url, const char *data,
+ const char *content_type, const char *ext_hdr,
+ const char *ca_fname,
+ const char *username, const char *password,
+ const char *client_cert, const char *client_key,
+ size_t *resp_len)
+{
+ long http = 0;
+ CURLcode res;
+ char *ret;
+ CURL *curl;
+ struct curl_slist *curl_hdr = NULL;
+
+ ctx->last_err = NULL;
+ wpa_printf(MSG_DEBUG, "curl: HTTP POST to %s", url);
+ curl = setup_curl_post(ctx, url, ca_fname, username, password,
+ client_cert, client_key);
+ if (curl == NULL)
+ return NULL;
+
+ if (content_type) {
+ char ct[200];
+ snprintf(ct, sizeof(ct), "Content-Type: %s", content_type);
+ curl_hdr = curl_slist_append(curl_hdr, ct);
+ }
+ if (ext_hdr)
+ curl_hdr = curl_slist_append(curl_hdr, ext_hdr);
+ curl_easy_setopt(curl, CURLOPT_HTTPHEADER, curl_hdr);
+
+ curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
+ free_curl_buf(ctx);
+
+ res = curl_easy_perform(curl);
+ if (res != CURLE_OK) {
+ if (!ctx->last_err)
+ ctx->last_err = curl_easy_strerror(res);
+ wpa_printf(MSG_ERROR, "curl_easy_perform() failed: %s",
+ ctx->last_err);
+ free_curl_buf(ctx);
+ return NULL;
+ }
+
+ curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http);
+ wpa_printf(MSG_DEBUG, "curl: Server response code %ld", http);
+ if (http != 200) {
+ ctx->last_err = "HTTP POST failed";
+ wpa_printf(MSG_INFO, "HTTP POST failed - code %ld", http);
+ free_curl_buf(ctx);
+ return NULL;
+ }
+
+ if (ctx->curl_buf == NULL)
+ return NULL;
+
+ ret = ctx->curl_buf;
+ if (resp_len)
+ *resp_len = ctx->curl_buf_len;
+ ctx->curl_buf = NULL;
+ ctx->curl_buf_len = 0;
+
+ wpa_printf(MSG_MSGDUMP, "Server response:\n%s", ret);
+
+ return ret;
+}
+
+
+void http_set_cert_cb(struct http_ctx *ctx,
+ int (*cb)(void *ctx, struct http_cert *cert),
+ void *cb_ctx)
+{
+ ctx->cert_cb = cb;
+ ctx->cert_cb_ctx = cb_ctx;
+}
+
+
+const char * http_get_err(struct http_ctx *ctx)
+{
+ return ctx->last_err;
+}
diff --git a/src/utils/ip_addr.c b/src/utils/ip_addr.c
index 3647c764e6721..92a3590390331 100644
--- a/src/utils/ip_addr.c
+++ b/src/utils/ip_addr.c
@@ -33,30 +33,6 @@ const char * hostapd_ip_txt(const struct hostapd_ip_addr *addr, char *buf,
}
-int hostapd_ip_diff(struct hostapd_ip_addr *a, struct hostapd_ip_addr *b)
-{
- if (a == NULL && b == NULL)
- return 0;
- if (a == NULL || b == NULL)
- return 1;
-
- switch (a->af) {
- case AF_INET:
- if (a->u.v4.s_addr != b->u.v4.s_addr)
- return 1;
- break;
-#ifdef CONFIG_IPV6
- case AF_INET6:
- if (os_memcmp(&a->u.v6, &b->u.v6, sizeof(a->u.v6)) != 0)
- return 1;
- break;
-#endif /* CONFIG_IPV6 */
- }
-
- return 0;
-}
-
-
int hostapd_parse_ip_addr(const char *txt, struct hostapd_ip_addr *addr)
{
#ifndef CONFIG_NATIVE_WINDOWS
diff --git a/src/utils/ip_addr.h b/src/utils/ip_addr.h
index 79ac20cdbdc9e..0670411ccde43 100644
--- a/src/utils/ip_addr.h
+++ b/src/utils/ip_addr.h
@@ -22,7 +22,6 @@ struct hostapd_ip_addr {
const char * hostapd_ip_txt(const struct hostapd_ip_addr *addr, char *buf,
size_t buflen);
-int hostapd_ip_diff(struct hostapd_ip_addr *a, struct hostapd_ip_addr *b);
int hostapd_parse_ip_addr(const char *txt, struct hostapd_ip_addr *addr);
#endif /* IP_ADDR_H */
diff --git a/src/utils/list.h b/src/utils/list.h
index 6881130957ffa..ee2f4856950f1 100644
--- a/src/utils/list.h
+++ b/src/utils/list.h
@@ -17,6 +17,8 @@ struct dl_list {
struct dl_list *prev;
};
+#define DL_LIST_HEAD_INIT(l) { &(l), &(l) }
+
static inline void dl_list_init(struct dl_list *list)
{
list->next = list;
diff --git a/src/utils/os.h b/src/utils/os.h
index ad208341fa94d..77250d6371c91 100644
--- a/src/utils/os.h
+++ b/src/utils/os.h
@@ -23,6 +23,11 @@ struct os_time {
os_time_t usec;
};
+struct os_reltime {
+ os_time_t sec;
+ os_time_t usec;
+};
+
/**
* os_get_time - Get current time (sec, usec)
* @t: Pointer to buffer for the time
@@ -30,21 +35,84 @@ struct os_time {
*/
int os_get_time(struct os_time *t);
+/**
+ * os_get_reltime - Get relative time (sec, usec)
+ * @t: Pointer to buffer for the time
+ * Returns: 0 on success, -1 on failure
+ */
+int os_get_reltime(struct os_reltime *t);
+
+
+/* Helpers for handling struct os_time */
+
+static inline int os_time_before(struct os_time *a, struct os_time *b)
+{
+ return (a->sec < b->sec) ||
+ (a->sec == b->sec && a->usec < b->usec);
+}
+
+
+static inline void os_time_sub(struct os_time *a, struct os_time *b,
+ struct os_time *res)
+{
+ res->sec = a->sec - b->sec;
+ res->usec = a->usec - b->usec;
+ if (res->usec < 0) {
+ res->sec--;
+ res->usec += 1000000;
+ }
+}
+
+
+/* Helpers for handling struct os_reltime */
+
+static inline int os_reltime_before(struct os_reltime *a,
+ struct os_reltime *b)
+{
+ return (a->sec < b->sec) ||
+ (a->sec == b->sec && a->usec < b->usec);
+}
+
+
+static inline void os_reltime_sub(struct os_reltime *a, struct os_reltime *b,
+ struct os_reltime *res)
+{
+ res->sec = a->sec - b->sec;
+ res->usec = a->usec - b->usec;
+ if (res->usec < 0) {
+ res->sec--;
+ res->usec += 1000000;
+ }
+}
+
+
+static inline void os_reltime_age(struct os_reltime *start,
+ struct os_reltime *age)
+{
+ struct os_reltime now;
+
+ os_get_reltime(&now);
+ os_reltime_sub(&now, start, age);
+}
+
+
+static inline int os_reltime_expired(struct os_reltime *now,
+ struct os_reltime *ts,
+ os_time_t timeout_secs)
+{
+ struct os_reltime age;
+
+ os_reltime_sub(now, ts, &age);
+ return (age.sec > timeout_secs) ||
+ (age.sec == timeout_secs && age.usec > 0);
+}
-/* Helper macros for handling struct os_time */
-#define os_time_before(a, b) \
- ((a)->sec < (b)->sec || \
- ((a)->sec == (b)->sec && (a)->usec < (b)->usec))
+static inline int os_reltime_initialized(struct os_reltime *t)
+{
+ return t->sec != 0 || t->usec != 0;
+}
-#define os_time_sub(a, b, res) do { \
- (res)->sec = (a)->sec - (b)->sec; \
- (res)->usec = (a)->usec - (b)->usec; \
- if ((res)->usec < 0) { \
- (res)->sec--; \
- (res)->usec += 1000000; \
- } \
-} while (0)
/**
* os_mktime - Convert broken-down time into seconds since 1970-01-01
@@ -172,6 +240,13 @@ int os_unsetenv(const char *name);
char * os_readfile(const char *name, size_t *len);
/**
+ * os_file_exists - Check whether the specified file exists
+ * @fname: Path and name of the file
+ * Returns: 1 if the file exists or 0 if not
+ */
+int os_file_exists(const char *fname);
+
+/**
* os_zalloc - Allocate and zero memory
* @size: Number of bytes to allocate
* Returns: Pointer to allocated and zeroed memory or %NULL on failure
@@ -361,15 +436,6 @@ int os_strcmp(const char *s1, const char *s2);
int os_strncmp(const char *s1, const char *s2, size_t n);
/**
- * os_strncpy - Copy a string
- * @dest: Destination
- * @src: Source
- * @n: Maximum number of characters to copy
- * Returns: dest
- */
-char * os_strncpy(char *dest, const char *src, size_t n);
-
-/**
* os_strstr - Locate a substring
* @haystack: String (haystack) to search from
* @needle: Needle to search from haystack
@@ -465,9 +531,6 @@ char * os_strdup(const char *s);
#ifndef os_strncmp
#define os_strncmp(s1, s2, n) strncmp((s1), (s2), (n))
#endif
-#ifndef os_strncpy
-#define os_strncpy(d, s, n) strncpy((d), (s), (n))
-#endif
#ifndef os_strrchr
#define os_strrchr(s, c) strrchr((s), (c))
#endif
@@ -486,6 +549,12 @@ char * os_strdup(const char *s);
#endif /* OS_NO_C_LIB_DEFINES */
+static inline int os_snprintf_error(size_t size, int res)
+{
+ return res < 0 || (unsigned int) res >= size;
+}
+
+
static inline void * os_realloc_array(void *ptr, size_t nmemb, size_t size)
{
if (size && nmemb > (~(size_t) 0) / size)
@@ -493,6 +562,21 @@ static inline void * os_realloc_array(void *ptr, size_t nmemb, size_t size)
return os_realloc(ptr, nmemb * size);
}
+/**
+ * os_remove_in_array - Remove a member from an array by index
+ * @ptr: Pointer to the array
+ * @nmemb: Current member count of the array
+ * @size: The size per member of the array
+ * @idx: Index of the member to be removed
+ */
+static inline void os_remove_in_array(void *ptr, size_t nmemb, size_t size,
+ size_t idx)
+{
+ if (idx < nmemb - 1)
+ os_memmove(((unsigned char *) ptr) + idx * size,
+ ((unsigned char *) ptr) + (idx + 1) * size,
+ (nmemb - idx - 1) * size);
+}
/**
* os_strlcpy - Copy a string with size bound and NUL-termination
@@ -506,6 +590,32 @@ static inline void * os_realloc_array(void *ptr, size_t nmemb, size_t size)
*/
size_t os_strlcpy(char *dest, const char *src, size_t siz);
+/**
+ * os_memcmp_const - Constant time memory comparison
+ * @a: First buffer to compare
+ * @b: Second buffer to compare
+ * @len: Number of octets to compare
+ * Returns: 0 if buffers are equal, non-zero if not
+ *
+ * This function is meant for comparing passwords or hash values where
+ * difference in execution time could provide external observer information
+ * about the location of the difference in the memory buffers. The return value
+ * does not behave like os_memcmp(), i.e., os_memcmp_const() cannot be used to
+ * sort items into a defined order. Unlike os_memcmp(), execution time of
+ * os_memcmp_const() does not depend on the contents of the compared memory
+ * buffers, but only on the total compared length.
+ */
+int os_memcmp_const(const void *a, const void *b, size_t len);
+
+/**
+ * os_exec - Execute an external program
+ * @program: Path to the program
+ * @arg: Command line argument string
+ * @wait_completion: Whether to wait until the program execution completes
+ * Returns: 0 on success, -1 on error
+ */
+int os_exec(const char *program, const char *arg, int wait_completion);
+
#ifdef OS_REJECT_C_LIB_FUNCTIONS
#define malloc OS_DO_NOT_USE_malloc
diff --git a/src/utils/os_internal.c b/src/utils/os_internal.c
index e4b7fdb18ad35..77733ad916cd0 100644
--- a/src/utils/os_internal.c
+++ b/src/utils/os_internal.c
@@ -17,9 +17,11 @@
*/
#include "includes.h"
+#include <time.h>
+#include <sys/wait.h>
#undef OS_REJECT_C_LIB_FUNCTIONS
-#include "os.h"
+#include "common.h"
void os_sleep(os_time_t sec, os_time_t usec)
{
@@ -41,6 +43,17 @@ int os_get_time(struct os_time *t)
}
+int os_get_reltime(struct os_reltime *t)
+{
+ int res;
+ struct timeval tv;
+ res = gettimeofday(&tv, NULL);
+ t->sec = tv.tv_sec;
+ t->usec = tv.tv_usec;
+ return res;
+}
+
+
int os_mktime(int year, int month, int day, int hour, int min, int sec,
os_time_t *t)
{
@@ -85,7 +98,7 @@ int os_gmtime(os_time_t t, struct os_tm *tm)
int os_daemonize(const char *pid_file)
{
if (daemon(0, 0)) {
- perror("daemon");
+ wpa_printf(MSG_ERROR, "daemon: %s", strerror(errno));
return -1;
}
@@ -156,8 +169,8 @@ char * os_rel2abs_path(const char *rel_path)
}
}
- cwd_len = strlen(cwd);
- rel_len = strlen(rel_path);
+ cwd_len = os_strlen(cwd);
+ rel_len = os_strlen(rel_path);
ret_len = cwd_len + 1 + rel_len + 1;
ret = os_malloc(ret_len);
if (ret) {
@@ -452,6 +465,20 @@ size_t os_strlcpy(char *dest, const char *src, size_t siz)
}
+int os_memcmp_const(const void *a, const void *b, size_t len)
+{
+ const u8 *aa = a;
+ const u8 *bb = b;
+ size_t i;
+ u8 res;
+
+ for (res = 0, i = 0; i < len; i++)
+ res |= aa[i] ^ bb[i];
+
+ return res;
+}
+
+
char * os_strstr(const char *haystack, const char *needle)
{
size_t len = os_strlen(needle);
@@ -481,3 +508,57 @@ int os_snprintf(char *str, size_t size, const char *format, ...)
str[size - 1] = '\0';
return ret;
}
+
+
+int os_exec(const char *program, const char *arg, int wait_completion)
+{
+ pid_t pid;
+ int pid_status;
+
+ pid = fork();
+ if (pid < 0) {
+ wpa_printf(MSG_ERROR, "fork: %s", strerror(errno));
+ return -1;
+ }
+
+ if (pid == 0) {
+ /* run the external command in the child process */
+ const int MAX_ARG = 30;
+ char *_program, *_arg, *pos;
+ char *argv[MAX_ARG + 1];
+ int i;
+
+ _program = os_strdup(program);
+ _arg = os_strdup(arg);
+
+ argv[0] = _program;
+
+ i = 1;
+ pos = _arg;
+ while (i < MAX_ARG && pos && *pos) {
+ while (*pos == ' ')
+ pos++;
+ if (*pos == '\0')
+ break;
+ argv[i++] = pos;
+ pos = os_strchr(pos, ' ');
+ if (pos)
+ *pos++ = '\0';
+ }
+ argv[i] = NULL;
+
+ execv(program, argv);
+ wpa_printf(MSG_ERROR, "execv: %s", strerror(errno));
+ os_free(_program);
+ os_free(_arg);
+ exit(0);
+ return -1;
+ }
+
+ if (wait_completion) {
+ /* wait for the child process to complete in the parent */
+ waitpid(pid, &pid_status, 0);
+ }
+
+ return 0;
+}
diff --git a/src/utils/os_none.c b/src/utils/os_none.c
index cabf73bd87fc6..83fe025167b6f 100644
--- a/src/utils/os_none.c
+++ b/src/utils/os_none.c
@@ -26,6 +26,12 @@ int os_get_time(struct os_time *t)
}
+int os_get_reltime(struct os_reltime *t)
+{
+ return -1;
+}
+
+
int os_mktime(int year, int month, int day, int hour, int min, int sec,
os_time_t *t)
{
@@ -212,6 +218,11 @@ size_t os_strlcpy(char *dest, const char *src, size_t size)
}
+int os_memcmp_const(const void *a, const void *b, size_t len)
+{
+ return 0;
+}
+
char * os_strstr(const char *haystack, const char *needle)
{
return NULL;
@@ -223,3 +234,9 @@ int os_snprintf(char *str, size_t size, const char *format, ...)
return 0;
}
#endif /* OS_NO_C_LIB_DEFINES */
+
+
+int os_exec(const char *program, const char *arg, int wait_completion)
+{
+ return -1;
+}
diff --git a/src/utils/os_unix.c b/src/utils/os_unix.c
index 23a93becea43c..e0c1125d53051 100644
--- a/src/utils/os_unix.c
+++ b/src/utils/os_unix.c
@@ -9,23 +9,24 @@
#include "includes.h"
#include <time.h>
+#include <sys/wait.h>
#ifdef ANDROID
-#include <linux/capability.h>
-#include <linux/prctl.h>
+#include <sys/capability.h>
+#include <sys/prctl.h>
#include <private/android_filesystem_config.h>
#endif /* ANDROID */
#include "os.h"
+#include "common.h"
#ifdef WPA_TRACE
-#include "common.h"
#include "wpa_debug.h"
#include "trace.h"
#include "list.h"
-static struct dl_list alloc_list;
+static struct dl_list alloc_list = DL_LIST_HEAD_INIT(alloc_list);
#define ALLOC_MAGIC 0xa84ef1b2
#define FREED_MAGIC 0x67fd487a
@@ -60,6 +61,43 @@ int os_get_time(struct os_time *t)
}
+int os_get_reltime(struct os_reltime *t)
+{
+#if defined(CLOCK_BOOTTIME)
+ static clockid_t clock_id = CLOCK_BOOTTIME;
+#elif defined(CLOCK_MONOTONIC)
+ static clockid_t clock_id = CLOCK_MONOTONIC;
+#else
+ static clockid_t clock_id = CLOCK_REALTIME;
+#endif
+ struct timespec ts;
+ int res;
+
+ while (1) {
+ res = clock_gettime(clock_id, &ts);
+ if (res == 0) {
+ t->sec = ts.tv_sec;
+ t->usec = ts.tv_nsec / 1000;
+ return 0;
+ }
+ switch (clock_id) {
+#ifdef CLOCK_BOOTTIME
+ case CLOCK_BOOTTIME:
+ clock_id = CLOCK_MONOTONIC;
+ break;
+#endif
+#ifdef CLOCK_MONOTONIC
+ case CLOCK_MONOTONIC:
+ clock_id = CLOCK_REALTIME;
+ break;
+#endif
+ case CLOCK_REALTIME:
+ return -1;
+ }
+ }
+}
+
+
int os_mktime(int year, int month, int day, int hour, int min, int sec,
os_time_t *t)
{
@@ -213,6 +251,9 @@ char * os_rel2abs_path(const char *rel_path)
size_t len = 128, cwd_len, rel_len, ret_len;
int last_errno;
+ if (!rel_path)
+ return NULL;
+
if (rel_path[0] == '/')
return os_strdup(rel_path);
@@ -257,11 +298,15 @@ int os_program_init(void)
* We ignore errors here since errors are normal if we
* are already running as non-root.
*/
+#ifdef ANDROID_SETGROUPS_OVERRIDE
+ gid_t groups[] = { ANDROID_SETGROUPS_OVERRIDE };
+#else /* ANDROID_SETGROUPS_OVERRIDE */
gid_t groups[] = { AID_INET, AID_WIFI, AID_KEYSTORE };
+#endif /* ANDROID_SETGROUPS_OVERRIDE */
struct __user_cap_header_struct header;
struct __user_cap_data_struct cap;
- setgroups(sizeof(groups)/sizeof(groups[0]), groups);
+ setgroups(ARRAY_SIZE(groups), groups);
prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
@@ -276,9 +321,6 @@ int os_program_init(void)
capset(&header, &cap);
#endif /* ANDROID */
-#ifdef WPA_TRACE
- dl_list_init(&alloc_list);
-#endif /* WPA_TRACE */
return 0;
}
@@ -363,6 +405,16 @@ char * os_readfile(const char *name, size_t *len)
}
+int os_file_exists(const char *fname)
+{
+ FILE *f = fopen(fname, "rb");
+ if (f == NULL)
+ return 0;
+ fclose(f);
+ return 1;
+}
+
+
#ifndef WPA_TRACE
void * os_zalloc(size_t size)
{
@@ -396,11 +448,121 @@ size_t os_strlcpy(char *dest, const char *src, size_t siz)
}
+int os_memcmp_const(const void *a, const void *b, size_t len)
+{
+ const u8 *aa = a;
+ const u8 *bb = b;
+ size_t i;
+ u8 res;
+
+ for (res = 0, i = 0; i < len; i++)
+ res |= aa[i] ^ bb[i];
+
+ return res;
+}
+
+
#ifdef WPA_TRACE
+#if defined(WPA_TRACE_BFD) && defined(CONFIG_TESTING_OPTIONS)
+char wpa_trace_fail_func[256] = { 0 };
+unsigned int wpa_trace_fail_after;
+
+static int testing_fail_alloc(void)
+{
+ const char *func[WPA_TRACE_LEN];
+ size_t i, res, len;
+ char *pos, *next;
+ int match;
+
+ if (!wpa_trace_fail_after)
+ return 0;
+
+ res = wpa_trace_calling_func(func, WPA_TRACE_LEN);
+ i = 0;
+ if (i < res && os_strcmp(func[i], __func__) == 0)
+ i++;
+ if (i < res && os_strcmp(func[i], "os_malloc") == 0)
+ i++;
+ if (i < res && os_strcmp(func[i], "os_zalloc") == 0)
+ i++;
+ if (i < res && os_strcmp(func[i], "os_calloc") == 0)
+ i++;
+ if (i < res && os_strcmp(func[i], "os_realloc") == 0)
+ i++;
+ if (i < res && os_strcmp(func[i], "os_realloc_array") == 0)
+ i++;
+ if (i < res && os_strcmp(func[i], "os_strdup") == 0)
+ i++;
+
+ pos = wpa_trace_fail_func;
+
+ match = 0;
+ while (i < res) {
+ int allow_skip = 1;
+ int maybe = 0;
+
+ if (*pos == '=') {
+ allow_skip = 0;
+ pos++;
+ } else if (*pos == '?') {
+ maybe = 1;
+ pos++;
+ }
+ next = os_strchr(pos, ';');
+ if (next)
+ len = next - pos;
+ else
+ len = os_strlen(pos);
+ if (os_memcmp(pos, func[i], len) != 0) {
+ if (maybe && next) {
+ pos = next + 1;
+ continue;
+ }
+ if (allow_skip) {
+ i++;
+ continue;
+ }
+ return 0;
+ }
+ if (!next) {
+ match = 1;
+ break;
+ }
+ pos = next + 1;
+ i++;
+ }
+ if (!match)
+ return 0;
+
+ wpa_trace_fail_after--;
+ if (wpa_trace_fail_after == 0) {
+ wpa_printf(MSG_INFO, "TESTING: fail allocation at %s",
+ wpa_trace_fail_func);
+ for (i = 0; i < res; i++)
+ wpa_printf(MSG_INFO, "backtrace[%d] = %s",
+ (int) i, func[i]);
+ return 1;
+ }
+
+ return 0;
+}
+
+#else
+
+static inline int testing_fail_alloc(void)
+{
+ return 0;
+}
+#endif
+
void * os_malloc(size_t size)
{
struct os_alloc_trace *a;
+
+ if (testing_fail_alloc())
+ return NULL;
+
a = malloc(sizeof(*a) + size);
if (a == NULL)
return NULL;
@@ -486,3 +648,57 @@ char * os_strdup(const char *s)
}
#endif /* WPA_TRACE */
+
+
+int os_exec(const char *program, const char *arg, int wait_completion)
+{
+ pid_t pid;
+ int pid_status;
+
+ pid = fork();
+ if (pid < 0) {
+ perror("fork");
+ return -1;
+ }
+
+ if (pid == 0) {
+ /* run the external command in the child process */
+ const int MAX_ARG = 30;
+ char *_program, *_arg, *pos;
+ char *argv[MAX_ARG + 1];
+ int i;
+
+ _program = os_strdup(program);
+ _arg = os_strdup(arg);
+
+ argv[0] = _program;
+
+ i = 1;
+ pos = _arg;
+ while (i < MAX_ARG && pos && *pos) {
+ while (*pos == ' ')
+ pos++;
+ if (*pos == '\0')
+ break;
+ argv[i++] = pos;
+ pos = os_strchr(pos, ' ');
+ if (pos)
+ *pos++ = '\0';
+ }
+ argv[i] = NULL;
+
+ execv(program, argv);
+ perror("execv");
+ os_free(_program);
+ os_free(_arg);
+ exit(0);
+ return -1;
+ }
+
+ if (wait_completion) {
+ /* wait for the child process to complete in the parent */
+ waitpid(pid, &pid_status, 0);
+ }
+
+ return 0;
+}
diff --git a/src/utils/os_win32.c b/src/utils/os_win32.c
index 163cebefce265..296ea13f153b4 100644
--- a/src/utils/os_win32.c
+++ b/src/utils/os_win32.c
@@ -12,6 +12,7 @@
#include <wincrypt.h>
#include "os.h"
+#include "common.h"
void os_sleep(os_time_t sec, os_time_t usec)
{
@@ -47,6 +48,17 @@ int os_get_time(struct os_time *t)
}
+int os_get_reltime(struct os_reltime *t)
+{
+ /* consider using performance counters or so instead */
+ struct os_time now;
+ int res = os_get_time(&now);
+ t->sec = now.sec;
+ t->usec = now.usec;
+ return res;
+}
+
+
int os_mktime(int year, int month, int day, int hour, int min, int sec,
os_time_t *t)
{
@@ -233,3 +245,23 @@ size_t os_strlcpy(char *dest, const char *src, size_t siz)
return s - src - 1;
}
+
+
+int os_memcmp_const(const void *a, const void *b, size_t len)
+{
+ const u8 *aa = a;
+ const u8 *bb = b;
+ size_t i;
+ u8 res;
+
+ for (res = 0, i = 0; i < len; i++)
+ res |= aa[i] ^ bb[i];
+
+ return res;
+}
+
+
+int os_exec(const char *program, const char *arg, int wait_completion)
+{
+ return -1;
+}
diff --git a/src/utils/pcsc_funcs.c b/src/utils/pcsc_funcs.c
index 08510d015d9df..6f5ea93962131 100644
--- a/src/utils/pcsc_funcs.c
+++ b/src/utils/pcsc_funcs.c
@@ -281,77 +281,82 @@ static int scard_parse_fsp_templ(unsigned char *buf, size_t buf_len,
wpa_hexdump(MSG_DEBUG, "SCARD: file header FSP template",
pos, end - pos);
- while (pos + 1 < end) {
+ while (end - pos >= 2) {
+ unsigned char type, len;
+
+ type = pos[0];
+ len = pos[1];
wpa_printf(MSG_MSGDUMP, "SCARD: file header TLV 0x%02x len=%d",
- pos[0], pos[1]);
- if (pos + 2 + pos[1] > end)
+ type, len);
+ pos += 2;
+
+ if (len > (unsigned int) (end - pos))
break;
- switch (pos[0]) {
+ switch (type) {
case USIM_TLV_FILE_DESC:
wpa_hexdump(MSG_MSGDUMP, "SCARD: File Descriptor TLV",
- pos + 2, pos[1]);
+ pos, len);
break;
case USIM_TLV_FILE_ID:
wpa_hexdump(MSG_MSGDUMP, "SCARD: File Identifier TLV",
- pos + 2, pos[1]);
+ pos, len);
break;
case USIM_TLV_DF_NAME:
wpa_hexdump(MSG_MSGDUMP, "SCARD: DF name (AID) TLV",
- pos + 2, pos[1]);
+ pos, len);
break;
case USIM_TLV_PROPR_INFO:
wpa_hexdump(MSG_MSGDUMP, "SCARD: Proprietary "
- "information TLV", pos + 2, pos[1]);
+ "information TLV", pos, len);
break;
case USIM_TLV_LIFE_CYCLE_STATUS:
wpa_hexdump(MSG_MSGDUMP, "SCARD: Life Cycle Status "
- "Integer TLV", pos + 2, pos[1]);
+ "Integer TLV", pos, len);
break;
case USIM_TLV_FILE_SIZE:
wpa_hexdump(MSG_MSGDUMP, "SCARD: File size TLV",
- pos + 2, pos[1]);
- if ((pos[1] == 1 || pos[1] == 2) && file_len) {
- if (pos[1] == 1)
- *file_len = (int) pos[2];
+ pos, len);
+ if ((len == 1 || len == 2) && file_len) {
+ if (len == 1)
+ *file_len = (int) pos[0];
else
- *file_len = ((int) pos[2] << 8) |
- (int) pos[3];
+ *file_len = WPA_GET_BE16(pos);
wpa_printf(MSG_DEBUG, "SCARD: file_size=%d",
*file_len);
}
break;
case USIM_TLV_TOTAL_FILE_SIZE:
wpa_hexdump(MSG_MSGDUMP, "SCARD: Total file size TLV",
- pos + 2, pos[1]);
+ pos, len);
break;
case USIM_TLV_PIN_STATUS_TEMPLATE:
wpa_hexdump(MSG_MSGDUMP, "SCARD: PIN Status Template "
- "DO TLV", pos + 2, pos[1]);
- if (pos[1] >= 2 && pos[2] == USIM_PS_DO_TAG &&
- pos[3] >= 1 && ps_do) {
+ "DO TLV", pos, len);
+ if (len >= 2 && pos[0] == USIM_PS_DO_TAG &&
+ pos[1] >= 1 && ps_do) {
wpa_printf(MSG_DEBUG, "SCARD: PS_DO=0x%02x",
- pos[4]);
- *ps_do = (int) pos[4];
+ pos[2]);
+ *ps_do = (int) pos[2];
}
break;
case USIM_TLV_SHORT_FILE_ID:
wpa_hexdump(MSG_MSGDUMP, "SCARD: Short File "
- "Identifier (SFI) TLV", pos + 2, pos[1]);
+ "Identifier (SFI) TLV", pos, len);
break;
case USIM_TLV_SECURITY_ATTR_8B:
case USIM_TLV_SECURITY_ATTR_8C:
case USIM_TLV_SECURITY_ATTR_AB:
wpa_hexdump(MSG_MSGDUMP, "SCARD: Security attribute "
- "TLV", pos + 2, pos[1]);
+ "TLV", pos, len);
break;
default:
wpa_hexdump(MSG_MSGDUMP, "SCARD: Unrecognized TLV",
- pos, 2 + pos[1]);
+ pos, len);
break;
}
- pos += 2 + pos[1];
+ pos += len;
if (pos == end)
return 0;
@@ -397,10 +402,12 @@ static int scard_get_aid(struct scard_data *scard, unsigned char *aid,
unsigned char rid[5];
unsigned char appl_code[2]; /* 0x1002 for 3G USIM */
} *efdir;
- unsigned char buf[127];
+ unsigned char buf[127], *aid_pos;
size_t blen;
+ unsigned int aid_len = 0;
efdir = (struct efdir *) buf;
+ aid_pos = &buf[4];
blen = sizeof(buf);
if (scard_select_file(scard, SCARD_FILE_EF_DIR, buf, &blen)) {
wpa_printf(MSG_DEBUG, "SCARD: Failed to read EF_DIR");
@@ -449,14 +456,15 @@ static int scard_get_aid(struct scard_data *scard, unsigned char *aid,
continue;
}
- if (efdir->aid_len < 1 || efdir->aid_len > 16) {
- wpa_printf(MSG_DEBUG, "SCARD: Invalid AID length %d",
- efdir->aid_len);
+ aid_len = efdir->aid_len;
+ if (aid_len < 1 || aid_len > 16) {
+ wpa_printf(MSG_DEBUG, "SCARD: Invalid AID length %u",
+ aid_len);
continue;
}
wpa_hexdump(MSG_DEBUG, "SCARD: AID from EF_DIR record",
- efdir->rid, efdir->aid_len);
+ aid_pos, aid_len);
if (efdir->appl_code[0] == 0x10 &&
efdir->appl_code[1] == 0x02) {
@@ -472,30 +480,28 @@ static int scard_get_aid(struct scard_data *scard, unsigned char *aid,
return -1;
}
- if (efdir->aid_len > maxlen) {
+ if (aid_len > maxlen) {
wpa_printf(MSG_DEBUG, "SCARD: Too long AID");
return -1;
}
- os_memcpy(aid, efdir->rid, efdir->aid_len);
+ os_memcpy(aid, aid_pos, aid_len);
- return efdir->aid_len;
+ return aid_len;
}
/**
* scard_init - Initialize SIM/USIM connection using PC/SC
- * @sim_type: Allowed SIM types (SIM, USIM, or both)
* @reader: Reader name prefix to search for
* Returns: Pointer to private data structure, or %NULL on failure
*
* This function is used to initialize SIM/USIM connection. PC/SC is used to
- * open connection to the SIM/USIM card and the card is verified to support the
- * selected sim_type. In addition, local flag is set if a PIN is needed to
- * access some of the card functions. Once the connection is not needed
- * anymore, scard_deinit() can be used to close it.
+ * open connection to the SIM/USIM card. In addition, local flag is set if a
+ * PIN is needed to access some of the card functions. Once the connection is
+ * not needed anymore, scard_deinit() can be used to close it.
*/
-struct scard_data * scard_init(scard_sim_type sim_type, const char *reader)
+struct scard_data * scard_init(const char *reader)
{
long ret;
unsigned long len, pos;
@@ -612,20 +618,14 @@ struct scard_data * scard_init(scard_sim_type sim_type, const char *reader)
blen = sizeof(buf);
- scard->sim_type = SCARD_GSM_SIM;
- if (sim_type == SCARD_USIM_ONLY || sim_type == SCARD_TRY_BOTH) {
- wpa_printf(MSG_DEBUG, "SCARD: verifying USIM support");
- if (_scard_select_file(scard, SCARD_FILE_MF, buf, &blen,
- SCARD_USIM, NULL, 0)) {
- wpa_printf(MSG_DEBUG, "SCARD: USIM is not supported");
- if (sim_type == SCARD_USIM_ONLY)
- goto failed;
- wpa_printf(MSG_DEBUG, "SCARD: Trying to use GSM SIM");
- scard->sim_type = SCARD_GSM_SIM;
- } else {
- wpa_printf(MSG_DEBUG, "SCARD: USIM is supported");
- scard->sim_type = SCARD_USIM;
- }
+ wpa_printf(MSG_DEBUG, "SCARD: verifying USIM support");
+ if (_scard_select_file(scard, SCARD_FILE_MF, buf, &blen,
+ SCARD_USIM, NULL, 0)) {
+ wpa_printf(MSG_DEBUG, "SCARD: USIM is not supported. Trying to use GSM SIM");
+ scard->sim_type = SCARD_GSM_SIM;
+ } else {
+ wpa_printf(MSG_DEBUG, "SCARD: USIM is supported");
+ scard->sim_type = SCARD_USIM;
}
if (scard->sim_type == SCARD_GSM_SIM) {
@@ -1104,7 +1104,7 @@ int scard_get_imsi(struct scard_data *scard, char *imsi, size_t *len)
}
if (scard->sim_type == SCARD_GSM_SIM) {
- blen = (buf[2] << 8) | buf[3];
+ blen = WPA_GET_BE16(&buf[2]);
} else {
int file_size;
if (scard_parse_fsp_templ(buf, blen, NULL, &file_size))
@@ -1178,7 +1178,7 @@ int scard_get_mnc_len(struct scard_data *scard)
}
if (scard->sim_type == SCARD_GSM_SIM) {
- file_size = (buf[2] << 8) | buf[3];
+ file_size = WPA_GET_BE16(&buf[2]);
} else {
if (scard_parse_fsp_templ(buf, blen, NULL, &file_size))
return -3;
@@ -1245,6 +1245,7 @@ int scard_gsm_auth(struct scard_data *scard, const unsigned char *_rand,
cmd[4] = 17;
cmd[5] = 16;
os_memcpy(cmd + 6, _rand, 16);
+ get_resp[0] = USIM_CLA;
}
len = sizeof(resp);
ret = scard_transmit(scard, cmd, cmdlen, resp, &len);
@@ -1413,6 +1414,12 @@ int scard_umts_auth(struct scard_data *scard, const unsigned char *_rand,
pos += IK_LEN;
wpa_hexdump(MSG_DEBUG, "SCARD: IK", ik, IK_LEN);
+ if (end > pos) {
+ wpa_hexdump(MSG_DEBUG,
+ "SCARD: Ignore extra data in end",
+ pos, end - pos);
+ }
+
return 0;
}
diff --git a/src/utils/pcsc_funcs.h b/src/utils/pcsc_funcs.h
index b4ebc99835b6e..eacd2a2d70f14 100644
--- a/src/utils/pcsc_funcs.h
+++ b/src/utils/pcsc_funcs.h
@@ -9,15 +9,8 @@
#ifndef PCSC_FUNCS_H
#define PCSC_FUNCS_H
-typedef enum {
- SCARD_GSM_SIM_ONLY,
- SCARD_USIM_ONLY,
- SCARD_TRY_BOTH
-} scard_sim_type;
-
-
#ifdef PCSC_FUNCS
-struct scard_data * scard_init(scard_sim_type sim_type, const char *reader);
+struct scard_data * scard_init(const char *reader);
void scard_deinit(struct scard_data *scard);
int scard_set_pin(struct scard_data *scard, const char *pin);
@@ -34,7 +27,7 @@ int scard_supports_umts(struct scard_data *scard);
#else /* PCSC_FUNCS */
-#define scard_init(s, r) NULL
+#define scard_init(r) NULL
#define scard_deinit(s) do { } while (0)
#define scard_set_pin(s, p) -1
#define scard_get_imsi(s, i, l) -1
diff --git a/src/utils/platform.h b/src/utils/platform.h
new file mode 100644
index 0000000000000..46cfe785e1806
--- /dev/null
+++ b/src/utils/platform.h
@@ -0,0 +1,21 @@
+#ifndef PLATFORM_H
+#define PLATFORM_H
+
+#include "includes.h"
+#include "common.h"
+
+#define le16_to_cpu le_to_host16
+#define le32_to_cpu le_to_host32
+
+#define get_unaligned(p) \
+({ \
+ struct packed_dummy_struct { \
+ typeof(*(p)) __val; \
+ } __attribute__((packed)) *__ptr = (void *) (p); \
+ \
+ __ptr->__val; \
+})
+#define get_unaligned_le16(p) le16_to_cpu(get_unaligned((uint16_t *)(p)))
+#define get_unaligned_le32(p) le32_to_cpu(get_unaligned((uint32_t *)(p)))
+
+#endif /* PLATFORM_H */
diff --git a/src/utils/radiotap.c b/src/utils/radiotap.c
index 804473fa4bfb9..f8f815a86be92 100644
--- a/src/utils/radiotap.c
+++ b/src/utils/radiotap.c
@@ -2,6 +2,7 @@
* Radiotap parser
*
* Copyright 2007 Andy Green <andy@warmcat.com>
+ * Copyright 2009 Johannes Berg <johannes@sipsolutions.net>
*
* 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
@@ -10,34 +11,44 @@
* Alternatively, this software may be distributed under the terms of BSD
* license.
*
- * See README and COPYING for more details.
- *
- *
- * Modified for userspace by Johannes Berg <johannes@sipsolutions.net>
- * I only modified some things on top to ease syncing should bugs be found.
+ * See COPYING for more details.
*/
-
-#include "includes.h"
-
-#include "common.h"
#include "radiotap_iter.h"
-
-#define le16_to_cpu le_to_host16
-#define le32_to_cpu le_to_host32
-#define __le32 uint32_t
-#define ulong unsigned long
-#define unlikely(cond) (cond)
-#define get_unaligned(p) \
-({ \
- struct packed_dummy_struct { \
- typeof(*(p)) __val; \
- } __attribute__((packed)) *__ptr = (void *) (p); \
- \
- __ptr->__val; \
-})
+#include "platform.h"
/* function prototypes and related defs are in radiotap_iter.h */
+static const struct radiotap_align_size rtap_namespace_sizes[] = {
+ [IEEE80211_RADIOTAP_TSFT] = { .align = 8, .size = 8, },
+ [IEEE80211_RADIOTAP_FLAGS] = { .align = 1, .size = 1, },
+ [IEEE80211_RADIOTAP_RATE] = { .align = 1, .size = 1, },
+ [IEEE80211_RADIOTAP_CHANNEL] = { .align = 2, .size = 4, },
+ [IEEE80211_RADIOTAP_FHSS] = { .align = 2, .size = 2, },
+ [IEEE80211_RADIOTAP_DBM_ANTSIGNAL] = { .align = 1, .size = 1, },
+ [IEEE80211_RADIOTAP_DBM_ANTNOISE] = { .align = 1, .size = 1, },
+ [IEEE80211_RADIOTAP_LOCK_QUALITY] = { .align = 2, .size = 2, },
+ [IEEE80211_RADIOTAP_TX_ATTENUATION] = { .align = 2, .size = 2, },
+ [IEEE80211_RADIOTAP_DB_TX_ATTENUATION] = { .align = 2, .size = 2, },
+ [IEEE80211_RADIOTAP_DBM_TX_POWER] = { .align = 1, .size = 1, },
+ [IEEE80211_RADIOTAP_ANTENNA] = { .align = 1, .size = 1, },
+ [IEEE80211_RADIOTAP_DB_ANTSIGNAL] = { .align = 1, .size = 1, },
+ [IEEE80211_RADIOTAP_DB_ANTNOISE] = { .align = 1, .size = 1, },
+ [IEEE80211_RADIOTAP_RX_FLAGS] = { .align = 2, .size = 2, },
+ [IEEE80211_RADIOTAP_TX_FLAGS] = { .align = 2, .size = 2, },
+ [IEEE80211_RADIOTAP_RTS_RETRIES] = { .align = 1, .size = 1, },
+ [IEEE80211_RADIOTAP_DATA_RETRIES] = { .align = 1, .size = 1, },
+ [IEEE80211_RADIOTAP_MCS] = { .align = 1, .size = 3, },
+ [IEEE80211_RADIOTAP_AMPDU_STATUS] = { .align = 4, .size = 8, },
+ /*
+ * add more here as they are defined in radiotap.h
+ */
+};
+
+static const struct ieee80211_radiotap_namespace radiotap_ns = {
+ .n_bits = sizeof(rtap_namespace_sizes) / sizeof(rtap_namespace_sizes[0]),
+ .align_size = rtap_namespace_sizes,
+};
+
/**
* ieee80211_radiotap_iterator_init - radiotap parser iterator initialization
* @iterator: radiotap_iterator to initialize
@@ -73,38 +84,53 @@
* get_unaligned((type *)iterator.this_arg) to dereference
* iterator.this_arg for type "type" safely on all arches.
*
- * Example code:
- * See Documentation/networking/radiotap-headers.txt
+ * Example code: parse.c
*/
int ieee80211_radiotap_iterator_init(
- struct ieee80211_radiotap_iterator *iterator,
- struct ieee80211_radiotap_header *radiotap_header,
- int max_length)
+ struct ieee80211_radiotap_iterator *iterator,
+ struct ieee80211_radiotap_header *radiotap_header,
+ int max_length, const struct ieee80211_radiotap_vendor_namespaces *vns)
{
+ /* must at least have the radiotap header */
+ if (max_length < (int)sizeof(struct ieee80211_radiotap_header))
+ return -EINVAL;
+
/* Linux only supports version 0 radiotap format */
if (radiotap_header->it_version)
return -EINVAL;
/* sanity check for allowed length and radiotap length field */
- if (max_length < le16_to_cpu(get_unaligned(&radiotap_header->it_len)))
+ if (max_length < get_unaligned_le16(&radiotap_header->it_len))
return -EINVAL;
- iterator->rtheader = radiotap_header;
- iterator->max_length = le16_to_cpu(get_unaligned(
- &radiotap_header->it_len));
- iterator->arg_index = 0;
- iterator->bitmap_shifter = le32_to_cpu(get_unaligned(
- &radiotap_header->it_present));
- iterator->arg = (u8 *)radiotap_header + sizeof(*radiotap_header);
- iterator->this_arg = NULL;
+ iterator->_rtheader = radiotap_header;
+ iterator->_max_length = get_unaligned_le16(&radiotap_header->it_len);
+ iterator->_arg_index = 0;
+ iterator->_bitmap_shifter = get_unaligned_le32(&radiotap_header->it_present);
+ iterator->_arg = (uint8_t *)radiotap_header + sizeof(*radiotap_header);
+ iterator->_next_ns_data = NULL;
+ iterator->_reset_on_ext = 0;
+ iterator->_next_bitmap = &radiotap_header->it_present;
+ iterator->_next_bitmap++;
+ iterator->_vns = vns;
+ iterator->current_namespace = &radiotap_ns;
+ iterator->is_radiotap_ns = 1;
+#ifdef RADIOTAP_SUPPORT_OVERRIDES
+ iterator->n_overrides = 0;
+ iterator->overrides = NULL;
+#endif
/* find payload start allowing for extended bitmap(s) */
- if (unlikely(iterator->bitmap_shifter & (1<<IEEE80211_RADIOTAP_EXT))) {
- while (le32_to_cpu(get_unaligned((__le32 *)iterator->arg)) &
- (1<<IEEE80211_RADIOTAP_EXT)) {
- iterator->arg += sizeof(u32);
+ if (iterator->_bitmap_shifter & (1<<IEEE80211_RADIOTAP_EXT)) {
+ if ((unsigned long)iterator->_arg -
+ (unsigned long)iterator->_rtheader + sizeof(uint32_t) >
+ (unsigned long)iterator->_max_length)
+ return -EINVAL;
+ while (get_unaligned_le32(iterator->_arg) &
+ (1 << IEEE80211_RADIOTAP_EXT)) {
+ iterator->_arg += sizeof(uint32_t);
/*
* check for insanity where the present bitmaps
@@ -112,12 +138,14 @@ int ieee80211_radiotap_iterator_init(
* stated radiotap header length
*/
- if (((ulong)iterator->arg - (ulong)iterator->rtheader)
- > (ulong)iterator->max_length)
+ if ((unsigned long)iterator->_arg -
+ (unsigned long)iterator->_rtheader +
+ sizeof(uint32_t) >
+ (unsigned long)iterator->_max_length)
return -EINVAL;
}
- iterator->arg += sizeof(u32);
+ iterator->_arg += sizeof(uint32_t);
/*
* no need to check again for blowing past stated radiotap
@@ -126,11 +154,59 @@ int ieee80211_radiotap_iterator_init(
*/
}
+ iterator->this_arg = iterator->_arg;
+ iterator->this_arg_index = 0;
+ iterator->this_arg_size = 0;
+
/* we are all initialized happily */
return 0;
}
+static void find_ns(struct ieee80211_radiotap_iterator *iterator,
+ uint32_t oui, uint8_t subns)
+{
+ int i;
+
+ iterator->current_namespace = NULL;
+
+ if (!iterator->_vns)
+ return;
+
+ for (i = 0; i < iterator->_vns->n_ns; i++) {
+ if (iterator->_vns->ns[i].oui != oui)
+ continue;
+ if (iterator->_vns->ns[i].subns != subns)
+ continue;
+
+ iterator->current_namespace = &iterator->_vns->ns[i];
+ break;
+ }
+}
+
+#ifdef RADIOTAP_SUPPORT_OVERRIDES
+static int find_override(struct ieee80211_radiotap_iterator *iterator,
+ int *align, int *size)
+{
+ int i;
+
+ if (!iterator->overrides)
+ return 0;
+
+ for (i = 0; i < iterator->n_overrides; i++) {
+ if (iterator->_arg_index == iterator->overrides[i].field) {
+ *align = iterator->overrides[i].align;
+ *size = iterator->overrides[i].size;
+ if (!*align) /* erroneous override */
+ return 0;
+ return 1;
+ }
+ }
+
+ return 0;
+}
+#endif
+
/**
* ieee80211_radiotap_iterator_next - return next radiotap parser iterator arg
@@ -156,99 +232,106 @@ int ieee80211_radiotap_iterator_init(
*/
int ieee80211_radiotap_iterator_next(
- struct ieee80211_radiotap_iterator *iterator)
+ struct ieee80211_radiotap_iterator *iterator)
{
-
- /*
- * small length lookup table for all radiotap types we heard of
- * starting from b0 in the bitmap, so we can walk the payload
- * area of the radiotap header
- *
- * There is a requirement to pad args, so that args
- * of a given length must begin at a boundary of that length
- * -- but note that compound args are allowed (eg, 2 x u16
- * for IEEE80211_RADIOTAP_CHANNEL) so total arg length is not
- * a reliable indicator of alignment requirement.
- *
- * upper nybble: content alignment for arg
- * lower nybble: content length for arg
- */
-
- static const u8 rt_sizes[] = {
- [IEEE80211_RADIOTAP_TSFT] = 0x88,
- [IEEE80211_RADIOTAP_FLAGS] = 0x11,
- [IEEE80211_RADIOTAP_RATE] = 0x11,
- [IEEE80211_RADIOTAP_CHANNEL] = 0x24,
- [IEEE80211_RADIOTAP_FHSS] = 0x22,
- [IEEE80211_RADIOTAP_DBM_ANTSIGNAL] = 0x11,
- [IEEE80211_RADIOTAP_DBM_ANTNOISE] = 0x11,
- [IEEE80211_RADIOTAP_LOCK_QUALITY] = 0x22,
- [IEEE80211_RADIOTAP_TX_ATTENUATION] = 0x22,
- [IEEE80211_RADIOTAP_DB_TX_ATTENUATION] = 0x22,
- [IEEE80211_RADIOTAP_DBM_TX_POWER] = 0x11,
- [IEEE80211_RADIOTAP_ANTENNA] = 0x11,
- [IEEE80211_RADIOTAP_DB_ANTSIGNAL] = 0x11,
- [IEEE80211_RADIOTAP_DB_ANTNOISE] = 0x11,
- [IEEE80211_RADIOTAP_RX_FLAGS] = 0x22,
- [IEEE80211_RADIOTAP_TX_FLAGS] = 0x22,
- [IEEE80211_RADIOTAP_RTS_RETRIES] = 0x11,
- [IEEE80211_RADIOTAP_DATA_RETRIES] = 0x11,
- /*
- * add more here as they are defined in
- * include/net/ieee80211_radiotap.h
- */
- };
-
- /*
- * for every radiotap entry we can at
- * least skip (by knowing the length)...
- */
-
- while (iterator->arg_index < (int) sizeof(rt_sizes)) {
+ while (1) {
int hit = 0;
- int pad;
+ int pad, align, size, subns;
+ uint32_t oui;
- if (!(iterator->bitmap_shifter & 1))
+ /* if no more EXT bits, that's it */
+ if ((iterator->_arg_index % 32) == IEEE80211_RADIOTAP_EXT &&
+ !(iterator->_bitmap_shifter & 1))
+ return -ENOENT;
+
+ if (!(iterator->_bitmap_shifter & 1))
goto next_entry; /* arg not present */
+ /* get alignment/size of data */
+ switch (iterator->_arg_index % 32) {
+ case IEEE80211_RADIOTAP_RADIOTAP_NAMESPACE:
+ case IEEE80211_RADIOTAP_EXT:
+ align = 1;
+ size = 0;
+ break;
+ case IEEE80211_RADIOTAP_VENDOR_NAMESPACE:
+ align = 2;
+ size = 6;
+ break;
+ default:
+#ifdef RADIOTAP_SUPPORT_OVERRIDES
+ if (find_override(iterator, &align, &size)) {
+ /* all set */
+ } else
+#endif
+ if (!iterator->current_namespace ||
+ iterator->_arg_index >= iterator->current_namespace->n_bits) {
+ if (iterator->current_namespace == &radiotap_ns)
+ return -ENOENT;
+ align = 0;
+ } else {
+ align = iterator->current_namespace->align_size[iterator->_arg_index].align;
+ size = iterator->current_namespace->align_size[iterator->_arg_index].size;
+ }
+ if (!align) {
+ /* skip all subsequent data */
+ iterator->_arg = iterator->_next_ns_data;
+ /* give up on this namespace */
+ iterator->current_namespace = NULL;
+ goto next_entry;
+ }
+ break;
+ }
+
/*
* arg is present, account for alignment padding
- * 8-bit args can be at any alignment
- * 16-bit args must start on 16-bit boundary
- * 32-bit args must start on 32-bit boundary
- * 64-bit args must start on 64-bit boundary
- *
- * note that total arg size can differ from alignment of
- * elements inside arg, so we use upper nybble of length
- * table to base alignment on
*
- * also note: these alignments are ** relative to the
- * start of the radiotap header **. There is no guarantee
+ * Note that these alignments are relative to the start
+ * of the radiotap header. There is no guarantee
* that the radiotap header itself is aligned on any
* kind of boundary.
*
- * the above is why get_unaligned() is used to dereference
- * multibyte elements from the radiotap area
+ * The above is why get_unaligned() is used to dereference
+ * multibyte elements from the radiotap area.
*/
- pad = (((ulong)iterator->arg) -
- ((ulong)iterator->rtheader)) &
- ((rt_sizes[iterator->arg_index] >> 4) - 1);
+ pad = ((unsigned long)iterator->_arg -
+ (unsigned long)iterator->_rtheader) & (align - 1);
if (pad)
- iterator->arg +=
- (rt_sizes[iterator->arg_index] >> 4) - pad;
+ iterator->_arg += align - pad;
+
+ if (iterator->_arg_index % 32 == IEEE80211_RADIOTAP_VENDOR_NAMESPACE) {
+ int vnslen;
+
+ if ((unsigned long)iterator->_arg + size -
+ (unsigned long)iterator->_rtheader >
+ (unsigned long)iterator->_max_length)
+ return -EINVAL;
+
+ oui = (*iterator->_arg << 16) |
+ (*(iterator->_arg + 1) << 8) |
+ *(iterator->_arg + 2);
+ subns = *(iterator->_arg + 3);
+
+ find_ns(iterator, oui, subns);
+
+ vnslen = get_unaligned_le16(iterator->_arg + 4);
+ iterator->_next_ns_data = iterator->_arg + size + vnslen;
+ if (!iterator->current_namespace)
+ size += vnslen;
+ }
/*
* this is what we will return to user, but we need to
* move on first so next call has something fresh to test
*/
- iterator->this_arg_index = iterator->arg_index;
- iterator->this_arg = iterator->arg;
- hit = 1;
+ iterator->this_arg_index = iterator->_arg_index;
+ iterator->this_arg = iterator->_arg;
+ iterator->this_arg_size = size;
/* internally move on the size of this arg */
- iterator->arg += rt_sizes[iterator->arg_index] & 0x0f;
+ iterator->_arg += size;
/*
* check for insanity where we are given a bitmap that
@@ -257,31 +340,57 @@ int ieee80211_radiotap_iterator_next(
* max_length on the last arg, never exceeding it.
*/
- if (((ulong)iterator->arg - (ulong)iterator->rtheader) >
- (ulong) iterator->max_length)
+ if ((unsigned long)iterator->_arg -
+ (unsigned long)iterator->_rtheader >
+ (unsigned long)iterator->_max_length)
return -EINVAL;
- next_entry:
- iterator->arg_index++;
- if (unlikely((iterator->arg_index & 31) == 0)) {
- /* completed current u32 bitmap */
- if (iterator->bitmap_shifter & 1) {
- /* b31 was set, there is more */
- /* move to next u32 bitmap */
- iterator->bitmap_shifter = le32_to_cpu(
- get_unaligned(iterator->next_bitmap));
- iterator->next_bitmap++;
- } else
- /* no more bitmaps: end */
- iterator->arg_index = sizeof(rt_sizes);
- } else /* just try the next bit */
- iterator->bitmap_shifter >>= 1;
+ /* these special ones are valid in each bitmap word */
+ switch (iterator->_arg_index % 32) {
+ case IEEE80211_RADIOTAP_VENDOR_NAMESPACE:
+ iterator->_reset_on_ext = 1;
+
+ iterator->is_radiotap_ns = 0;
+ /*
+ * If parser didn't register this vendor
+ * namespace with us, allow it to show it
+ * as 'raw. Do do that, set argument index
+ * to vendor namespace.
+ */
+ iterator->this_arg_index =
+ IEEE80211_RADIOTAP_VENDOR_NAMESPACE;
+ if (!iterator->current_namespace)
+ hit = 1;
+ goto next_entry;
+ case IEEE80211_RADIOTAP_RADIOTAP_NAMESPACE:
+ iterator->_reset_on_ext = 1;
+ iterator->current_namespace = &radiotap_ns;
+ iterator->is_radiotap_ns = 1;
+ goto next_entry;
+ case IEEE80211_RADIOTAP_EXT:
+ /*
+ * bit 31 was set, there is more
+ * -- move to next u32 bitmap
+ */
+ iterator->_bitmap_shifter =
+ get_unaligned_le32(iterator->_next_bitmap);
+ iterator->_next_bitmap++;
+ if (iterator->_reset_on_ext)
+ iterator->_arg_index = 0;
+ else
+ iterator->_arg_index++;
+ iterator->_reset_on_ext = 0;
+ break;
+ default:
+ /* we've got a hit! */
+ hit = 1;
+ next_entry:
+ iterator->_bitmap_shifter >>= 1;
+ iterator->_arg_index++;
+ }
/* if we found a valid arg earlier, return it now */
if (hit)
return 0;
}
-
- /* we don't know how to handle any more args, we're done */
- return -ENOENT;
}
diff --git a/src/utils/radiotap.h b/src/utils/radiotap.h
index 137288f9a1e01..0572e7c963da7 100644
--- a/src/utils/radiotap.h
+++ b/src/utils/radiotap.h
@@ -1,6 +1,3 @@
-/* $FreeBSD: src/sys/net80211/ieee80211_radiotap.h,v 1.5 2005/01/22 20:12:05 sam Exp $ */
-/* $NetBSD: ieee80211_radiotap.h,v 1.11 2005/06/22 06:16:02 dyoung Exp $ */
-
/*-
* Copyright (c) 2003, 2004 David Young. All rights reserved.
*
@@ -178,6 +175,14 @@ struct ieee80211_radiotap_header {
*
* Number of unicast retries a transmitted frame used.
*
+ * IEEE80211_RADIOTAP_MCS u8, u8, u8 unitless
+ *
+ * Contains a bitmap of known fields/flags, the flags, and
+ * the MCS index.
+ *
+ * IEEE80211_RADIOTAP_AMPDU_STATUS u32, u16, u8, u8 unitlesss
+ *
+ * Contains the AMPDU information for the subframe.
*/
enum ieee80211_radiotap_type {
IEEE80211_RADIOTAP_TSFT = 0,
@@ -198,6 +203,13 @@ enum ieee80211_radiotap_type {
IEEE80211_RADIOTAP_TX_FLAGS = 15,
IEEE80211_RADIOTAP_RTS_RETRIES = 16,
IEEE80211_RADIOTAP_DATA_RETRIES = 17,
+
+ IEEE80211_RADIOTAP_MCS = 19,
+ IEEE80211_RADIOTAP_AMPDU_STATUS = 20,
+
+ /* valid in every it_present bitmap, even vendor namespaces */
+ IEEE80211_RADIOTAP_RADIOTAP_NAMESPACE = 29,
+ IEEE80211_RADIOTAP_VENDOR_NAMESPACE = 30,
IEEE80211_RADIOTAP_EXT = 31
};
@@ -230,8 +242,10 @@ enum ieee80211_radiotap_type {
* 802.11 header and payload
* (to 32-bit boundary)
*/
+#define IEEE80211_RADIOTAP_F_BADFCS 0x40 /* frame failed FCS check */
+
/* For IEEE80211_RADIOTAP_RX_FLAGS */
-#define IEEE80211_RADIOTAP_F_RX_BADFCS 0x0001 /* frame failed crc check */
+#define IEEE80211_RADIOTAP_F_RX_BADPLCP 0x0002 /* bad PLCP */
/* For IEEE80211_RADIOTAP_TX_FLAGS */
#define IEEE80211_RADIOTAP_F_TX_FAIL 0x0001 /* failed due to excessive
@@ -240,4 +254,38 @@ enum ieee80211_radiotap_type {
#define IEEE80211_RADIOTAP_F_TX_RTS 0x0004 /* used rts/cts handshake */
#define IEEE80211_RADIOTAP_F_TX_NOACK 0x0008 /* don't expect an ACK */
+/* For IEEE80211_RADIOTAP_AMPDU_STATUS */
+#define IEEE80211_RADIOTAP_AMPDU_REPORT_ZEROLEN 0x0001
+#define IEEE80211_RADIOTAP_AMPDU_IS_ZEROLEN 0x0002
+#define IEEE80211_RADIOTAP_AMPDU_LAST_KNOWN 0x0004
+#define IEEE80211_RADIOTAP_AMPDU_IS_LAST 0x0008
+#define IEEE80211_RADIOTAP_AMPDU_DELIM_CRC_ERR 0x0010
+#define IEEE80211_RADIOTAP_AMPDU_DELIM_CRC_KNOWN 0x0020
+
+/* For IEEE80211_RADIOTAP_MCS */
+#define IEEE80211_RADIOTAP_MCS_HAVE_BW 0x01
+#define IEEE80211_RADIOTAP_MCS_HAVE_MCS 0x02
+#define IEEE80211_RADIOTAP_MCS_HAVE_GI 0x04
+#define IEEE80211_RADIOTAP_MCS_HAVE_FMT 0x08
+#define IEEE80211_RADIOTAP_MCS_HAVE_FEC 0x10
+#define IEEE80211_RADIOTAP_MCS_HAVE_STBC 0x20
+#define IEEE80211_RADIOTAP_MCS_HAVE_NESS 0x40
+#define IEEE80211_RADIOTAP_MCS_NESS_BIT1 0x80
+
+
+#define IEEE80211_RADIOTAP_MCS_BW_MASK 0x03
+#define IEEE80211_RADIOTAP_MCS_BW_20 0
+#define IEEE80211_RADIOTAP_MCS_BW_40 1
+#define IEEE80211_RADIOTAP_MCS_BW_20L 2
+#define IEEE80211_RADIOTAP_MCS_BW_20U 3
+#define IEEE80211_RADIOTAP_MCS_SGI 0x04
+#define IEEE80211_RADIOTAP_MCS_FMT_GF 0x08
+#define IEEE80211_RADIOTAP_MCS_FEC_LDPC 0x10
+#define IEEE80211_RADIOTAP_MCS_STBC_MASK 0x60
+#define IEEE80211_RADIOTAP_MCS_STBC_SHIFT 5
+#define IEEE80211_RADIOTAP_MCS_STBC_1 1
+#define IEEE80211_RADIOTAP_MCS_STBC_2 2
+#define IEEE80211_RADIOTAP_MCS_STBC_3 3
+#define IEEE80211_RADIOTAP_MCS_NESS_BIT0 0x80
+
#endif /* IEEE80211_RADIOTAP_H */
diff --git a/src/utils/radiotap_iter.h b/src/utils/radiotap_iter.h
index 2e0e87296ef57..b768c85baace5 100644
--- a/src/utils/radiotap_iter.h
+++ b/src/utils/radiotap_iter.h
@@ -1,56 +1,96 @@
-/*
- * Radiotap parser
- *
- * Copyright 2007 Andy Green <andy@warmcat.com>
- *
- * 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 __RADIOTAP_ITER_H
#define __RADIOTAP_ITER_H
+#include <stdint.h>
#include "radiotap.h"
/* Radiotap header iteration
* implemented in radiotap.c
*/
+
+struct radiotap_override {
+ uint8_t field;
+ uint8_t align:4, size:4;
+};
+
+struct radiotap_align_size {
+ uint8_t align:4, size:4;
+};
+
+struct ieee80211_radiotap_namespace {
+ const struct radiotap_align_size *align_size;
+ int n_bits;
+ uint32_t oui;
+ uint8_t subns;
+};
+
+struct ieee80211_radiotap_vendor_namespaces {
+ const struct ieee80211_radiotap_namespace *ns;
+ int n_ns;
+};
+
/**
* struct ieee80211_radiotap_iterator - tracks walk thru present radiotap args
- * @rtheader: pointer to the radiotap header we are walking through
- * @max_length: length of radiotap header in cpu byte ordering
- * @this_arg_index: IEEE80211_RADIOTAP_... index of current arg
- * @this_arg: pointer to current radiotap arg
- * @arg_index: internal next argument index
- * @arg: internal next argument pointer
- * @next_bitmap: internal pointer to next present u32
- * @bitmap_shifter: internal shifter for curr u32 bitmap, b0 set == arg present
+ * @this_arg_index: index of current arg, valid after each successful call
+ * to ieee80211_radiotap_iterator_next()
+ * @this_arg: pointer to current radiotap arg; it is valid after each
+ * call to ieee80211_radiotap_iterator_next() but also after
+ * ieee80211_radiotap_iterator_init() where it will point to
+ * the beginning of the actual data portion
+ * @this_arg_size: length of the current arg, for convenience
+ * @current_namespace: pointer to the current namespace definition
+ * (or internally %NULL if the current namespace is unknown)
+ * @is_radiotap_ns: indicates whether the current namespace is the default
+ * radiotap namespace or not
+ *
+ * @overrides: override standard radiotap fields
+ * @n_overrides: number of overrides
+ *
+ * @_rtheader: pointer to the radiotap header we are walking through
+ * @_max_length: length of radiotap header in cpu byte ordering
+ * @_arg_index: next argument index
+ * @_arg: next argument pointer
+ * @_next_bitmap: internal pointer to next present u32
+ * @_bitmap_shifter: internal shifter for curr u32 bitmap, b0 set == arg present
+ * @_vns: vendor namespace definitions
+ * @_next_ns_data: beginning of the next namespace's data
+ * @_reset_on_ext: internal; reset the arg index to 0 when going to the
+ * next bitmap word
+ *
+ * Describes the radiotap parser state. Fields prefixed with an underscore
+ * must not be used by users of the parser, only by the parser internally.
*/
struct ieee80211_radiotap_iterator {
- struct ieee80211_radiotap_header *rtheader;
- int max_length;
- int this_arg_index;
+ struct ieee80211_radiotap_header *_rtheader;
+ const struct ieee80211_radiotap_vendor_namespaces *_vns;
+ const struct ieee80211_radiotap_namespace *current_namespace;
+
+ unsigned char *_arg, *_next_ns_data;
+ uint32_t *_next_bitmap;
+
unsigned char *this_arg;
+#ifdef RADIOTAP_SUPPORT_OVERRIDES
+ const struct radiotap_override *overrides;
+ int n_overrides;
+#endif
+ int this_arg_index;
+ int this_arg_size;
+
+ int is_radiotap_ns;
- int arg_index;
- unsigned char *arg;
- uint32_t *next_bitmap;
- uint32_t bitmap_shifter;
+ int _max_length;
+ int _arg_index;
+ uint32_t _bitmap_shifter;
+ int _reset_on_ext;
};
extern int ieee80211_radiotap_iterator_init(
- struct ieee80211_radiotap_iterator *iterator,
- struct ieee80211_radiotap_header *radiotap_header,
- int max_length);
+ struct ieee80211_radiotap_iterator *iterator,
+ struct ieee80211_radiotap_header *radiotap_header,
+ int max_length, const struct ieee80211_radiotap_vendor_namespaces *vns);
extern int ieee80211_radiotap_iterator_next(
- struct ieee80211_radiotap_iterator *iterator);
+ struct ieee80211_radiotap_iterator *iterator);
#endif /* __RADIOTAP_ITER_H */
diff --git a/src/utils/trace.c b/src/utils/trace.c
index 6795d417d5d40..8484d277d24b6 100644
--- a/src/utils/trace.c
+++ b/src/utils/trace.c
@@ -18,11 +18,9 @@ static struct dl_list active_references =
#ifdef WPA_TRACE_BFD
#include <bfd.h>
-#ifdef __linux__
-#include <demangle.h>
-#else /* __linux__ */
-#include <libiberty/demangle.h>
-#endif /* __linux__ */
+
+#define DMGL_PARAMS (1 << 0)
+#define DMGL_ANSI (1 << 1)
static char *prg_fname = NULL;
static bfd *cached_abfd = NULL;
@@ -35,7 +33,7 @@ static void get_prg_fname(void)
os_snprintf(exe, sizeof(exe) - 1, "/proc/%u/exe", getpid());
len = readlink(exe, fname, sizeof(fname) - 1);
if (len < 0 || len >= (int) sizeof(fname)) {
- perror("readlink");
+ wpa_printf(MSG_ERROR, "readlink: %s", strerror(errno));
return;
}
fname[len] = '\0';
@@ -162,7 +160,7 @@ static void wpa_trace_bfd_addr(void *pc)
if (abfd == NULL)
return;
- data.pc = (bfd_vma) pc;
+ data.pc = (bfd_hostptr_t) pc;
data.found = FALSE;
bfd_map_over_sections(abfd, find_addr_sect, &data);
@@ -187,6 +185,7 @@ static void wpa_trace_bfd_addr(void *pc)
wpa_printf(MSG_INFO, " %s() %s:%u",
name, filename, data.line);
free(aname);
+ aname = NULL;
data.found = bfd_find_inliner_info(abfd, &data.filename,
&data.function, &data.line);
@@ -202,7 +201,7 @@ static const char * wpa_trace_bfd_addr2func(void *pc)
if (abfd == NULL)
return NULL;
- data.pc = (bfd_vma) pc;
+ data.pc = (bfd_hostptr_t) pc;
data.found = FALSE;
bfd_map_over_sections(abfd, find_addr_sect, &data);
@@ -244,6 +243,53 @@ void wpa_trace_dump_funcname(const char *title, void *pc)
wpa_trace_bfd_addr(pc);
}
+
+size_t wpa_trace_calling_func(const char *buf[], size_t len)
+{
+ bfd *abfd;
+ void *btrace_res[WPA_TRACE_LEN];
+ int i, btrace_num;
+ size_t pos = 0;
+
+ if (len == 0)
+ return 0;
+ if (len > WPA_TRACE_LEN)
+ len = WPA_TRACE_LEN;
+
+ wpa_trace_bfd_init();
+ abfd = cached_abfd;
+ if (!abfd)
+ return 0;
+
+ btrace_num = backtrace(btrace_res, len);
+ if (btrace_num < 1)
+ return 0;
+
+ for (i = 0; i < btrace_num; i++) {
+ struct bfd_data data;
+
+ data.pc = (bfd_hostptr_t) btrace_res[i];
+ data.found = FALSE;
+ bfd_map_over_sections(abfd, find_addr_sect, &data);
+
+ while (data.found) {
+ if (data.function &&
+ (pos > 0 ||
+ os_strcmp(data.function, __func__) != 0)) {
+ buf[pos++] = data.function;
+ if (pos == len)
+ return pos;
+ }
+
+ data.found = bfd_find_inliner_info(abfd, &data.filename,
+ &data.function,
+ &data.line);
+ }
+ }
+
+ return pos;
+}
+
#else /* WPA_TRACE_BFD */
#define wpa_trace_bfd_init() do { } while (0)
diff --git a/src/utils/trace.h b/src/utils/trace.h
index 38f43fbfab96f..43ed86c199786 100644
--- a/src/utils/trace.h
+++ b/src/utils/trace.h
@@ -40,6 +40,7 @@ void wpa_trace_add_ref_func(struct wpa_trace_ref *ref, const void *addr);
dl_list_del(&(ptr)->wpa_trace_ref_##name.list); \
} while (0)
void wpa_trace_check_ref(const void *addr);
+size_t wpa_trace_calling_func(const char *buf[], size_t len);
#else /* WPA_TRACE */
diff --git a/src/utils/utils_module_tests.c b/src/utils/utils_module_tests.c
new file mode 100644
index 0000000000000..4b97dadd786c6
--- /dev/null
+++ b/src/utils/utils_module_tests.c
@@ -0,0 +1,423 @@
+/*
+ * utils module tests
+ * Copyright (c) 2014-2015, Jouni Malinen <j@w1.fi>
+ *
+ * This software may be distributed under the terms of the BSD license.
+ * See README for more details.
+ */
+
+#include "utils/includes.h"
+
+#include "utils/common.h"
+#include "utils/bitfield.h"
+#include "utils/ext_password.h"
+#include "utils/trace.h"
+#include "utils/base64.h"
+
+
+struct printf_test_data {
+ u8 *data;
+ size_t len;
+ char *encoded;
+};
+
+static const struct printf_test_data printf_tests[] = {
+ { (u8 *) "abcde", 5, "abcde" },
+ { (u8 *) "a\0b\nc\ed\re\tf\"\\", 13, "a\\0b\\nc\\ed\\re\\tf\\\"\\\\" },
+ { (u8 *) "\x00\x31\x00\x32\x00\x39", 6, "\\x001\\0002\\09" },
+ { (u8 *) "\n\n\n", 3, "\n\12\x0a" },
+ { (u8 *) "\303\245\303\244\303\266\303\205\303\204\303\226", 12,
+ "\\xc3\\xa5\xc3\\xa4\\xc3\\xb6\\xc3\\x85\\xc3\\x84\\xc3\\x96" },
+ { (u8 *) "\303\245\303\244\303\266\303\205\303\204\303\226", 12,
+ "\\303\\245\\303\\244\\303\\266\\303\\205\\303\\204\\303\\226" },
+ { (u8 *) "\xe5\xe4\xf6\xc5\xc4\xd6", 6,
+ "\\xe5\\xe4\\xf6\\xc5\\xc4\\xd6" },
+ { NULL, 0, NULL }
+};
+
+
+static int printf_encode_decode_tests(void)
+{
+ int i;
+ size_t binlen;
+ char buf[100];
+ u8 bin[100];
+ int errors = 0;
+
+ wpa_printf(MSG_INFO, "printf encode/decode tests");
+
+ for (i = 0; printf_tests[i].data; i++) {
+ const struct printf_test_data *test = &printf_tests[i];
+ printf_encode(buf, sizeof(buf), test->data, test->len);
+ wpa_printf(MSG_INFO, "%d: -> \"%s\"", i, buf);
+
+ binlen = printf_decode(bin, sizeof(bin), buf);
+ if (binlen != test->len ||
+ os_memcmp(bin, test->data, binlen) != 0) {
+ wpa_hexdump(MSG_ERROR, "Error in decoding#1",
+ bin, binlen);
+ errors++;
+ }
+
+ binlen = printf_decode(bin, sizeof(bin), test->encoded);
+ if (binlen != test->len ||
+ os_memcmp(bin, test->data, binlen) != 0) {
+ wpa_hexdump(MSG_ERROR, "Error in decoding#2",
+ bin, binlen);
+ errors++;
+ }
+ }
+
+ buf[5] = 'A';
+ printf_encode(buf, 5, (const u8 *) "abcde", 5);
+ if (buf[5] != 'A') {
+ wpa_printf(MSG_ERROR, "Error in bounds checking#1");
+ errors++;
+ }
+
+ for (i = 5; i < 10; i++) {
+ buf[i] = 'A';
+ printf_encode(buf, i, (const u8 *) "\xdd\xdd\xdd\xdd\xdd", 5);
+ if (buf[i] != 'A') {
+ wpa_printf(MSG_ERROR, "Error in bounds checking#2(%d)",
+ i);
+ errors++;
+ }
+ }
+
+ if (printf_decode(bin, 3, "abcde") != 2)
+ errors++;
+
+ if (printf_decode(bin, 3, "\\xa") != 1 || bin[0] != 10)
+ errors++;
+
+ if (printf_decode(bin, 3, "\\a") != 1 || bin[0] != 'a')
+ errors++;
+
+ if (errors) {
+ wpa_printf(MSG_ERROR, "%d printf test(s) failed", errors);
+ return -1;
+ }
+
+ return 0;
+}
+
+
+static int bitfield_tests(void)
+{
+ struct bitfield *bf;
+ int i;
+ int errors = 0;
+
+ wpa_printf(MSG_INFO, "bitfield tests");
+
+ bf = bitfield_alloc(123);
+ if (bf == NULL)
+ return -1;
+
+ for (i = 0; i < 123; i++) {
+ if (bitfield_is_set(bf, i) || bitfield_is_set(bf, i + 1))
+ errors++;
+ if (i > 0 && bitfield_is_set(bf, i - 1))
+ errors++;
+ bitfield_set(bf, i);
+ if (!bitfield_is_set(bf, i))
+ errors++;
+ bitfield_clear(bf, i);
+ if (bitfield_is_set(bf, i))
+ errors++;
+ }
+
+ for (i = 123; i < 200; i++) {
+ if (bitfield_is_set(bf, i) || bitfield_is_set(bf, i + 1))
+ errors++;
+ if (i > 0 && bitfield_is_set(bf, i - 1))
+ errors++;
+ bitfield_set(bf, i);
+ if (bitfield_is_set(bf, i))
+ errors++;
+ bitfield_clear(bf, i);
+ if (bitfield_is_set(bf, i))
+ errors++;
+ }
+
+ for (i = 0; i < 123; i++) {
+ if (bitfield_is_set(bf, i) || bitfield_is_set(bf, i + 1))
+ errors++;
+ bitfield_set(bf, i);
+ if (!bitfield_is_set(bf, i))
+ errors++;
+ }
+
+ for (i = 0; i < 123; i++) {
+ if (!bitfield_is_set(bf, i))
+ errors++;
+ bitfield_clear(bf, i);
+ if (bitfield_is_set(bf, i))
+ errors++;
+ }
+
+ for (i = 0; i < 123; i++) {
+ if (bitfield_get_first_zero(bf) != i)
+ errors++;
+ bitfield_set(bf, i);
+ }
+ if (bitfield_get_first_zero(bf) != -1)
+ errors++;
+ for (i = 0; i < 123; i++) {
+ if (!bitfield_is_set(bf, i))
+ errors++;
+ bitfield_clear(bf, i);
+ if (bitfield_get_first_zero(bf) != i)
+ errors++;
+ bitfield_set(bf, i);
+ }
+ if (bitfield_get_first_zero(bf) != -1)
+ errors++;
+
+ bitfield_free(bf);
+
+ bf = bitfield_alloc(8);
+ if (bf == NULL)
+ return -1;
+ if (bitfield_get_first_zero(bf) != 0)
+ errors++;
+ for (i = 0; i < 8; i++)
+ bitfield_set(bf, i);
+ if (bitfield_get_first_zero(bf) != -1)
+ errors++;
+ bitfield_free(bf);
+
+ if (errors) {
+ wpa_printf(MSG_ERROR, "%d bitfield test(s) failed", errors);
+ return -1;
+ }
+
+ return 0;
+}
+
+
+static int int_array_tests(void)
+{
+ int test1[] = { 1, 2, 3, 4, 5, 6, 0 };
+ int test2[] = { 1, -1, 0 };
+ int test3[] = { 1, 1, 1, -1, 2, 3, 4, 1, 2, 0 };
+ int test3_res[] = { -1, 1, 2, 3, 4, 0 };
+ int errors = 0;
+ int len;
+
+ wpa_printf(MSG_INFO, "int_array tests");
+
+ if (int_array_len(test1) != 6 ||
+ int_array_len(test2) != 2)
+ errors++;
+
+ int_array_sort_unique(test3);
+ len = int_array_len(test3_res);
+ if (int_array_len(test3) != len)
+ errors++;
+ else if (os_memcmp(test3, test3_res, len * sizeof(int)) != 0)
+ errors++;
+
+ if (errors) {
+ wpa_printf(MSG_ERROR, "%d int_array test(s) failed", errors);
+ return -1;
+ }
+
+ return 0;
+}
+
+
+static int ext_password_tests(void)
+{
+ struct ext_password_data *data;
+ int ret = 0;
+ struct wpabuf *pw;
+
+ wpa_printf(MSG_INFO, "ext_password tests");
+
+ data = ext_password_init("unknown", "foo");
+ if (data != NULL)
+ return -1;
+
+ data = ext_password_init("test", NULL);
+ if (data == NULL)
+ return -1;
+ pw = ext_password_get(data, "foo");
+ if (pw != NULL)
+ ret = -1;
+ ext_password_free(pw);
+
+ ext_password_deinit(data);
+
+ pw = ext_password_get(NULL, "foo");
+ if (pw != NULL)
+ ret = -1;
+ ext_password_free(pw);
+
+ return ret;
+}
+
+
+static int trace_tests(void)
+{
+ wpa_printf(MSG_INFO, "trace tests");
+
+ wpa_trace_show("test backtrace");
+ wpa_trace_dump_funcname("test funcname", trace_tests);
+
+ return 0;
+}
+
+
+static int base64_tests(void)
+{
+ int errors = 0;
+ unsigned char *res;
+ size_t res_len;
+
+ wpa_printf(MSG_INFO, "base64 tests");
+
+ res = base64_encode((const unsigned char *) "", ~0, &res_len);
+ if (res) {
+ errors++;
+ os_free(res);
+ }
+
+ res = base64_encode((const unsigned char *) "=", 1, &res_len);
+ if (!res || res_len != 5 || res[0] != 'P' || res[1] != 'Q' ||
+ res[2] != '=' || res[3] != '=' || res[4] != '\n')
+ errors++;
+ os_free(res);
+
+ res = base64_encode((const unsigned char *) "=", 1, NULL);
+ if (!res || res[0] != 'P' || res[1] != 'Q' ||
+ res[2] != '=' || res[3] != '=' || res[4] != '\n')
+ errors++;
+ os_free(res);
+
+ res = base64_decode((const unsigned char *) "", 0, &res_len);
+ if (res) {
+ errors++;
+ os_free(res);
+ }
+
+ res = base64_decode((const unsigned char *) "a", 1, &res_len);
+ if (res) {
+ errors++;
+ os_free(res);
+ }
+
+ res = base64_decode((const unsigned char *) "====", 4, &res_len);
+ if (res) {
+ errors++;
+ os_free(res);
+ }
+
+ res = base64_decode((const unsigned char *) "PQ==", 4, &res_len);
+ if (!res || res_len != 1 || res[0] != '=')
+ errors++;
+ os_free(res);
+
+ res = base64_decode((const unsigned char *) "P.Q-=!=*", 8, &res_len);
+ if (!res || res_len != 1 || res[0] != '=')
+ errors++;
+ os_free(res);
+
+ if (errors) {
+ wpa_printf(MSG_ERROR, "%d base64 test(s) failed", errors);
+ return -1;
+ }
+
+ return 0;
+}
+
+
+static int common_tests(void)
+{
+ char buf[3];
+ u8 addr[ETH_ALEN] = { 1, 2, 3, 4, 5, 6 };
+ u8 bin[3];
+ int errors = 0;
+ struct wpa_freq_range_list ranges;
+
+ wpa_printf(MSG_INFO, "common tests");
+
+ if (hwaddr_mask_txt(buf, 3, addr, addr) != -1)
+ errors++;
+
+ if (wpa_scnprintf(buf, 0, "hello") != 0 ||
+ wpa_scnprintf(buf, 3, "hello") != 2)
+ errors++;
+
+ if (wpa_snprintf_hex(buf, 0, addr, ETH_ALEN) != 0 ||
+ wpa_snprintf_hex(buf, 3, addr, ETH_ALEN) != 2)
+ errors++;
+
+ if (merge_byte_arrays(bin, 3, addr, ETH_ALEN, NULL, 0) != 3 ||
+ merge_byte_arrays(bin, 3, NULL, 0, addr, ETH_ALEN) != 3)
+ errors++;
+
+ if (dup_binstr(NULL, 0) != NULL)
+ errors++;
+
+ if (freq_range_list_includes(NULL, 0) != 0)
+ errors++;
+
+ os_memset(&ranges, 0, sizeof(ranges));
+ if (freq_range_list_parse(&ranges, "") != 0 ||
+ freq_range_list_includes(&ranges, 0) != 0 ||
+ freq_range_list_str(&ranges) != NULL)
+ errors++;
+
+ if (utf8_unescape(NULL, 0, buf, sizeof(buf)) != 0 ||
+ utf8_unescape("a", 1, NULL, 0) != 0 ||
+ utf8_unescape("a\\", 2, buf, sizeof(buf)) != 0 ||
+ utf8_unescape("abcde", 5, buf, sizeof(buf)) != 0 ||
+ utf8_unescape("abc", 3, buf, 3) != 3)
+ errors++;
+
+ if (utf8_unescape("a", 0, buf, sizeof(buf)) != 1 || buf[0] != 'a')
+ errors++;
+
+ if (utf8_unescape("\\b", 2, buf, sizeof(buf)) != 1 || buf[0] != 'b')
+ errors++;
+
+ if (utf8_escape(NULL, 0, buf, sizeof(buf)) != 0 ||
+ utf8_escape("a", 1, NULL, 0) != 0 ||
+ utf8_escape("abcde", 5, buf, sizeof(buf)) != 0 ||
+ utf8_escape("a\\bcde", 6, buf, sizeof(buf)) != 0 ||
+ utf8_escape("ab\\cde", 6, buf, sizeof(buf)) != 0 ||
+ utf8_escape("abc\\de", 6, buf, sizeof(buf)) != 0 ||
+ utf8_escape("abc", 3, buf, 3) != 3)
+ errors++;
+
+ if (utf8_escape("a", 0, buf, sizeof(buf)) != 1 || buf[0] != 'a')
+ errors++;
+
+ if (errors) {
+ wpa_printf(MSG_ERROR, "%d common test(s) failed", errors);
+ return -1;
+ }
+
+ return 0;
+}
+
+
+int utils_module_tests(void)
+{
+ int ret = 0;
+
+ wpa_printf(MSG_INFO, "utils module tests");
+
+ if (printf_encode_decode_tests() < 0 ||
+ ext_password_tests() < 0 ||
+ trace_tests() < 0 ||
+ bitfield_tests() < 0 ||
+ base64_tests() < 0 ||
+ common_tests() < 0 ||
+ int_array_tests() < 0)
+ ret = -1;
+
+ return ret;
+}
diff --git a/src/utils/uuid.c b/src/utils/uuid.c
index 2aa4bcb5fa19d..0f224f976b803 100644
--- a/src/utils/uuid.c
+++ b/src/utils/uuid.c
@@ -55,7 +55,7 @@ int uuid_bin2str(const u8 *bin, char *str, size_t max_len)
bin[4], bin[5], bin[6], bin[7],
bin[8], bin[9], bin[10], bin[11],
bin[12], bin[13], bin[14], bin[15]);
- if (len < 0 || (size_t) len >= max_len)
+ if (os_snprintf_error(max_len, len))
return -1;
return 0;
}
diff --git a/src/utils/wpa_debug.c b/src/utils/wpa_debug.c
index 5511ef193b0c6..0d11905185365 100644
--- a/src/utils/wpa_debug.c
+++ b/src/utils/wpa_debug.c
@@ -1,6 +1,6 @@
/*
* wpa_supplicant/hostapd / Debug prints
- * Copyright (c) 2002-2007, Jouni Malinen <j@w1.fi>
+ * Copyright (c) 2002-2013, Jouni Malinen <j@w1.fi>
*
* This software may be distributed under the terms of the BSD license.
* See README for more details.
@@ -375,19 +375,19 @@ static void _wpa_hexdump(int level, const char *title, const u8 *buf,
#endif /* CONFIG_ANDROID_LOG */
}
-void wpa_hexdump(int level, const char *title, const u8 *buf, size_t len)
+void wpa_hexdump(int level, const char *title, const void *buf, size_t len)
{
_wpa_hexdump(level, title, buf, len, 1);
}
-void wpa_hexdump_key(int level, const char *title, const u8 *buf, size_t len)
+void wpa_hexdump_key(int level, const char *title, const void *buf, size_t len)
{
_wpa_hexdump(level, title, buf, len, wpa_debug_show_keys);
}
-static void _wpa_hexdump_ascii(int level, const char *title, const u8 *buf,
+static void _wpa_hexdump_ascii(int level, const char *title, const void *buf,
size_t len, int show)
{
size_t i, llen;
@@ -407,7 +407,7 @@ static void _wpa_hexdump_ascii(int level, const char *title, const u8 *buf,
/* can do ascii processing in userspace */
for (i = 0; i < len; i++)
fprintf(wpa_debug_tracing_file,
- " %02x", buf[i]);
+ " %02x", pos[i]);
}
fflush(wpa_debug_tracing_file);
}
@@ -495,13 +495,14 @@ static void _wpa_hexdump_ascii(int level, const char *title, const u8 *buf,
}
-void wpa_hexdump_ascii(int level, const char *title, const u8 *buf, size_t len)
+void wpa_hexdump_ascii(int level, const char *title, const void *buf,
+ size_t len)
{
_wpa_hexdump_ascii(level, title, buf, len, 1);
}
-void wpa_hexdump_ascii_key(int level, const char *title, const u8 *buf,
+void wpa_hexdump_ascii_key(int level, const char *title, const void *buf,
size_t len)
{
_wpa_hexdump_ascii(level, title, buf, len, wpa_debug_show_keys);
@@ -554,6 +555,8 @@ int wpa_debug_open_file(const char *path)
#ifndef _WIN32
setvbuf(out_file, NULL, _IOLBF, 0);
#endif /* _WIN32 */
+#else /* CONFIG_DEBUG_FILE */
+ (void)path;
#endif /* CONFIG_DEBUG_FILE */
return 0;
}
@@ -571,6 +574,14 @@ void wpa_debug_close_file(void)
#endif /* CONFIG_DEBUG_FILE */
}
+
+void wpa_debug_setup_stdout(void)
+{
+#ifndef _WIN32
+ setvbuf(stdout, NULL, _IOLBF, 0);
+#endif /* _WIN32 */
+}
+
#endif /* CONFIG_NO_STDOUT_DEBUG */
@@ -595,10 +606,14 @@ void wpa_msg(void *ctx, int level, const char *fmt, ...)
{
va_list ap;
char *buf;
- const int buflen = 2048;
+ int buflen;
int len;
char prefix[130];
+ va_start(ap, fmt);
+ buflen = vsnprintf(NULL, 0, fmt, ap) + 1;
+ va_end(ap);
+
buf = os_malloc(buflen);
if (buf == NULL) {
wpa_printf(MSG_ERROR, "wpa_msg: Failed to allocate message "
@@ -612,7 +627,7 @@ void wpa_msg(void *ctx, int level, const char *fmt, ...)
if (ifname) {
int res = os_snprintf(prefix, sizeof(prefix), "%s: ",
ifname);
- if (res < 0 || res >= (int) sizeof(prefix))
+ if (os_snprintf_error(sizeof(prefix), res))
prefix[0] = '\0';
}
}
@@ -620,7 +635,7 @@ void wpa_msg(void *ctx, int level, const char *fmt, ...)
va_end(ap);
wpa_printf(level, "%s%s", prefix, buf);
if (wpa_msg_cb)
- wpa_msg_cb(ctx, level, buf, len);
+ wpa_msg_cb(ctx, level, 0, buf, len);
os_free(buf);
}
@@ -629,12 +644,16 @@ void wpa_msg_ctrl(void *ctx, int level, const char *fmt, ...)
{
va_list ap;
char *buf;
- const int buflen = 2048;
+ int buflen;
int len;
if (!wpa_msg_cb)
return;
+ va_start(ap, fmt);
+ buflen = vsnprintf(NULL, 0, fmt, ap) + 1;
+ va_end(ap);
+
buf = os_malloc(buflen);
if (buf == NULL) {
wpa_printf(MSG_ERROR, "wpa_msg_ctrl: Failed to allocate "
@@ -644,9 +663,92 @@ void wpa_msg_ctrl(void *ctx, int level, const char *fmt, ...)
va_start(ap, fmt);
len = vsnprintf(buf, buflen, fmt, ap);
va_end(ap);
- wpa_msg_cb(ctx, level, buf, len);
+ wpa_msg_cb(ctx, level, 0, buf, len);
+ os_free(buf);
+}
+
+
+void wpa_msg_global(void *ctx, int level, const char *fmt, ...)
+{
+ va_list ap;
+ char *buf;
+ int buflen;
+ int len;
+
+ va_start(ap, fmt);
+ buflen = vsnprintf(NULL, 0, fmt, ap) + 1;
+ va_end(ap);
+
+ buf = os_malloc(buflen);
+ if (buf == NULL) {
+ wpa_printf(MSG_ERROR, "wpa_msg_global: Failed to allocate "
+ "message buffer");
+ return;
+ }
+ va_start(ap, fmt);
+ len = vsnprintf(buf, buflen, fmt, ap);
+ va_end(ap);
+ wpa_printf(level, "%s", buf);
+ if (wpa_msg_cb)
+ wpa_msg_cb(ctx, level, 1, buf, len);
+ os_free(buf);
+}
+
+
+void wpa_msg_global_ctrl(void *ctx, int level, const char *fmt, ...)
+{
+ va_list ap;
+ char *buf;
+ int buflen;
+ int len;
+
+ if (!wpa_msg_cb)
+ return;
+
+ va_start(ap, fmt);
+ buflen = vsnprintf(NULL, 0, fmt, ap) + 1;
+ va_end(ap);
+
+ buf = os_malloc(buflen);
+ if (buf == NULL) {
+ wpa_printf(MSG_ERROR,
+ "wpa_msg_global_ctrl: Failed to allocate message buffer");
+ return;
+ }
+ va_start(ap, fmt);
+ len = vsnprintf(buf, buflen, fmt, ap);
+ va_end(ap);
+ wpa_msg_cb(ctx, level, 1, buf, len);
+ os_free(buf);
+}
+
+
+void wpa_msg_no_global(void *ctx, int level, const char *fmt, ...)
+{
+ va_list ap;
+ char *buf;
+ int buflen;
+ int len;
+
+ va_start(ap, fmt);
+ buflen = vsnprintf(NULL, 0, fmt, ap) + 1;
+ va_end(ap);
+
+ buf = os_malloc(buflen);
+ if (buf == NULL) {
+ wpa_printf(MSG_ERROR, "wpa_msg_no_global: Failed to allocate "
+ "message buffer");
+ return;
+ }
+ va_start(ap, fmt);
+ len = vsnprintf(buf, buflen, fmt, ap);
+ va_end(ap);
+ wpa_printf(level, "%s", buf);
+ if (wpa_msg_cb)
+ wpa_msg_cb(ctx, level, 2, buf, len);
os_free(buf);
}
+
#endif /* CONFIG_NO_WPA_MSG */
@@ -664,9 +766,13 @@ void hostapd_logger(void *ctx, const u8 *addr, unsigned int module, int level,
{
va_list ap;
char *buf;
- const int buflen = 2048;
+ int buflen;
int len;
+ va_start(ap, fmt);
+ buflen = vsnprintf(NULL, 0, fmt, ap) + 1;
+ va_end(ap);
+
buf = os_malloc(buflen);
if (buf == NULL) {
wpa_printf(MSG_ERROR, "hostapd_logger: Failed to allocate "
diff --git a/src/utils/wpa_debug.h b/src/utils/wpa_debug.h
index 339c749ce5820..400bea9e599fd 100644
--- a/src/utils/wpa_debug.h
+++ b/src/utils/wpa_debug.h
@@ -1,6 +1,6 @@
/*
* wpa_supplicant/hostapd / Debug prints
- * Copyright (c) 2002-2007, Jouni Malinen <j@w1.fi>
+ * Copyright (c) 2002-2013, Jouni Malinen <j@w1.fi>
*
* This software may be distributed under the terms of the BSD license.
* See README for more details.
@@ -11,6 +11,10 @@
#include "wpabuf.h"
+extern int wpa_debug_level;
+extern int wpa_debug_show_keys;
+extern int wpa_debug_timestamp;
+
/* Debugging function - conditional printf and hex dump. Driver wrappers can
* use these for debugging purposes. */
@@ -30,6 +34,7 @@ enum {
#define wpa_hexdump_ascii_key(l,t,b,le) do { } while (0)
#define wpa_debug_open_file(p) do { } while (0)
#define wpa_debug_close_file() do { } while (0)
+#define wpa_debug_setup_stdout() do { } while (0)
#define wpa_dbg(args...) do { } while (0)
static inline int wpa_debug_reopen_file(void)
@@ -42,6 +47,7 @@ static inline int wpa_debug_reopen_file(void)
int wpa_debug_open_file(const char *path);
int wpa_debug_reopen_file(void);
void wpa_debug_close_file(void);
+void wpa_debug_setup_stdout(void);
/**
* wpa_debug_printf_timestamp - Print timestamp for debug output
@@ -77,7 +83,7 @@ PRINTF_FORMAT(2, 3);
* output may be directed to stdout, stderr, and/or syslog based on
* configuration. The contents of buf is printed out has hex dump.
*/
-void wpa_hexdump(int level, const char *title, const u8 *buf, size_t len);
+void wpa_hexdump(int level, const char *title, const void *buf, size_t len);
static inline void wpa_hexdump_buf(int level, const char *title,
const struct wpabuf *buf)
@@ -99,7 +105,7 @@ static inline void wpa_hexdump_buf(int level, const char *title,
* like wpa_hexdump(), but by default, does not include secret keys (passwords,
* etc.) in debug output.
*/
-void wpa_hexdump_key(int level, const char *title, const u8 *buf, size_t len);
+void wpa_hexdump_key(int level, const char *title, const void *buf, size_t len);
static inline void wpa_hexdump_buf_key(int level, const char *title,
const struct wpabuf *buf)
@@ -121,7 +127,7 @@ static inline void wpa_hexdump_buf_key(int level, const char *title,
* the hex numbers and ASCII characters (for printable range) are shown. 16
* bytes per line will be shown.
*/
-void wpa_hexdump_ascii(int level, const char *title, const u8 *buf,
+void wpa_hexdump_ascii(int level, const char *title, const void *buf,
size_t len);
/**
@@ -138,7 +144,7 @@ void wpa_hexdump_ascii(int level, const char *title, const u8 *buf,
* bytes per line will be shown. This works like wpa_hexdump_ascii(), but by
* default, does not include secret keys (passwords, etc.) in debug output.
*/
-void wpa_hexdump_ascii_key(int level, const char *title, const u8 *buf,
+void wpa_hexdump_ascii_key(int level, const char *title, const void *buf,
size_t len);
/*
@@ -155,6 +161,9 @@ void wpa_hexdump_ascii_key(int level, const char *title, const u8 *buf,
#ifdef CONFIG_NO_WPA_MSG
#define wpa_msg(args...) do { } while (0)
#define wpa_msg_ctrl(args...) do { } while (0)
+#define wpa_msg_global(args...) do { } while (0)
+#define wpa_msg_global_ctrl(args...) do { } while (0)
+#define wpa_msg_no_global(args...) do { } while (0)
#define wpa_msg_register_cb(f) do { } while (0)
#define wpa_msg_register_ifname_cb(f) do { } while (0)
#else /* CONFIG_NO_WPA_MSG */
@@ -189,8 +198,53 @@ void wpa_msg(void *ctx, int level, const char *fmt, ...) PRINTF_FORMAT(3, 4);
void wpa_msg_ctrl(void *ctx, int level, const char *fmt, ...)
PRINTF_FORMAT(3, 4);
-typedef void (*wpa_msg_cb_func)(void *ctx, int level, const char *txt,
- size_t len);
+/**
+ * wpa_msg_global - Global printf for ctrl_iface monitors
+ * @ctx: Pointer to context data; this is the ctx variable registered
+ * with struct wpa_driver_ops::init()
+ * @level: priority level (MSG_*) of the message
+ * @fmt: printf format string, followed by optional arguments
+ *
+ * This function is used to print conditional debugging and error messages.
+ * This function is like wpa_msg(), but it sends the output as a global event,
+ * i.e., without being specific to an interface. For backwards compatibility,
+ * an old style event is also delivered on one of the interfaces (the one
+ * specified by the context data).
+ */
+void wpa_msg_global(void *ctx, int level, const char *fmt, ...)
+PRINTF_FORMAT(3, 4);
+
+/**
+ * wpa_msg_global_ctrl - Conditional global printf for ctrl_iface monitors
+ * @ctx: Pointer to context data; this is the ctx variable registered
+ * with struct wpa_driver_ops::init()
+ * @level: priority level (MSG_*) of the message
+ * @fmt: printf format string, followed by optional arguments
+ *
+ * This function is used to print conditional debugging and error messages.
+ * This function is like wpa_msg_global(), but it sends the output only to the
+ * attached global ctrl_iface monitors. In other words, it can be used for
+ * frequent events that do not need to be sent to syslog.
+ */
+void wpa_msg_global_ctrl(void *ctx, int level, const char *fmt, ...)
+PRINTF_FORMAT(3, 4);
+
+/**
+ * wpa_msg_no_global - Conditional printf for ctrl_iface monitors
+ * @ctx: Pointer to context data; this is the ctx variable registered
+ * with struct wpa_driver_ops::init()
+ * @level: priority level (MSG_*) of the message
+ * @fmt: printf format string, followed by optional arguments
+ *
+ * This function is used to print conditional debugging and error messages.
+ * This function is like wpa_msg(), but it does not send the output as a global
+ * event.
+ */
+void wpa_msg_no_global(void *ctx, int level, const char *fmt, ...)
+PRINTF_FORMAT(3, 4);
+
+typedef void (*wpa_msg_cb_func)(void *ctx, int level, int global,
+ const char *txt, size_t len);
/**
* wpa_msg_register_cb - Register callback function for wpa_msg() messages
diff --git a/src/utils/wpabuf.c b/src/utils/wpabuf.c
index b257b365c756c..7aafa0a5169ba 100644
--- a/src/utils/wpabuf.c
+++ b/src/utils/wpabuf.c
@@ -205,6 +205,15 @@ void wpabuf_free(struct wpabuf *buf)
}
+void wpabuf_clear_free(struct wpabuf *buf)
+{
+ if (buf) {
+ os_memset(wpabuf_mhead(buf), 0, wpabuf_len(buf));
+ wpabuf_free(buf);
+ }
+}
+
+
void * wpabuf_put(struct wpabuf *buf, size_t len)
{
void *tmp = wpabuf_mhead_u8(buf) + wpabuf_len(buf);
diff --git a/src/utils/wpabuf.h b/src/utils/wpabuf.h
index dbce925ca1bbb..c3ef1bae3667a 100644
--- a/src/utils/wpabuf.h
+++ b/src/utils/wpabuf.h
@@ -32,6 +32,7 @@ struct wpabuf * wpabuf_alloc_ext_data(u8 *data, size_t len);
struct wpabuf * wpabuf_alloc_copy(const void *data, size_t len);
struct wpabuf * wpabuf_dup(const struct wpabuf *src);
void wpabuf_free(struct wpabuf *buf);
+void wpabuf_clear_free(struct wpabuf *buf);
void * wpabuf_put(struct wpabuf *buf, size_t len);
struct wpabuf * wpabuf_concat(struct wpabuf *a, struct wpabuf *b);
struct wpabuf * wpabuf_zeropad(struct wpabuf *buf, size_t len);
diff --git a/src/utils/xml-utils.c b/src/utils/xml-utils.c
new file mode 100644
index 0000000000000..4916d29765f91
--- /dev/null
+++ b/src/utils/xml-utils.c
@@ -0,0 +1,471 @@
+/*
+ * Generic XML helper functions
+ * Copyright (c) 2012-2013, Qualcomm Atheros, Inc.
+ *
+ * This software may be distributed under the terms of the BSD license.
+ * See README for more details.
+ */
+
+#include "includes.h"
+
+#include "common.h"
+#include "xml-utils.h"
+
+
+static xml_node_t * get_node_uri_iter(struct xml_node_ctx *ctx,
+ xml_node_t *root, char *uri)
+{
+ char *end;
+ xml_node_t *node;
+ const char *name;
+
+ end = strchr(uri, '/');
+ if (end)
+ *end++ = '\0';
+
+ node = root;
+ xml_node_for_each_sibling(ctx, node) {
+ xml_node_for_each_check(ctx, node);
+ name = xml_node_get_localname(ctx, node);
+ if (strcasecmp(name, uri) == 0)
+ break;
+ }
+
+ if (node == NULL)
+ return NULL;
+
+ if (end) {
+ return get_node_uri_iter(ctx, xml_node_first_child(ctx, node),
+ end);
+ }
+
+ return node;
+}
+
+
+xml_node_t * get_node_uri(struct xml_node_ctx *ctx, xml_node_t *root,
+ const char *uri)
+{
+ char *search;
+ xml_node_t *node;
+
+ search = os_strdup(uri);
+ if (search == NULL)
+ return NULL;
+
+ node = get_node_uri_iter(ctx, root, search);
+
+ os_free(search);
+ return node;
+}
+
+
+static xml_node_t * get_node_iter(struct xml_node_ctx *ctx,
+ xml_node_t *root, const char *path)
+{
+ char *end;
+ xml_node_t *node;
+ const char *name;
+
+ end = os_strchr(path, '/');
+ if (end)
+ *end++ = '\0';
+
+ xml_node_for_each_child(ctx, node, root) {
+ xml_node_for_each_check(ctx, node);
+ name = xml_node_get_localname(ctx, node);
+ if (os_strcasecmp(name, path) == 0)
+ break;
+ }
+
+ if (node == NULL)
+ return NULL;
+ if (end)
+ return get_node_iter(ctx, node, end);
+ return node;
+}
+
+
+xml_node_t * get_node(struct xml_node_ctx *ctx, xml_node_t *root,
+ const char *path)
+{
+ char *search;
+ xml_node_t *node;
+
+ search = os_strdup(path);
+ if (search == NULL)
+ return NULL;
+
+ node = get_node_iter(ctx, root, search);
+
+ os_free(search);
+ return node;
+}
+
+
+xml_node_t * get_child_node(struct xml_node_ctx *ctx, xml_node_t *root,
+ const char *path)
+{
+ xml_node_t *node;
+ xml_node_t *match;
+
+ xml_node_for_each_child(ctx, node, root) {
+ xml_node_for_each_check(ctx, node);
+ match = get_node(ctx, node, path);
+ if (match)
+ return match;
+ }
+
+ return NULL;
+}
+
+
+xml_node_t * node_from_file(struct xml_node_ctx *ctx, const char *name)
+{
+ xml_node_t *node;
+ char *buf, *buf2, *start;
+ size_t len;
+
+ buf = os_readfile(name, &len);
+ if (buf == NULL)
+ return NULL;
+ buf2 = os_realloc(buf, len + 1);
+ if (buf2 == NULL) {
+ os_free(buf);
+ return NULL;
+ }
+ buf = buf2;
+ buf[len] = '\0';
+
+ start = os_strstr(buf, "<!DOCTYPE ");
+ if (start) {
+ char *pos = start + 1;
+ int count = 1;
+ while (*pos) {
+ if (*pos == '<')
+ count++;
+ else if (*pos == '>') {
+ count--;
+ if (count == 0) {
+ pos++;
+ break;
+ }
+ }
+ pos++;
+ }
+ if (count == 0) {
+ /* Remove DOCTYPE to allow the file to be parsed */
+ os_memset(start, ' ', pos - start);
+ }
+ }
+
+ node = xml_node_from_buf(ctx, buf);
+ os_free(buf);
+
+ return node;
+}
+
+
+int node_to_file(struct xml_node_ctx *ctx, const char *fname, xml_node_t *node)
+{
+ FILE *f;
+ char *str;
+
+ str = xml_node_to_str(ctx, node);
+ if (str == NULL)
+ return -1;
+
+ f = fopen(fname, "w");
+ if (!f) {
+ os_free(str);
+ return -1;
+ }
+
+ fprintf(f, "%s\n", str);
+ os_free(str);
+ fclose(f);
+
+ return 0;
+}
+
+
+static char * get_val(struct xml_node_ctx *ctx, xml_node_t *node)
+{
+ char *val, *pos;
+
+ val = xml_node_get_text(ctx, node);
+ if (val == NULL)
+ return NULL;
+ pos = val;
+ while (*pos) {
+ if (*pos != ' ' && *pos != '\t' && *pos != '\r' && *pos != '\n')
+ return val;
+ pos++;
+ }
+
+ return NULL;
+}
+
+
+static char * add_path(const char *prev, const char *leaf)
+{
+ size_t len;
+ char *new_uri;
+
+ if (prev == NULL)
+ return NULL;
+
+ len = os_strlen(prev) + 1 + os_strlen(leaf) + 1;
+ new_uri = os_malloc(len);
+ if (new_uri)
+ os_snprintf(new_uri, len, "%s/%s", prev, leaf);
+
+ return new_uri;
+}
+
+
+static void node_to_tnds(struct xml_node_ctx *ctx, xml_node_t *out,
+ xml_node_t *in, const char *uri)
+{
+ xml_node_t *node;
+ xml_node_t *tnds;
+ const char *name;
+ char *val;
+ char *new_uri;
+
+ xml_node_for_each_child(ctx, node, in) {
+ xml_node_for_each_check(ctx, node);
+ name = xml_node_get_localname(ctx, node);
+
+ tnds = xml_node_create(ctx, out, NULL, "Node");
+ if (tnds == NULL)
+ return;
+ xml_node_create_text(ctx, tnds, NULL, "NodeName", name);
+
+ if (uri)
+ xml_node_create_text(ctx, tnds, NULL, "Path", uri);
+
+ val = get_val(ctx, node);
+ if (val) {
+ xml_node_create_text(ctx, tnds, NULL, "Value", val);
+ xml_node_get_text_free(ctx, val);
+ }
+
+ new_uri = add_path(uri, name);
+ node_to_tnds(ctx, new_uri ? out : tnds, node, new_uri);
+ os_free(new_uri);
+ }
+}
+
+
+static int add_ddfname(struct xml_node_ctx *ctx, xml_node_t *parent,
+ const char *urn)
+{
+ xml_node_t *node;
+
+ node = xml_node_create(ctx, parent, NULL, "RTProperties");
+ if (node == NULL)
+ return -1;
+ node = xml_node_create(ctx, node, NULL, "Type");
+ if (node == NULL)
+ return -1;
+ xml_node_create_text(ctx, node, NULL, "DDFName", urn);
+ return 0;
+}
+
+
+xml_node_t * mo_to_tnds(struct xml_node_ctx *ctx, xml_node_t *mo,
+ int use_path, const char *urn, const char *ns_uri)
+{
+ xml_node_t *root;
+ xml_node_t *node;
+ const char *name;
+
+ root = xml_node_create_root(ctx, ns_uri, NULL, NULL, "MgmtTree");
+ if (root == NULL)
+ return NULL;
+
+ xml_node_create_text(ctx, root, NULL, "VerDTD", "1.2");
+
+ name = xml_node_get_localname(ctx, mo);
+
+ node = xml_node_create(ctx, root, NULL, "Node");
+ if (node == NULL)
+ goto fail;
+ xml_node_create_text(ctx, node, NULL, "NodeName", name);
+ if (urn)
+ add_ddfname(ctx, node, urn);
+
+ node_to_tnds(ctx, use_path ? root : node, mo, use_path ? name : NULL);
+
+ return root;
+
+fail:
+ xml_node_free(ctx, root);
+ return NULL;
+}
+
+
+static xml_node_t * get_first_child_node(struct xml_node_ctx *ctx,
+ xml_node_t *node,
+ const char *name)
+{
+ const char *lname;
+ xml_node_t *child;
+
+ xml_node_for_each_child(ctx, child, node) {
+ xml_node_for_each_check(ctx, child);
+ lname = xml_node_get_localname(ctx, child);
+ if (os_strcasecmp(lname, name) == 0)
+ return child;
+ }
+
+ return NULL;
+}
+
+
+static char * get_node_text(struct xml_node_ctx *ctx, xml_node_t *node,
+ const char *node_name)
+{
+ node = get_first_child_node(ctx, node, node_name);
+ if (node == NULL)
+ return NULL;
+ return xml_node_get_text(ctx, node);
+}
+
+
+static xml_node_t * add_mo_node(struct xml_node_ctx *ctx, xml_node_t *root,
+ xml_node_t *node, const char *uri)
+{
+ char *nodename, *value, *path;
+ xml_node_t *parent;
+
+ nodename = get_node_text(ctx, node, "NodeName");
+ if (nodename == NULL)
+ return NULL;
+ value = get_node_text(ctx, node, "Value");
+
+ if (root == NULL) {
+ root = xml_node_create_root(ctx, NULL, NULL, NULL,
+ nodename);
+ if (root && value)
+ xml_node_set_text(ctx, root, value);
+ } else {
+ if (uri == NULL) {
+ xml_node_get_text_free(ctx, nodename);
+ xml_node_get_text_free(ctx, value);
+ return NULL;
+ }
+ path = get_node_text(ctx, node, "Path");
+ if (path)
+ uri = path;
+ parent = get_node_uri(ctx, root, uri);
+ xml_node_get_text_free(ctx, path);
+ if (parent == NULL) {
+ printf("Could not find URI '%s'\n", uri);
+ xml_node_get_text_free(ctx, nodename);
+ xml_node_get_text_free(ctx, value);
+ return NULL;
+ }
+ if (value)
+ xml_node_create_text(ctx, parent, NULL, nodename,
+ value);
+ else
+ xml_node_create(ctx, parent, NULL, nodename);
+ }
+
+ xml_node_get_text_free(ctx, nodename);
+ xml_node_get_text_free(ctx, value);
+
+ return root;
+}
+
+
+static xml_node_t * tnds_to_mo_iter(struct xml_node_ctx *ctx, xml_node_t *root,
+ xml_node_t *node, const char *uri)
+{
+ xml_node_t *child;
+ const char *name;
+ char *nodename;
+
+ xml_node_for_each_sibling(ctx, node) {
+ xml_node_for_each_check(ctx, node);
+
+ nodename = get_node_text(ctx, node, "NodeName");
+ if (nodename == NULL)
+ return NULL;
+
+ name = xml_node_get_localname(ctx, node);
+ if (strcmp(name, "Node") == 0) {
+ if (root && !uri) {
+ printf("Invalid TNDS tree structure - "
+ "multiple top level nodes\n");
+ xml_node_get_text_free(ctx, nodename);
+ return NULL;
+ }
+ root = add_mo_node(ctx, root, node, uri);
+ }
+
+ child = get_first_child_node(ctx, node, "Node");
+ if (child) {
+ if (uri == NULL)
+ tnds_to_mo_iter(ctx, root, child, nodename);
+ else {
+ char *new_uri;
+ new_uri = add_path(uri, nodename);
+ tnds_to_mo_iter(ctx, root, child, new_uri);
+ os_free(new_uri);
+ }
+ }
+ xml_node_get_text_free(ctx, nodename);
+ }
+
+ return root;
+}
+
+
+xml_node_t * tnds_to_mo(struct xml_node_ctx *ctx, xml_node_t *tnds)
+{
+ const char *name;
+ xml_node_t *node;
+
+ name = xml_node_get_localname(ctx, tnds);
+ if (name == NULL || os_strcmp(name, "MgmtTree") != 0)
+ return NULL;
+
+ node = get_first_child_node(ctx, tnds, "Node");
+ if (!node)
+ return NULL;
+ return tnds_to_mo_iter(ctx, NULL, node, NULL);
+}
+
+
+xml_node_t * soap_build_envelope(struct xml_node_ctx *ctx, xml_node_t *node)
+{
+ xml_node_t *envelope, *body;
+ xml_namespace_t *ns;
+
+ envelope = xml_node_create_root(
+ ctx, "http://www.w3.org/2003/05/soap-envelope", "soap12", &ns,
+ "Envelope");
+ if (envelope == NULL)
+ return NULL;
+ body = xml_node_create(ctx, envelope, ns, "Body");
+ xml_node_add_child(ctx, body, node);
+ return envelope;
+}
+
+
+xml_node_t * soap_get_body(struct xml_node_ctx *ctx, xml_node_t *soap)
+{
+ xml_node_t *body, *child;
+
+ body = get_node_uri(ctx, soap, "Envelope/Body");
+ if (body == NULL)
+ return NULL;
+ xml_node_for_each_child(ctx, child, body) {
+ xml_node_for_each_check(ctx, child);
+ return child;
+ }
+ return NULL;
+}
diff --git a/src/utils/xml-utils.h b/src/utils/xml-utils.h
new file mode 100644
index 0000000000000..fb6208cdac323
--- /dev/null
+++ b/src/utils/xml-utils.h
@@ -0,0 +1,97 @@
+/*
+ * Generic XML helper functions
+ * Copyright (c) 2012-2013, Qualcomm Atheros, Inc.
+ *
+ * This software may be distributed under the terms of the BSD license.
+ * See README for more details.
+ */
+
+#ifndef XML_UTILS_H
+#define XML_UTILS_H
+
+struct xml_node_ctx;
+typedef struct xml_node xml_node_t;
+typedef struct xml_namespace_foo xml_namespace_t;
+
+/* XML library wrappers */
+
+int xml_validate(struct xml_node_ctx *ctx, xml_node_t *node,
+ const char *xml_schema_fname, char **ret_err);
+int xml_validate_dtd(struct xml_node_ctx *ctx, xml_node_t *node,
+ const char *dtd_fname, char **ret_err);
+void xml_node_free(struct xml_node_ctx *ctx, xml_node_t *node);
+xml_node_t * xml_node_get_parent(struct xml_node_ctx *ctx, xml_node_t *node);
+xml_node_t * xml_node_from_buf(struct xml_node_ctx *ctx, const char *buf);
+const char * xml_node_get_localname(struct xml_node_ctx *ctx,
+ xml_node_t *node);
+char * xml_node_to_str(struct xml_node_ctx *ctx, xml_node_t *node);
+void xml_node_detach(struct xml_node_ctx *ctx, xml_node_t *node);
+void xml_node_add_child(struct xml_node_ctx *ctx, xml_node_t *parent,
+ xml_node_t *child);
+xml_node_t * xml_node_create_root(struct xml_node_ctx *ctx, const char *ns_uri,
+ const char *ns_prefix,
+ xml_namespace_t **ret_ns, const char *name);
+xml_node_t * xml_node_create(struct xml_node_ctx *ctx, xml_node_t *parent,
+ xml_namespace_t *ns, const char *name);
+xml_node_t * xml_node_create_text(struct xml_node_ctx *ctx,
+ xml_node_t *parent, xml_namespace_t *ns,
+ const char *name, const char *value);
+xml_node_t * xml_node_create_text_ns(struct xml_node_ctx *ctx,
+ xml_node_t *parent, const char *ns_uri,
+ const char *name, const char *value);
+void xml_node_set_text(struct xml_node_ctx *ctx, xml_node_t *node,
+ const char *value);
+int xml_node_add_attr(struct xml_node_ctx *ctx, xml_node_t *node,
+ xml_namespace_t *ns, const char *name, const char *value);
+char * xml_node_get_attr_value(struct xml_node_ctx *ctx, xml_node_t *node,
+ char *name);
+char * xml_node_get_attr_value_ns(struct xml_node_ctx *ctx, xml_node_t *node,
+ const char *ns_uri, char *name);
+void xml_node_get_attr_value_free(struct xml_node_ctx *ctx, char *val);
+xml_node_t * xml_node_first_child(struct xml_node_ctx *ctx,
+ xml_node_t *parent);
+xml_node_t * xml_node_next_sibling(struct xml_node_ctx *ctx,
+ xml_node_t *node);
+int xml_node_is_element(struct xml_node_ctx *ctx, xml_node_t *node);
+char * xml_node_get_text(struct xml_node_ctx *ctx, xml_node_t *node);
+void xml_node_get_text_free(struct xml_node_ctx *ctx, char *val);
+char * xml_node_get_base64_text(struct xml_node_ctx *ctx, xml_node_t *node,
+ int *ret_len);
+xml_node_t * xml_node_copy(struct xml_node_ctx *ctx, xml_node_t *node);
+
+#define xml_node_for_each_child(ctx, child, parent) \
+for (child = xml_node_first_child(ctx, parent); \
+ child; \
+ child = xml_node_next_sibling(ctx, child))
+
+#define xml_node_for_each_sibling(ctx, node) \
+for (; \
+ node; \
+ node = xml_node_next_sibling(ctx, node))
+
+#define xml_node_for_each_check(ctx, child) \
+if (!xml_node_is_element(ctx, child)) \
+ continue
+
+
+struct xml_node_ctx * xml_node_init_ctx(void *upper_ctx,
+ const void *env);
+void xml_node_deinit_ctx(struct xml_node_ctx *ctx);
+
+
+xml_node_t * get_node_uri(struct xml_node_ctx *ctx, xml_node_t *root,
+ const char *uri);
+xml_node_t * get_node(struct xml_node_ctx *ctx, xml_node_t *root,
+ const char *path);
+xml_node_t * get_child_node(struct xml_node_ctx *ctx, xml_node_t *root,
+ const char *path);
+xml_node_t * node_from_file(struct xml_node_ctx *ctx, const char *name);
+int node_to_file(struct xml_node_ctx *ctx, const char *fname, xml_node_t *node);
+xml_node_t * mo_to_tnds(struct xml_node_ctx *ctx, xml_node_t *mo,
+ int use_path, const char *urn, const char *ns_uri);
+xml_node_t * tnds_to_mo(struct xml_node_ctx *ctx, xml_node_t *tnds);
+
+xml_node_t * soap_build_envelope(struct xml_node_ctx *ctx, xml_node_t *node);
+xml_node_t * soap_get_body(struct xml_node_ctx *ctx, xml_node_t *soap);
+
+#endif /* XML_UTILS_H */
diff --git a/src/utils/xml_libxml2.c b/src/utils/xml_libxml2.c
new file mode 100644
index 0000000000000..c92839461dad4
--- /dev/null
+++ b/src/utils/xml_libxml2.c
@@ -0,0 +1,457 @@
+/*
+ * XML wrapper for libxml2
+ * Copyright (c) 2012-2013, Qualcomm Atheros, Inc.
+ *
+ * This software may be distributed under the terms of the BSD license.
+ * See README for more details.
+ */
+
+#include "includes.h"
+#define LIBXML_VALID_ENABLED
+#include <libxml/tree.h>
+#include <libxml/xmlschemastypes.h>
+
+#include "common.h"
+#include "base64.h"
+#include "xml-utils.h"
+
+
+struct xml_node_ctx {
+ void *ctx;
+};
+
+
+struct str_buf {
+ char *buf;
+ size_t len;
+};
+
+#define MAX_STR 1000
+
+static void add_str(void *ctx_ptr, const char *fmt, ...)
+{
+ struct str_buf *str = ctx_ptr;
+ va_list ap;
+ char *n;
+ int len;
+
+ n = os_realloc(str->buf, str->len + MAX_STR + 2);
+ if (n == NULL)
+ return;
+ str->buf = n;
+
+ va_start(ap, fmt);
+ len = vsnprintf(str->buf + str->len, MAX_STR, fmt, ap);
+ va_end(ap);
+ if (len >= MAX_STR)
+ len = MAX_STR - 1;
+ str->len += len;
+ str->buf[str->len] = '\0';
+}
+
+
+int xml_validate(struct xml_node_ctx *ctx, xml_node_t *node,
+ const char *xml_schema_fname, char **ret_err)
+{
+ xmlDocPtr doc;
+ xmlNodePtr n;
+ xmlSchemaParserCtxtPtr pctx;
+ xmlSchemaValidCtxtPtr vctx;
+ xmlSchemaPtr schema;
+ int ret;
+ struct str_buf errors;
+
+ if (ret_err)
+ *ret_err = NULL;
+
+ doc = xmlNewDoc((xmlChar *) "1.0");
+ if (doc == NULL)
+ return -1;
+ n = xmlDocCopyNode((xmlNodePtr) node, doc, 1);
+ if (n == NULL) {
+ xmlFreeDoc(doc);
+ return -1;
+ }
+ xmlDocSetRootElement(doc, n);
+
+ os_memset(&errors, 0, sizeof(errors));
+
+ pctx = xmlSchemaNewParserCtxt(xml_schema_fname);
+ xmlSchemaSetParserErrors(pctx, (xmlSchemaValidityErrorFunc) add_str,
+ (xmlSchemaValidityWarningFunc) add_str,
+ &errors);
+ schema = xmlSchemaParse(pctx);
+ xmlSchemaFreeParserCtxt(pctx);
+
+ vctx = xmlSchemaNewValidCtxt(schema);
+ xmlSchemaSetValidErrors(vctx, (xmlSchemaValidityErrorFunc) add_str,
+ (xmlSchemaValidityWarningFunc) add_str,
+ &errors);
+
+ ret = xmlSchemaValidateDoc(vctx, doc);
+ xmlSchemaFreeValidCtxt(vctx);
+ xmlFreeDoc(doc);
+ xmlSchemaFree(schema);
+
+ if (ret == 0) {
+ os_free(errors.buf);
+ return 0;
+ } else if (ret > 0) {
+ if (ret_err)
+ *ret_err = errors.buf;
+ else
+ os_free(errors.buf);
+ return -1;
+ } else {
+ if (ret_err)
+ *ret_err = errors.buf;
+ else
+ os_free(errors.buf);
+ return -1;
+ }
+}
+
+
+int xml_validate_dtd(struct xml_node_ctx *ctx, xml_node_t *node,
+ const char *dtd_fname, char **ret_err)
+{
+ xmlDocPtr doc;
+ xmlNodePtr n;
+ xmlValidCtxt vctx;
+ xmlDtdPtr dtd;
+ int ret;
+ struct str_buf errors;
+
+ if (ret_err)
+ *ret_err = NULL;
+
+ doc = xmlNewDoc((xmlChar *) "1.0");
+ if (doc == NULL)
+ return -1;
+ n = xmlDocCopyNode((xmlNodePtr) node, doc, 1);
+ if (n == NULL) {
+ xmlFreeDoc(doc);
+ return -1;
+ }
+ xmlDocSetRootElement(doc, n);
+
+ os_memset(&errors, 0, sizeof(errors));
+
+ dtd = xmlParseDTD(NULL, (const xmlChar *) dtd_fname);
+ if (dtd == NULL) {
+ xmlFreeDoc(doc);
+ return -1;
+ }
+
+ os_memset(&vctx, 0, sizeof(vctx));
+ vctx.userData = &errors;
+ vctx.error = add_str;
+ vctx.warning = add_str;
+ ret = xmlValidateDtd(&vctx, doc, dtd);
+ xmlFreeDoc(doc);
+ xmlFreeDtd(dtd);
+
+ if (ret == 1) {
+ os_free(errors.buf);
+ return 0;
+ } else {
+ if (ret_err)
+ *ret_err = errors.buf;
+ else
+ os_free(errors.buf);
+ return -1;
+ }
+}
+
+
+void xml_node_free(struct xml_node_ctx *ctx, xml_node_t *node)
+{
+ xmlFreeNode((xmlNodePtr) node);
+}
+
+
+xml_node_t * xml_node_get_parent(struct xml_node_ctx *ctx, xml_node_t *node)
+{
+ return (xml_node_t *) ((xmlNodePtr) node)->parent;
+}
+
+
+xml_node_t * xml_node_from_buf(struct xml_node_ctx *ctx, const char *buf)
+{
+ xmlDocPtr doc;
+ xmlNodePtr node;
+
+ doc = xmlParseMemory(buf, strlen(buf));
+ if (doc == NULL)
+ return NULL;
+ node = xmlDocGetRootElement(doc);
+ node = xmlCopyNode(node, 1);
+ xmlFreeDoc(doc);
+
+ return (xml_node_t *) node;
+}
+
+
+const char * xml_node_get_localname(struct xml_node_ctx *ctx,
+ xml_node_t *node)
+{
+ return (const char *) ((xmlNodePtr) node)->name;
+}
+
+
+char * xml_node_to_str(struct xml_node_ctx *ctx, xml_node_t *node)
+{
+ xmlChar *buf;
+ int bufsiz;
+ char *ret, *pos;
+ xmlNodePtr n = (xmlNodePtr) node;
+ xmlDocPtr doc;
+
+ doc = xmlNewDoc((xmlChar *) "1.0");
+ n = xmlDocCopyNode(n, doc, 1);
+ xmlDocSetRootElement(doc, n);
+ xmlDocDumpFormatMemory(doc, &buf, &bufsiz, 0);
+ xmlFreeDoc(doc);
+ pos = (char *) buf;
+ if (strncmp(pos, "<?xml", 5) == 0) {
+ pos = strchr(pos, '>');
+ if (pos)
+ pos++;
+ while (pos && (*pos == '\r' || *pos == '\n'))
+ pos++;
+ }
+ if (pos)
+ ret = os_strdup(pos);
+ else
+ ret = NULL;
+ xmlFree(buf);
+
+ if (ret) {
+ pos = ret;
+ if (pos[0]) {
+ while (pos[1])
+ pos++;
+ }
+ while (pos >= ret && *pos == '\n')
+ *pos-- = '\0';
+ }
+
+ return ret;
+}
+
+
+void xml_node_detach(struct xml_node_ctx *ctx, xml_node_t *node)
+{
+ xmlUnlinkNode((xmlNodePtr) node);
+}
+
+
+void xml_node_add_child(struct xml_node_ctx *ctx, xml_node_t *parent,
+ xml_node_t *child)
+{
+ xmlAddChild((xmlNodePtr) parent, (xmlNodePtr) child);
+}
+
+
+xml_node_t * xml_node_create_root(struct xml_node_ctx *ctx, const char *ns_uri,
+ const char *ns_prefix,
+ xml_namespace_t **ret_ns, const char *name)
+{
+ xmlNodePtr node;
+ xmlNsPtr ns = NULL;
+
+ node = xmlNewNode(NULL, (const xmlChar *) name);
+ if (node == NULL)
+ return NULL;
+ if (ns_uri) {
+ ns = xmlNewNs(node, (const xmlChar *) ns_uri,
+ (const xmlChar *) ns_prefix);
+ xmlSetNs(node, ns);
+ }
+
+ if (ret_ns)
+ *ret_ns = (xml_namespace_t *) ns;
+
+ return (xml_node_t *) node;
+}
+
+
+xml_node_t * xml_node_create(struct xml_node_ctx *ctx, xml_node_t *parent,
+ xml_namespace_t *ns, const char *name)
+{
+ xmlNodePtr node;
+ node = xmlNewChild((xmlNodePtr) parent, (xmlNsPtr) ns,
+ (const xmlChar *) name, NULL);
+ return (xml_node_t *) node;
+}
+
+
+xml_node_t * xml_node_create_text(struct xml_node_ctx *ctx,
+ xml_node_t *parent, xml_namespace_t *ns,
+ const char *name, const char *value)
+{
+ xmlNodePtr node;
+ node = xmlNewTextChild((xmlNodePtr) parent, (xmlNsPtr) ns,
+ (const xmlChar *) name, (const xmlChar *) value);
+ return (xml_node_t *) node;
+}
+
+
+xml_node_t * xml_node_create_text_ns(struct xml_node_ctx *ctx,
+ xml_node_t *parent, const char *ns_uri,
+ const char *name, const char *value)
+{
+ xmlNodePtr node;
+ xmlNsPtr ns;
+
+ node = xmlNewTextChild((xmlNodePtr) parent, NULL,
+ (const xmlChar *) name, (const xmlChar *) value);
+ ns = xmlNewNs(node, (const xmlChar *) ns_uri, NULL);
+ xmlSetNs(node, ns);
+ return (xml_node_t *) node;
+}
+
+
+void xml_node_set_text(struct xml_node_ctx *ctx, xml_node_t *node,
+ const char *value)
+{
+ /* TODO: escape XML special chars in value */
+ xmlNodeSetContent((xmlNodePtr) node, (xmlChar *) value);
+}
+
+
+int xml_node_add_attr(struct xml_node_ctx *ctx, xml_node_t *node,
+ xml_namespace_t *ns, const char *name, const char *value)
+{
+ xmlAttrPtr attr;
+
+ if (ns) {
+ attr = xmlNewNsProp((xmlNodePtr) node, (xmlNsPtr) ns,
+ (const xmlChar *) name,
+ (const xmlChar *) value);
+ } else {
+ attr = xmlNewProp((xmlNodePtr) node, (const xmlChar *) name,
+ (const xmlChar *) value);
+ }
+
+ return attr ? 0 : -1;
+}
+
+
+char * xml_node_get_attr_value(struct xml_node_ctx *ctx, xml_node_t *node,
+ char *name)
+{
+ return (char *) xmlGetNoNsProp((xmlNodePtr) node,
+ (const xmlChar *) name);
+}
+
+
+char * xml_node_get_attr_value_ns(struct xml_node_ctx *ctx, xml_node_t *node,
+ const char *ns_uri, char *name)
+{
+ return (char *) xmlGetNsProp((xmlNodePtr) node, (const xmlChar *) name,
+ (const xmlChar *) ns_uri);
+}
+
+
+void xml_node_get_attr_value_free(struct xml_node_ctx *ctx, char *val)
+{
+ if (val)
+ xmlFree((xmlChar *) val);
+}
+
+
+xml_node_t * xml_node_first_child(struct xml_node_ctx *ctx,
+ xml_node_t *parent)
+{
+ return (xml_node_t *) ((xmlNodePtr) parent)->children;
+}
+
+
+xml_node_t * xml_node_next_sibling(struct xml_node_ctx *ctx,
+ xml_node_t *node)
+{
+ return (xml_node_t *) ((xmlNodePtr) node)->next;
+}
+
+
+int xml_node_is_element(struct xml_node_ctx *ctx, xml_node_t *node)
+{
+ return ((xmlNodePtr) node)->type == XML_ELEMENT_NODE;
+}
+
+
+char * xml_node_get_text(struct xml_node_ctx *ctx, xml_node_t *node)
+{
+ if (xmlChildElementCount((xmlNodePtr) node) > 0)
+ return NULL;
+ return (char *) xmlNodeGetContent((xmlNodePtr) node);
+}
+
+
+void xml_node_get_text_free(struct xml_node_ctx *ctx, char *val)
+{
+ if (val)
+ xmlFree((xmlChar *) val);
+}
+
+
+char * xml_node_get_base64_text(struct xml_node_ctx *ctx, xml_node_t *node,
+ int *ret_len)
+{
+ char *txt;
+ unsigned char *ret;
+ size_t len;
+
+ txt = xml_node_get_text(ctx, node);
+ if (txt == NULL)
+ return NULL;
+
+ ret = base64_decode((unsigned char *) txt, strlen(txt), &len);
+ if (ret_len)
+ *ret_len = len;
+ xml_node_get_text_free(ctx, txt);
+ if (ret == NULL)
+ return NULL;
+ txt = os_malloc(len + 1);
+ if (txt == NULL) {
+ os_free(ret);
+ return NULL;
+ }
+ os_memcpy(txt, ret, len);
+ txt[len] = '\0';
+ return txt;
+}
+
+
+xml_node_t * xml_node_copy(struct xml_node_ctx *ctx, xml_node_t *node)
+{
+ if (node == NULL)
+ return NULL;
+ return (xml_node_t *) xmlCopyNode((xmlNodePtr) node, 1);
+}
+
+
+struct xml_node_ctx * xml_node_init_ctx(void *upper_ctx,
+ const void *env)
+{
+ struct xml_node_ctx *xctx;
+
+ xctx = os_zalloc(sizeof(*xctx));
+ if (xctx == NULL)
+ return NULL;
+ xctx->ctx = upper_ctx;
+
+ LIBXML_TEST_VERSION
+
+ return xctx;
+}
+
+
+void xml_node_deinit_ctx(struct xml_node_ctx *ctx)
+{
+ xmlSchemaCleanupTypes();
+ xmlCleanupParser();
+ xmlMemoryDump();
+ os_free(ctx);
+}