/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "adbd_wifi.h"

#include <adbd_auth.h>

#if defined(__ANDROID__)

#include <unistd.h>
#include <optional>

#include <android-base/properties.h>
#include <com_android_adbdauth_flags.h>

#include "adb.h"
#include "adbd_wifi.h"
#include "daemon/mdns.h"
#include "sysdeps.h"
#include "transport.h"

using namespace android::base;

namespace {

static AdbdAuthContext* auth_ctx;

static void adb_disconnected(void* unused, atransport* t);
static struct adisconnect adb_disconnect = {adb_disconnected, nullptr};

static void adb_disconnected(void* unused, atransport* t) {
    LOG(INFO) << "ADB wifi device disconnected";
    CHECK(t->auth_id.has_value());
    adbd_auth_tls_device_disconnected(auth_ctx, kAdbTransportTypeWifi, t->auth_id.value());
}

class TlsServer {
  public:
    explicit TlsServer(int port);
    virtual ~TlsServer();
    bool Start();
    uint16_t port() { return port_; };

  private:
    void OnFdEvent(int fd, unsigned ev);
    static void StaticOnFdEvent(int fd, unsigned ev, void* opaque);

    fdevent* fd_event_ = nullptr;
    uint16_t port_;
};  // TlsServer

TlsServer::TlsServer(int port) : port_(port) {}

TlsServer::~TlsServer() {
    fdevent* fde = fd_event_;
    fdevent_run_on_looper([fde]() {
        if (fde != nullptr) {
            fdevent_destroy(fde);
        }
    });
}

bool TlsServer::Start() {
    std::condition_variable cv;
    std::mutex mutex;
    std::optional<bool> success;
    auto callback = [&](bool result) {
        {
            std::lock_guard<std::mutex> lock(mutex);
            success = result;
        }
        cv.notify_one();
    };

    std::string err;
    unique_fd fd(network_inaddr_any_server(port_, SOCK_STREAM, &err));
    if (fd.get() == -1) {
        LOG(ERROR) << "Failed to start TLS server [" << err << "]";
        return false;
    }
    close_on_exec(fd.get());
    int port = socket_get_local_port(fd.get());
    if (port <= 0 || port > 65535) {
        LOG(ERROR) << "Invalid port for tls server";
        return false;
    }
    port_ = static_cast<uint16_t>(port);
    LOG(INFO) << "adbwifi started on port " << port_;

    std::unique_lock<std::mutex> lock(mutex);
    fdevent_run_on_looper([&]() {
        fd_event_ = fdevent_create(fd.release(), &TlsServer::StaticOnFdEvent, this);
        if (fd_event_ == nullptr) {
            LOG(ERROR) << "Failed to create fd event for TlsServer.";
            callback(false);
            return;
        }
        callback(true);
    });

    cv.wait(lock, [&]() { return success.has_value(); });
    if (!*success) {
        LOG(INFO) << "TlsServer fdevent_create failed";
        return false;
    }
    fdevent_set(fd_event_, FDE_READ);
    LOG(INFO) << "TlsServer running on port " << port_;

    return *success;
}

// static
void TlsServer::StaticOnFdEvent(int fd, unsigned ev, void* opaque) {
    auto server = reinterpret_cast<TlsServer*>(opaque);
    server->OnFdEvent(fd, ev);
}

void TlsServer::OnFdEvent(int fd, unsigned ev) {
    if ((ev & FDE_READ) == 0 || fd != fd_event_->fd.get()) {
        LOG(INFO) << __func__ << ": No read [ev=" << ev << " fd=" << fd << "]";
        return;
    }

    unique_fd new_fd(adb_socket_accept(fd, nullptr, nullptr));
    if (new_fd >= 0) {
        LOG(INFO) << "New TLS connection [fd=" << new_fd.get() << "]";
        close_on_exec(new_fd.get());
        disable_tcp_nagle(new_fd.get());
        std::string serial = android::base::StringPrintf("host-%d", new_fd.get());
        register_socket_transport(
                std::move(new_fd), std::move(serial), port_, false,
                [](atransport*) { return ReconnectResult::Abort; }, true);
    }
}

TlsServer* sTlsServer = nullptr;

const char kWifiEnabledProp[] = "persist.adb.tls_server.enable";

// Pre API 37 control ADB Wifi TLSServer by toggling kWifiEnabledProp property
static void start_wifi_enabled_observer() {
    LOG(INFO) << "wifi_init: Starting property observer thread";
    std::thread([]() {
        bool wifi_enabled = false;
        while (true) {
            std::string toggled_val = wifi_enabled ? "0" : "1";
            LOG(INFO) << "Waiting for " << kWifiEnabledProp << "=" << toggled_val;

            if (WaitForProperty(kWifiEnabledProp, toggled_val)) {
                wifi_enabled = !wifi_enabled;
                LOG(INFO) << kWifiEnabledProp << " changed to " << toggled_val;
                if (wifi_enabled) {
                    enable_wifi_debugging();
                } else {
                    disable_wifi_debugging();
                }
            }
        }
    }).detach();
}
}  // namespace

static void adbd_send_tls_server_port(uint16_t port) {
    if (com_android_adbdauth_flags_use_tls_lifecycle()) {
        if (__builtin_available(android 37, *)) {
            LOG(INFO) << "Sending TLS port to framework via adbdauth'" << port << "'";
            adbd_auth_send_tls_server_port(auth_ctx, port);
            return;
        }
    }

    // Fallback to legacy system property
    LOG(INFO) << "Sending TLS port to framework via system property '" << port << "'";
    SetProperty("service.adb.tls.port", std::to_string(port));
}

void enable_wifi_debugging() {
    if (sTlsServer != nullptr) {
        // The TLS server is already up. This is a noop. But the Framework may still expect to get
        // sent the tls port.
        LOG(INFO) << "enable_wifi_debugging noop, still sending port=" << sTlsServer->port();
        adbd_send_tls_server_port(sTlsServer->port());
        return;
    }
    sTlsServer = new TlsServer(0);
    if (!sTlsServer->Start()) {
        LOG(ERROR) << "Failed to start TlsServer";
        delete sTlsServer;
        sTlsServer = nullptr;
        return;
    }

    // Start mdns connect service for discovery
    register_adb_tls_service(sTlsServer->port());
    LOG(INFO) << "adb wifi started on port " << sTlsServer->port();
    adbd_send_tls_server_port(sTlsServer->port());
}

void disable_wifi_debugging() {
    if (sTlsServer != nullptr) {
        delete sTlsServer;
        sTlsServer = nullptr;
    }

    unregister_adb_tls_service();

    kick_all_tcp_tls_transports();
    LOG(INFO) << "adb wifi stopped";
    adbd_send_tls_server_port(0);
}

void adbd_wifi_init(AdbdAuthContext* ctx) {
    auth_ctx = ctx;
    if (com_android_adbdauth_flags_use_tls_lifecycle()) {
        if (__builtin_available(android 37, *)) {
            LOG(INFO) << "wifi_init: Expecting lifecycle message over adbdauth";
            return;
        }
    }

    // Fallback to legacy property observer to detect when start/stop adb wifi is requested
    start_wifi_enabled_observer();
}

void adbd_wifi_secure_connect(atransport* t) {
    t->AddDisconnect(&adb_disconnect);
    handle_online(t);
    send_connect(t);
    LOG(INFO) << __func__ << ": connected " << t->name;
    t->auth_id = adbd_auth_tls_device_connected(auth_ctx, kAdbTransportTypeWifi, t->auth_key.data(),
                                                t->auth_key.size());
}
#else
void enable_wifi_debugging() {}
void disable_wifi_debugging() {}
void adbd_wifi_init(AdbdAuthContext*) {}
void adbd_wifi_secure_connect(atransport*) {}
#endif  //__ANDROID__
