hostapd(hidl): Add asynchronous failure callback

Changes in the CL:
a) Add a new callback registration mechanism for the hostapd HIDL interface.
b) Use the existing |setup_complete_cb| callback provided by the hostapd
core to trigger the new onFailure() HIDL callback.

Bug: 112705137
Test: Manual test. Simulated the issue reported in the bug and ensured
that UI toggled off.
Change-Id: I7211e313c107be3a4a7a52af69ffe1e565b5147b
diff --git a/hostapd/hidl/1.1/hidl.cpp b/hostapd/hidl/1.1/hidl.cpp
new file mode 100644
index 0000000..2051e7b
--- /dev/null
+++ b/hostapd/hidl/1.1/hidl.cpp
@@ -0,0 +1,70 @@
+/*
+ * hidl interface for wpa_supplicant daemon
+ * Copyright (c) 2004-2018, Jouni Malinen <j@w1.fi>
+ * Copyright (c) 2004-2018, Roshan Pius <rpius@google.com>
+ *
+ * This software may be distributed under the terms of the BSD license.
+ * See README for more details.
+ */
+
+#include <hwbinder/IPCThreadState.h>
+#include <hidl/HidlTransportSupport.h>
+
+#include "hostapd.h"
+
+extern "C"
+{
+#include "hidl.h"
+#include "utils/common.h"
+#include "utils/eloop.h"
+#include "utils/includes.h"
+}
+
+using android::hardware::configureRpcThreadpool;
+using android::hardware::IPCThreadState;
+using android::hardware::wifi::hostapd::V1_1::IHostapd;
+using android::hardware::wifi::hostapd::V1_1::implementation::Hostapd;
+
+// This file is a bridge between the hostapd code written in 'C' and the HIDL
+// interface in C++. So, using "C" style static globals here!
+static int hidl_fd = -1;
+static android::sp<IHostapd> service;
+
+void hostapd_hidl_sock_handler(
+    int /* sock */, void * /* eloop_ctx */, void * /* sock_ctx */)
+{
+	IPCThreadState::self()->handlePolledCommands();
+}
+
+int hostapd_hidl_init(struct hapd_interfaces *interfaces)
+{
+	wpa_printf(MSG_DEBUG, "Initing hidl control");
+
+	IPCThreadState::self()->setupPolling(&hidl_fd);
+	if (hidl_fd < 0)
+		goto err;
+
+	wpa_printf(MSG_INFO, "Processing hidl events on FD %d", hidl_fd);
+	// Look for read events from the hidl socket in the eloop.
+	if (eloop_register_read_sock(
+		hidl_fd, hostapd_hidl_sock_handler, interfaces, NULL) < 0)
+		goto err;
+	service = new Hostapd(interfaces);
+	if (!service)
+		goto err;
+	if (service->registerAsService() != android::NO_ERROR)
+		goto err;
+	return 0;
+err:
+	hostapd_hidl_deinit(interfaces);
+	return -1;
+}
+
+void hostapd_hidl_deinit(struct hapd_interfaces *interfaces)
+{
+	wpa_printf(MSG_DEBUG, "Deiniting hidl control");
+	eloop_unregister_read_sock(hidl_fd);
+	IPCThreadState::shutdown();
+	hidl_fd = -1;
+	service.clear();
+}
diff --git a/hostapd/hidl/1.1/hidl.h b/hostapd/hidl/1.1/hidl.h
new file mode 100644
index 0000000..5decf64
--- /dev/null
+++ b/hostapd/hidl/1.1/hidl.h
@@ -0,0 +1,30 @@
+/*
+ * hidl interface for wpa_supplicant daemon
+ * Copyright (c) 2004-2018, Jouni Malinen <j@w1.fi>
+ * Copyright (c) 2004-2018, Roshan Pius <rpius@google.com>
+ *
+ * This software may be distributed under the terms of the BSD license.
+ * See README for more details.
+ */
+
+#ifndef HOSTAPD_HIDL_HIDL_H
+#define HOSTAPD_HIDL_HIDL_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif  // _cplusplus
+#include "ap/hostapd.h"
+
+/**
+ * This is the hidl RPC interface entry point to the hostapd core.
+ * This initializes the hidl driver & IHostapd instance.
+ */
+int hostapd_hidl_init(struct hapd_interfaces *interfaces);
+void hostapd_hidl_deinit(struct hapd_interfaces *interfaces);
+
+#ifdef __cplusplus
+}
+#endif  // _cplusplus
+
+#endif  // HOSTAPD_HIDL_HIDL_H
diff --git a/hostapd/hidl/1.1/hidl_return_util.h b/hostapd/hidl/1.1/hidl_return_util.h
new file mode 100644
index 0000000..d914ee2
--- /dev/null
+++ b/hostapd/hidl/1.1/hidl_return_util.h
@@ -0,0 +1,44 @@
+/*
+ * hidl interface for wpa_hostapd daemon
+ * Copyright (c) 2004-2018, Jouni Malinen <j@w1.fi>
+ * Copyright (c) 2004-2018, Roshan Pius <rpius@google.com>
+ *
+ * This software may be distributed under the terms of the BSD license.
+ * See README for more details.
+ */
+
+#ifndef HIDL_RETURN_UTIL_H_
+#define HIDL_RETURN_UTIL_H_
+
+#include <functional>
+
+namespace android {
+namespace hardware {
+namespace wifi {
+namespace hostapd {
+namespace V1_1 {
+namespace implementation {
+namespace hidl_return_util {
+
+/**
+ * These utility functions are used to invoke a method on the provided
+ * HIDL interface object.
+ */
+// Use for HIDL methods which return only an instance of HostapdStatus.
+template <typename ObjT, typename WorkFuncT, typename... Args>
+Return<void> call(
+    ObjT* obj, WorkFuncT&& work,
+    const std::function<void(const HostapdStatus&)>& hidl_cb, Args&&... args)
+{
+	hidl_cb((obj->*work)(std::forward<Args>(args)...));
+	return Void();
+}
+
+}  // namespace hidl_return_util
+}  // namespace implementation
+}  // namespace V1_1
+}  // namespace hostapd
+}  // namespace wifi
+}  // namespace hardware
+}  // namespace android
+#endif  // HIDL_RETURN_UTIL_H_
diff --git a/hostapd/hidl/1.1/hostapd.cpp b/hostapd/hidl/1.1/hostapd.cpp
new file mode 100644
index 0000000..340b22c
--- /dev/null
+++ b/hostapd/hidl/1.1/hostapd.cpp
@@ -0,0 +1,339 @@
+/*
+ * hidl interface for wpa_hostapd daemon
+ * Copyright (c) 2004-2018, Jouni Malinen <j@w1.fi>
+ * Copyright (c) 2004-2018, Roshan Pius <rpius@google.com>
+ *
+ * This software may be distributed under the terms of the BSD license.
+ * See README for more details.
+ */
+#include <iomanip>
+#include <sstream>
+#include <string>
+#include <vector>
+
+#include <android-base/file.h>
+#include <android-base/stringprintf.h>
+
+#include "hostapd.h"
+#include "hidl_return_util.h"
+
+extern "C"
+{
+#include "utils/eloop.h"
+}
+
+// The HIDL implementation for hostapd creates a hostapd.conf dynamically for
+// each interface. This file can then be used to hook onto the normal config
+// file parsing logic in hostapd code.  Helps us to avoid duplication of code
+// in the HIDL interface.
+// TOOD(b/71872409): Add unit tests for this.
+namespace {
+constexpr char kConfFileNameFmt[] = "/data/vendor/wifi/hostapd/hostapd_%s.conf";
+
+using android::base::RemoveFileIfExists;
+using android::base::StringPrintf;
+using android::base::WriteStringToFile;
+using android::hardware::wifi::hostapd::V1_1::IHostapd;
+
+std::string WriteHostapdConfig(
+    const std::string& interface_name, const std::string& config)
+{
+	const std::string file_path =
+	    StringPrintf(kConfFileNameFmt, interface_name.c_str());
+	if (WriteStringToFile(
+		config, file_path, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP,
+		getuid(), getgid())) {
+		return file_path;
+	}
+	// Diagnose failure
+	int error = errno;
+	wpa_printf(
+	    MSG_ERROR, "Cannot write hostapd config to %s, error: %s",
+	    file_path.c_str(), strerror(error));
+	struct stat st;
+	int result = stat(file_path.c_str(), &st);
+	if (result == 0) {
+		wpa_printf(
+		    MSG_ERROR, "hostapd config file uid: %d, gid: %d, mode: %d",
+		    st.st_uid, st.st_gid, st.st_mode);
+	} else {
+		wpa_printf(
+		    MSG_ERROR,
+		    "Error calling stat() on hostapd config file: %s",
+		    strerror(errno));
+	}
+	return "";
+}
+
+std::string CreateHostapdConfig(
+    const IHostapd::IfaceParams& iface_params,
+    const IHostapd::NetworkParams& nw_params)
+{
+	if (nw_params.ssid.size() >
+	    static_cast<uint32_t>(
+		IHostapd::ParamSizeLimits::SSID_MAX_LEN_IN_BYTES)) {
+		wpa_printf(
+		    MSG_ERROR, "Invalid SSID size: %zu", nw_params.ssid.size());
+		return "";
+	}
+	if ((nw_params.encryptionType != IHostapd::EncryptionType::NONE) &&
+	    (nw_params.pskPassphrase.size() <
+		 static_cast<uint32_t>(
+		     IHostapd::ParamSizeLimits::
+			 WPA2_PSK_PASSPHRASE_MIN_LEN_IN_BYTES) ||
+	     nw_params.pskPassphrase.size() >
+		 static_cast<uint32_t>(
+		     IHostapd::ParamSizeLimits::
+			 WPA2_PSK_PASSPHRASE_MAX_LEN_IN_BYTES))) {
+		wpa_printf(
+		    MSG_ERROR, "Invalid psk passphrase size: %zu",
+		    nw_params.pskPassphrase.size());
+		return "";
+	}
+
+	// SSID string
+	std::stringstream ss;
+	ss << std::hex;
+	ss << std::setfill('0');
+	for (uint8_t b : nw_params.ssid) {
+		ss << std::setw(2) << static_cast<unsigned int>(b);
+	}
+	const std::string ssid_as_string = ss.str();
+
+	// Encryption config string
+	std::string encryption_config_as_string;
+	switch (nw_params.encryptionType) {
+	case IHostapd::EncryptionType::NONE:
+		// no security params
+		break;
+	case IHostapd::EncryptionType::WPA:
+		encryption_config_as_string = StringPrintf(
+		    "wpa=3\n"
+		    "wpa_pairwise=TKIP CCMP\n"
+		    "wpa_passphrase=%s",
+		    nw_params.pskPassphrase.c_str());
+		break;
+	case IHostapd::EncryptionType::WPA2:
+		encryption_config_as_string = StringPrintf(
+		    "wpa=2\n"
+		    "rsn_pairwise=CCMP\n"
+		    "wpa_passphrase=%s",
+		    nw_params.pskPassphrase.c_str());
+		break;
+	default:
+		wpa_printf(MSG_ERROR, "Unknown encryption type");
+		return "";
+	}
+
+	std::string channel_config_as_string;
+	if (iface_params.channelParams.enableAcs) {
+		channel_config_as_string = StringPrintf(
+		    "channel=0\n"
+		    "acs_exclude_dfs=%d",
+		    iface_params.channelParams.acsShouldExcludeDfs);
+	} else {
+		channel_config_as_string = StringPrintf(
+		    "channel=%d", iface_params.channelParams.channel);
+	}
+
+	// Hw Mode String
+	std::string hw_mode_as_string;
+	std::string ht_cap_vht_oper_chwidth_as_string;
+	switch (iface_params.channelParams.band) {
+	case IHostapd::Band::BAND_2_4_GHZ:
+		hw_mode_as_string = "hw_mode=g";
+		break;
+	case IHostapd::Band::BAND_5_GHZ:
+		hw_mode_as_string = "hw_mode=a";
+		if (iface_params.channelParams.enableAcs) {
+			ht_cap_vht_oper_chwidth_as_string =
+			    "ht_capab=[HT40+]\n"
+			    "vht_oper_chwidth=1";
+		}
+		break;
+	case IHostapd::Band::BAND_ANY:
+		hw_mode_as_string = "hw_mode=any";
+		if (iface_params.channelParams.enableAcs) {
+			ht_cap_vht_oper_chwidth_as_string =
+			    "ht_capab=[HT40+]\n"
+			    "vht_oper_chwidth=1";
+		}
+		break;
+	default:
+		wpa_printf(MSG_ERROR, "Invalid band");
+		return "";
+	}
+
+	return StringPrintf(
+	    "interface=%s\n"
+	    "driver=nl80211\n"
+	    "ctrl_interface=/data/vendor/wifi/hostapd/ctrl\n"
+	    // ssid2 signals to hostapd that the value is not a literal value
+	    // for use as a SSID.  In this case, we're giving it a hex
+	    // std::string and hostapd needs to expect that.
+	    "ssid2=%s\n"
+	    "%s\n"
+	    "ieee80211n=%d\n"
+	    "ieee80211ac=%d\n"
+	    "%s\n"
+	    "%s\n"
+	    "ignore_broadcast_ssid=%d\n"
+	    "wowlan_triggers=any\n"
+	    "%s\n",
+	    iface_params.ifaceName.c_str(), ssid_as_string.c_str(),
+	    channel_config_as_string.c_str(),
+	    iface_params.hwModeParams.enable80211N ? 1 : 0,
+	    iface_params.hwModeParams.enable80211AC ? 1 : 0,
+	    hw_mode_as_string.c_str(), ht_cap_vht_oper_chwidth_as_string.c_str(),
+	    nw_params.isHidden ? 1 : 0, encryption_config_as_string.c_str());
+}
+
+// hostapd core functions accept "C" style function pointers, so use global
+// functions to pass to the hostapd core function and store the corresponding
+// std::function methods to be invoked.
+//
+// NOTE: Using the pattern from the vendor HAL (wifi_legacy_hal.cpp).
+//
+// Callback to be invoked once setup is complete
+std::function<void(struct hostapd_data*)> on_setup_complete_internal_callback;
+void onAsyncSetupCompleteCb(void* ctx)
+{
+	struct hostapd_data* iface_hapd = (struct hostapd_data*)ctx;
+	if (on_setup_complete_internal_callback) {
+		on_setup_complete_internal_callback(iface_hapd);
+		// Invalidate this callback since we don't want this firing
+		// again.
+		on_setup_complete_internal_callback = nullptr;
+	}
+}
+}  // namespace
+
+namespace android {
+namespace hardware {
+namespace wifi {
+namespace hostapd {
+namespace V1_1 {
+namespace implementation {
+using hidl_return_util::call;
+using namespace android::hardware::wifi::hostapd::V1_0;
+
+Hostapd::Hostapd(struct hapd_interfaces* interfaces) : interfaces_(interfaces)
+{}
+
+Return<void> Hostapd::addAccessPoint(
+    const IfaceParams& iface_params, const NetworkParams& nw_params,
+    addAccessPoint_cb _hidl_cb)
+{
+	return call(
+	    this, &Hostapd::addAccessPointInternal, _hidl_cb, iface_params,
+	    nw_params);
+}
+
+Return<void> Hostapd::removeAccessPoint(
+    const hidl_string& iface_name, removeAccessPoint_cb _hidl_cb)
+{
+	return call(
+	    this, &Hostapd::removeAccessPointInternal, _hidl_cb, iface_name);
+}
+
+Return<void> Hostapd::terminate()
+{
+	wpa_printf(MSG_INFO, "Terminating...");
+	eloop_terminate();
+	return Void();
+}
+
+Return<void> Hostapd::registerCallback(
+    const sp<IHostapdCallback>& callback, registerCallback_cb _hidl_cb)
+{
+	return call(
+	    this, &Hostapd::registerCallbackInternal, _hidl_cb, callback);
+}
+
+HostapdStatus Hostapd::addAccessPointInternal(
+    const IfaceParams& iface_params, const NetworkParams& nw_params)
+{
+	if (hostapd_get_iface(interfaces_, iface_params.ifaceName.c_str())) {
+		wpa_printf(
+		    MSG_ERROR, "Interface %s already present",
+		    iface_params.ifaceName.c_str());
+		return {HostapdStatusCode::FAILURE_IFACE_EXISTS, ""};
+	}
+	const auto conf_params = CreateHostapdConfig(iface_params, nw_params);
+	if (conf_params.empty()) {
+		wpa_printf(MSG_ERROR, "Failed to create config params");
+		return {HostapdStatusCode::FAILURE_ARGS_INVALID, ""};
+	}
+	const auto conf_file_path =
+	    WriteHostapdConfig(iface_params.ifaceName, conf_params);
+	if (conf_file_path.empty()) {
+		wpa_printf(MSG_ERROR, "Failed to write config file");
+		return {HostapdStatusCode::FAILURE_UNKNOWN, ""};
+	}
+	std::string add_iface_param_str = StringPrintf(
+	    "%s config=%s", iface_params.ifaceName.c_str(),
+	    conf_file_path.c_str());
+	std::vector<char> add_iface_param_vec(
+	    add_iface_param_str.begin(), add_iface_param_str.end() + 1);
+	if (hostapd_add_iface(interfaces_, add_iface_param_vec.data()) < 0) {
+		wpa_printf(
+		    MSG_ERROR, "Adding interface %s failed",
+		    add_iface_param_str.c_str());
+		return {HostapdStatusCode::FAILURE_UNKNOWN, ""};
+	}
+	struct hostapd_data* iface_hapd =
+	    hostapd_get_iface(interfaces_, iface_params.ifaceName.c_str());
+	WPA_ASSERT(iface_hapd != nullptr && iface_hapd->iface != nullptr);
+	// Register the setup complete callbacks
+	on_setup_complete_internal_callback =
+	    [this](struct hostapd_data* iface_hapd) {
+		    wpa_printf(
+			MSG_DEBUG, "AP interface setup completed - state %s",
+			hostapd_state_text(iface_hapd->iface->state));
+		    if (iface_hapd->iface->state == HAPD_IFACE_DISABLED) {
+			    // Invoke the failure callback on all registered
+			    // clients.
+			    for (const auto& callback : callbacks_) {
+				    callback->onFailure(
+					iface_hapd->conf->iface);
+			    }
+		    }
+	    };
+	iface_hapd->setup_complete_cb = onAsyncSetupCompleteCb;
+	iface_hapd->setup_complete_cb_ctx = iface_hapd;
+	if (hostapd_enable_iface(iface_hapd->iface) < 0) {
+		wpa_printf(
+		    MSG_ERROR, "Enabling interface %s failed",
+		    iface_params.ifaceName.c_str());
+		return {HostapdStatusCode::FAILURE_UNKNOWN, ""};
+	}
+	return {HostapdStatusCode::SUCCESS, ""};
+}
+
+HostapdStatus Hostapd::removeAccessPointInternal(const std::string& iface_name)
+{
+	std::vector<char> remove_iface_param_vec(
+	    iface_name.begin(), iface_name.end() + 1);
+	if (hostapd_remove_iface(interfaces_, remove_iface_param_vec.data()) <
+	    0) {
+		wpa_printf(
+		    MSG_ERROR, "Removing interface %s failed",
+		    iface_name.c_str());
+		return {HostapdStatusCode::FAILURE_UNKNOWN, ""};
+	}
+	return {HostapdStatusCode::SUCCESS, ""};
+}
+
+HostapdStatus Hostapd::registerCallbackInternal(
+    const sp<IHostapdCallback>& callback)
+{
+	callbacks_.push_back(callback);
+	return {HostapdStatusCode::SUCCESS, ""};
+}
+
+}  // namespace implementation
+}  // namespace V1_1
+}  // namespace hostapd
+}  // namespace wifi
+}  // namespace hardware
+}  // namespace android
diff --git a/hostapd/hidl/1.1/hostapd.h b/hostapd/hidl/1.1/hostapd.h
new file mode 100644
index 0000000..3438d8b
--- /dev/null
+++ b/hostapd/hidl/1.1/hostapd.h
@@ -0,0 +1,81 @@
+/*
+ * hidl interface for wpa_hostapd daemon
+ * Copyright (c) 2004-2018, Jouni Malinen <j@w1.fi>
+ * Copyright (c) 2004-2018, Roshan Pius <rpius@google.com>
+ *
+ * This software may be distributed under the terms of the BSD license.
+ * See README for more details.
+ */
+
+#ifndef HOSTAPD_HIDL_SUPPLICANT_H
+#define HOSTAPD_HIDL_SUPPLICANT_H
+
+#include <string>
+
+#include <android-base/macros.h>
+
+#include <android/hardware/wifi/hostapd/1.1/IHostapd.h>
+#include <android/hardware/wifi/hostapd/1.1/IHostapdCallback.h>
+
+extern "C"
+{
+#include "utils/common.h"
+#include "utils/includes.h"
+#include "utils/wpa_debug.h"
+#include "ap/hostapd.h"
+}
+
+namespace android {
+namespace hardware {
+namespace wifi {
+namespace hostapd {
+namespace V1_1 {
+namespace implementation {
+using namespace android::hardware::wifi::hostapd::V1_0;
+
+/**
+ * Implementation of the hostapd hidl object. This hidl
+ * object is used core for global control operations on
+ * hostapd.
+ */
+class Hostapd : public V1_1::IHostapd
+{
+public:
+	Hostapd(hapd_interfaces* interfaces);
+	~Hostapd() override = default;
+
+	// Hidl methods exposed.
+	Return<void> addAccessPoint(
+	    const IfaceParams& iface_params, const NetworkParams& nw_params,
+	    addAccessPoint_cb _hidl_cb) override;
+	Return<void> removeAccessPoint(
+	    const hidl_string& iface_name,
+	    removeAccessPoint_cb _hidl_cb) override;
+	Return<void> terminate() override;
+	Return<void> registerCallback(
+	    const sp<IHostapdCallback>& callback,
+	    registerCallback_cb _hidl_cb) override;
+
+private:
+	// Corresponding worker functions for the HIDL methods.
+	HostapdStatus addAccessPointInternal(
+	    const IfaceParams& iface_params, const NetworkParams& nw_params);
+	HostapdStatus removeAccessPointInternal(const std::string& iface_name);
+	HostapdStatus registerCallbackInternal(
+	    const sp<IHostapdCallback>& callback);
+
+	// Raw pointer to the global structure maintained by the core.
+	struct hapd_interfaces* interfaces_;
+	// Callbacks registered.
+	std::vector<sp<IHostapdCallback>> callbacks_;
+
+	DISALLOW_COPY_AND_ASSIGN(Hostapd);
+};
+}  // namespace implementation
+}  // namespace V1_1
+}  // namespace hostapd
+}  // namespace wifi
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HOSTAPD_HIDL_SUPPLICANT_H