#include "net.h"

#include <algorithm>
#include <cerrno>
#include <climits>
#include <cstring>

#if defined(_WIN32)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <io.h>
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#endif

#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>

#if !defined(_WIN32)
#include <arpa/inet.h>
#include <fcntl.h>
#include <limits.h>
#include <netdb.h>
#include <netinet/in.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#if defined(__APPLE__)
#include <mach-o/dyld.h>
#endif
#endif

namespace vn::net {

namespace {

#if defined(_WIN32)
void ensure_winsock() {
    static const bool initialized = [] {
        WSADATA data{};
        return WSAStartup(MAKEWORD(2, 2), &data) == 0;
    }();
    (void)initialized;
}

std::wstring widen_utf8(std::string_view text) {
    if (text.empty())
        return {};
    const int len =
        MultiByteToWideChar(CP_UTF8, 0, text.data(), static_cast<int>(text.size()), nullptr, 0);
    std::wstring out(static_cast<std::size_t>(len), L'\0');
    MultiByteToWideChar(CP_UTF8, 0, text.data(), static_cast<int>(text.size()), out.data(), len);
    return out;
}

// Quote one argument for CreateProcessW's command line.
std::wstring quote_windows_arg(std::wstring_view arg) {
    if (!arg.empty() && arg.find_first_of(L" \t\n\v\"") == std::wstring_view::npos)
        return std::wstring(arg);
    std::wstring out = L"\"";
    for (std::size_t i = 0; i < arg.size(); ++i) {
        std::size_t backslashes = 0;
        while (i < arg.size() && arg[i] == L'\\') {
            ++backslashes;
            ++i;
        }
        if (i == arg.size()) {
            out.append(backslashes * 2, L'\\');
            break;
        }
        if (arg[i] == L'"') {
            out.append(backslashes * 2 + 1, L'\\');
            out.push_back(L'"');
        } else {
            out.append(backslashes, L'\\');
            out.push_back(arg[i]);
        }
    }
    out.push_back(L'"');
    return out;
}

std::wstring build_windows_command_line(const std::vector<std::string>& argv) {
    std::wstring out;
    for (std::size_t i = 0; i < argv.size(); ++i) {
        if (i != 0)
            out.push_back(L' ');
        out += quote_windows_arg(widen_utf8(argv[i]));
    }
    return out;
}
#endif

std::string ssl_error_string() {
    unsigned long code = ERR_get_error();
    if (code == 0)
        return {};
    char buffer[256];
    ERR_error_string_n(code, buffer, sizeof(buffer));
    return std::string(buffer);
}

} // namespace

// ---------------------------------------------------------------------------
// Stream
// ---------------------------------------------------------------------------

Stream::Stream(Stream&& other) noexcept {
    *this = std::move(other);
}

Stream& Stream::operator=(Stream&& other) noexcept {
    if (this == &other)
        return *this;
    close();
    kind_ = other.kind_;
    fd_in_ = other.fd_in_;
    fd_out_ = other.fd_out_;
    ssl_ = other.ssl_;
#if defined(_WIN32)
    process_ = other.process_;
    process_id_ = other.process_id_;
#else
    pid_ = other.pid_;
#endif
    open_ = other.open_;
    other.open_ = false;
    other.ssl_ = nullptr;
    other.fd_in_ = 0;
    other.fd_out_ = 0;
#if defined(_WIN32)
    other.process_ = nullptr;
    other.process_id_ = 0;
#else
    other.pid_ = 0;
#endif
    return *this;
}

Stream::~Stream() {
    close();
}

Stream Stream::stdio_stream() {
    Stream stream;
    stream.kind_ = Kind::Stdio;
#if defined(_WIN32)
    stream.fd_in_ = reinterpret_cast<Socket>(GetStdHandle(STD_INPUT_HANDLE));
    stream.fd_out_ = reinterpret_cast<Socket>(GetStdHandle(STD_OUTPUT_HANDLE));
#else
    stream.fd_in_ = 0;
    stream.fd_out_ = 1;
#endif
    stream.open_ = true;
    return stream;
}

Stream Stream::fd_stream(Socket fd) {
    Stream stream;
    stream.kind_ = Kind::Fd;
    stream.fd_in_ = fd;
    stream.fd_out_ = fd;
    stream.open_ = true;
    return stream;
}

Stream Stream::tls_stream(Socket fd, void* ssl) {
    Stream stream;
    stream.kind_ = Kind::Tls;
    stream.fd_in_ = fd;
    stream.fd_out_ = fd;
    stream.ssl_ = ssl;
    stream.open_ = true;
    return stream;
}

std::optional<Stream> Stream::spawn_argv(const std::vector<std::string>& argv) {
    return vn::net::spawn_argv(argv);
}

std::int64_t Stream::read(void* buffer, std::size_t count) {
    if (!open_ || count == 0)
        return count == 0 ? 0 : -1;
    if (kind_ == Kind::Tls) {
        const int n = SSL_read(
            static_cast<SSL*>(ssl_), buffer,
            static_cast<int>(std::min<std::size_t>(count, static_cast<std::size_t>(INT_MAX))));
        if (n > 0)
            return n;
        if (n == 0)
            return 0;
        return -1;
    }
#if defined(_WIN32)
    if (kind_ == Kind::Stdio || kind_ == Kind::Proc) {
        DWORD got = 0;
        if (!ReadFile(reinterpret_cast<HANDLE>(fd_in_), buffer,
                      static_cast<DWORD>(
                          std::min<std::size_t>(count, static_cast<std::size_t>(MAXDWORD))),
                      &got, nullptr))
            return -1;
        return static_cast<std::int64_t>(got);
    }
    const int n =
        recv(static_cast<SOCKET>(fd_in_), static_cast<char*>(buffer),
             static_cast<int>(std::min<std::size_t>(count, static_cast<std::size_t>(INT_MAX))), 0);
    return n;
#else
    const int fd = kind_ == Kind::Stdio ? 0 : static_cast<int>(fd_in_);
    ssize_t n = 0;
    do {
        n = ::read(fd, buffer, count);
    } while (n < 0 && errno == EINTR);
    return n;
#endif
}

bool Stream::write_all(Bytes data) {
    if (!open_)
        return false;
    std::size_t offset = 0;
    while (offset < data.size()) {
        const std::size_t remaining = data.size() - offset;
        std::int64_t written = -1;
        if (kind_ == Kind::Tls) {
            const int n = SSL_write(static_cast<SSL*>(ssl_), data.data() + offset,
                                    static_cast<int>(std::min<std::size_t>(
                                        remaining, static_cast<std::size_t>(INT_MAX))));
            written = n;
        }
#if defined(_WIN32)
        else if (kind_ == Kind::Stdio || kind_ == Kind::Proc) {
            DWORD count = 0;
            if (!WriteFile(reinterpret_cast<HANDLE>(fd_out_), data.data() + offset,
                           static_cast<DWORD>(std::min<std::size_t>(
                               remaining, static_cast<std::size_t>(MAXDWORD))),
                           &count, nullptr))
                return false;
            written = static_cast<std::int64_t>(count);
        } else {
            const int n = send(static_cast<SOCKET>(fd_out_),
                               reinterpret_cast<const char*>(data.data() + offset),
                               static_cast<int>(std::min<std::size_t>(
                                   remaining, static_cast<std::size_t>(INT_MAX))),
                               0);
            written = n;
        }
#else
        else {
            ssize_t n = 0;
            do {
                n = ::write(kind_ == Kind::Stdio ? 1 : static_cast<int>(fd_out_),
                            data.data() + offset, remaining);
            } while (n < 0 && errno == EINTR);
            written = n;
        }
#endif
        if (written <= 0)
            return false;
        offset += static_cast<std::size_t>(written);
    }
    return true;
}

void Stream::close() {
    if (!open_)
        return;
    open_ = false;
    if (kind_ == Kind::Tls) {
        if (ssl_)
            tls_free(ssl_);
        ssl_ = nullptr;
#if defined(_WIN32)
        closesocket(static_cast<SOCKET>(fd_in_));
#else
        if (static_cast<int>(fd_in_) > 2)
            ::close(static_cast<int>(fd_in_));
#endif
        return;
    }
    if (kind_ == Kind::Proc) {
#if defined(_WIN32)
        if (fd_in_ != 0)
            CloseHandle(reinterpret_cast<HANDLE>(fd_in_));
        if (fd_out_ != 0)
            CloseHandle(reinterpret_cast<HANDLE>(fd_out_));
        if (process_) {
            WaitForSingleObject(reinterpret_cast<HANDLE>(process_), INFINITE);
            CloseHandle(reinterpret_cast<HANDLE>(process_));
            process_ = nullptr;
        }
#else
        if (static_cast<int>(fd_in_) > 2)
            ::close(static_cast<int>(fd_in_));
        if (static_cast<int>(fd_out_) > 2)
            ::close(static_cast<int>(fd_out_));
        if (pid_ > 0) {
            int status = 0;
            while (waitpid(pid_, &status, 0) < 0 && errno == EINTR) {
            }
            pid_ = 0;
        }
#endif
        return;
    }
    if (kind_ == Kind::Fd) {
#if defined(_WIN32)
        closesocket(static_cast<SOCKET>(fd_in_));
#else
        if (static_cast<int>(fd_in_) > 2)
            ::close(static_cast<int>(fd_in_));
#endif
    }
}

// ---------------------------------------------------------------------------
// Process spawning
// ---------------------------------------------------------------------------

#if defined(_WIN32)
std::optional<Stream> spawn_argv(const std::vector<std::string>& argv) {
    if (argv.empty())
        return std::nullopt;
    ensure_winsock();
    SECURITY_ATTRIBUTES attributes{};
    attributes.nLength = sizeof(attributes);
    attributes.bInheritHandle = TRUE;
    HANDLE child_stdin_read = nullptr;
    HANDLE child_stdin_write = nullptr;
    HANDLE child_stdout_read = nullptr;
    HANDLE child_stdout_write = nullptr;
    if (!CreatePipe(&child_stdin_read, &child_stdin_write, &attributes, 0) ||
        !CreatePipe(&child_stdout_read, &child_stdout_write, &attributes, 0)) {
        if (child_stdin_read)
            CloseHandle(child_stdin_read);
        if (child_stdin_write)
            CloseHandle(child_stdin_write);
        return std::nullopt;
    }
    SetHandleInformation(child_stdin_write, HANDLE_FLAG_INHERIT, 0);
    SetHandleInformation(child_stdout_read, HANDLE_FLAG_INHERIT, 0);
    STARTUPINFOW startup{};
    startup.cb = sizeof(startup);
    startup.dwFlags = STARTF_USESTDHANDLES;
    startup.hStdInput = child_stdin_read;
    startup.hStdOutput = child_stdout_write;
    startup.hStdError = GetStdHandle(STD_ERROR_HANDLE);
    PROCESS_INFORMATION process{};
    std::wstring command_line = build_windows_command_line(argv);
    const BOOL started = CreateProcessW(nullptr, command_line.data(), nullptr, nullptr, TRUE, 0,
                                        nullptr, nullptr, &startup, &process);
    CloseHandle(child_stdin_read);
    CloseHandle(child_stdout_write);
    if (!started) {
        CloseHandle(child_stdin_write);
        CloseHandle(child_stdout_read);
        return std::nullopt;
    }
    CloseHandle(process.hThread);
    Stream stream;
    stream.kind_ = Stream::Kind::Proc;
    stream.fd_in_ = reinterpret_cast<Socket>(child_stdout_read);
    stream.fd_out_ = reinterpret_cast<Socket>(child_stdin_write);
    stream.process_ = process.hProcess;
    stream.process_id_ = process.dwProcessId;
    stream.open_ = true;
    return stream;
}
#else
std::optional<Stream> spawn_argv(const std::vector<std::string>& argv) {
    if (argv.empty())
        return std::nullopt;
    int in_pipe[2];
    int out_pipe[2];
    if (::pipe(in_pipe) != 0)
        return std::nullopt;
    if (::pipe(out_pipe) != 0) {
        ::close(in_pipe[0]);
        ::close(in_pipe[1]);
        return std::nullopt;
    }
    std::vector<char*> raw;
    raw.reserve(argv.size() + 1);
    for (const auto& item : argv)
        raw.push_back(const_cast<char*>(item.c_str()));
    raw.push_back(nullptr);
    const pid_t pid = ::fork();
    if (pid == 0) {
        (void)::dup2(in_pipe[0], 0);
        (void)::dup2(out_pipe[1], 1);
        ::close(in_pipe[0]);
        ::close(in_pipe[1]);
        ::close(out_pipe[0]);
        ::close(out_pipe[1]);
        ::execvp(raw[0], raw.data());
        ::_exit(127);
    }
    ::close(in_pipe[0]);
    ::close(out_pipe[1]);
    if (pid < 0) {
        ::close(in_pipe[1]);
        ::close(out_pipe[0]);
        return std::nullopt;
    }
    Stream stream;
    stream.kind_ = Stream::Kind::Proc;
    stream.fd_in_ = out_pipe[0];
    stream.fd_out_ = in_pipe[1];
    stream.pid_ = pid;
    stream.open_ = true;
    return stream;
}
#endif

// ---------------------------------------------------------------------------
// TCP
// ---------------------------------------------------------------------------

std::optional<Socket> tcp_connect(std::string_view host, int port) {
    if (host.empty())
        return std::nullopt;
#if defined(_WIN32)
    ensure_winsock();
#endif
    addrinfo hints{};
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    const std::string service = std::to_string(port);
    const std::string host_text(host);
    addrinfo* results = nullptr;
    if (getaddrinfo(host_text.c_str(), service.c_str(), &hints, &results) != 0)
        return std::nullopt;
    Socket connected = INVALID_SOCKET_VALUE;
    for (addrinfo* it = results; it != nullptr; it = it->ai_next) {
#if defined(_WIN32)
        SOCKET socket = ::socket(it->ai_family, it->ai_socktype, it->ai_protocol);
        if (socket == INVALID_SOCKET)
            continue;
        if (::connect(socket, it->ai_addr, static_cast<int>(it->ai_addrlen)) == 0) {
            connected = static_cast<Socket>(socket);
            break;
        }
        closesocket(socket);
#else
        const int socket = ::socket(it->ai_family, it->ai_socktype, it->ai_protocol);
        if (socket < 0)
            continue;
        if (::connect(socket, it->ai_addr, it->ai_addrlen) == 0) {
            connected = socket;
            break;
        }
        ::close(socket);
#endif
    }
    freeaddrinfo(results);
    return connected == INVALID_SOCKET_VALUE ? std::nullopt : std::optional<Socket>(connected);
}

Socket tcp_listen(int port, int backlog) {
#if defined(_WIN32)
    ensure_winsock();
    SOCKET listener = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (listener == INVALID_SOCKET)
        return INVALID_SOCKET_VALUE;
    BOOL reuse = TRUE;
    setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char*>(&reuse),
               sizeof(reuse));
    sockaddr_in address{};
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = htonl(INADDR_ANY);
    address.sin_port = htons(static_cast<u_short>(port));
    if (::bind(listener, reinterpret_cast<sockaddr*>(&address), sizeof(address)) == SOCKET_ERROR ||
        ::listen(listener, backlog) == SOCKET_ERROR) {
        closesocket(listener);
        return INVALID_SOCKET_VALUE;
    }
    return static_cast<Socket>(listener);
#else
    const int listener = ::socket(AF_INET, SOCK_STREAM, 0);
    if (listener < 0)
        return INVALID_SOCKET_VALUE;
    int reuse = 1;
    (void)setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
    sockaddr_in address{};
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = htonl(INADDR_ANY);
    address.sin_port = htons(static_cast<std::uint16_t>(port));
    if (::bind(listener, reinterpret_cast<sockaddr*>(&address), sizeof(address)) != 0 ||
        ::listen(listener, backlog) != 0) {
        ::close(listener);
        return INVALID_SOCKET_VALUE;
    }
    return listener;
#endif
}

std::optional<Socket> tcp_accept(Socket listener) {
#if defined(_WIN32)
    const SOCKET accepted = ::accept(static_cast<SOCKET>(listener), nullptr, nullptr);
    if (accepted == INVALID_SOCKET)
        return std::nullopt;
    return static_cast<Socket>(accepted);
#else
    const int accepted = ::accept(static_cast<int>(listener), nullptr, nullptr);
    if (accepted < 0)
        return std::nullopt;
    return accepted;
#endif
}

void close_socket(Socket socket) {
    if (socket == INVALID_SOCKET_VALUE)
        return;
#if defined(_WIN32)
    closesocket(static_cast<SOCKET>(socket));
#else
    if (static_cast<int>(socket) > 2)
        ::close(static_cast<int>(socket));
#endif
}

// ---------------------------------------------------------------------------
// Process/platform helpers
// ---------------------------------------------------------------------------

void ignore_sigpipe() {
#if !defined(_WIN32)
    (void)::signal(SIGPIPE, SIG_IGN);
#endif
}

fs::path self_exe() {
#if defined(_WIN32)
    std::wstring buffer(32768, L'\0');
    const DWORD len = GetModuleFileNameW(nullptr, buffer.data(), static_cast<DWORD>(buffer.size()));
    if (len > 0) {
        buffer.resize(len);
        return fs::path(buffer);
    }
    return fs::path("vn.exe");
#elif defined(__APPLE__)
    std::uint32_t size = 0;
    _NSGetExecutablePath(nullptr, &size);
    std::string buffer(size, '\0');
    if (_NSGetExecutablePath(buffer.data(), &size) == 0) {
        char resolved[PATH_MAX];
        if (::realpath(buffer.c_str(), resolved))
            return fs::path(resolved);
        buffer.resize(std::strlen(buffer.c_str()));
        return fs::path(buffer);
    }
    return fs::path("vn");
#else
    std::string buffer(4096, '\0');
    const ssize_t len = ::readlink("/proc/self/exe", buffer.data(), buffer.size() - 1);
    if (len > 0) {
        buffer.resize(static_cast<std::size_t>(len));
        return fs::path(buffer);
    }
    return fs::path("vn");
#endif
}

std::string quote_shell(std::string_view word) {
    std::string out;
    out.reserve(word.size() + 2);
    out.push_back('\'');
    for (char c : word) {
        if (c == '\'')
            out += "'\\''";
        else
            out.push_back(c);
    }
    out.push_back('\'');
    return out;
}

std::string build_shell_command(const std::vector<std::string>& parts) {
    std::string out;
    for (const auto& part : parts) {
        if (!out.empty())
            out.push_back(' ');
        out += quote_shell(part);
    }
    return out;
}

// ---------------------------------------------------------------------------
// TLS
// ---------------------------------------------------------------------------

void* tls_server_ctx(std::string_view cert_path, std::string_view key_path) {
    SSL_CTX* ctx = SSL_CTX_new(TLS_server_method());
    if (!ctx)
        return nullptr;
    if (SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION) != 1)
        goto fail;
    if (SSL_CTX_use_certificate_chain_file(ctx, std::string(cert_path).c_str()) != 1)
        goto fail;
    if (SSL_CTX_use_PrivateKey_file(ctx, std::string(key_path).c_str(), SSL_FILETYPE_PEM) != 1)
        goto fail;
    if (SSL_CTX_check_private_key(ctx) != 1)
        goto fail;
    return ctx;
fail:
    SSL_CTX_free(ctx);
    return nullptr;
}

void* tls_client_ctx(bool pinned) {
    SSL_CTX* ctx = SSL_CTX_new(TLS_client_method());
    if (!ctx)
        return nullptr;
    if (SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION) != 1) {
        SSL_CTX_free(ctx);
        return nullptr;
    }
    if (pinned) {
        SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, nullptr);
        return ctx;
    }
    SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, nullptr);
    if (SSL_CTX_set_default_verify_paths(ctx) != 1) {
        SSL_CTX_free(ctx);
        return nullptr;
    }
    return ctx;
}

void* tls_accept(void* ctx, Socket fd) {
    SSL* ssl = SSL_new(static_cast<SSL_CTX*>(ctx));
    if (!ssl)
        return nullptr;
    if (SSL_set_fd(ssl, static_cast<int>(fd)) != 1 || SSL_accept(ssl) != 1) {
        SSL_free(ssl);
        return nullptr;
    }
    return ssl;
}

void* tls_connect(void* ctx, Socket fd, std::string_view host) {
    SSL* ssl = SSL_new(static_cast<SSL_CTX*>(ctx));
    if (!ssl)
        return nullptr;
    if (SSL_set_fd(ssl, static_cast<int>(fd)) != 1) {
        SSL_free(ssl);
        return nullptr;
    }
    if (!host.empty()) {
        const std::string text(host);
        SSL_set_tlsext_host_name(ssl, text.c_str());
        X509_VERIFY_PARAM* param = SSL_get0_param(ssl);
        X509_VERIFY_PARAM_set1_host(param, text.c_str(), 0);
    }
    if (SSL_connect(ssl) != 1) {
        SSL_free(ssl);
        return nullptr;
    }
    return ssl;
}

bool tls_exporter(void* ssl, std::uint8_t* out, std::size_t len) {
    static constexpr char label[] = "EXPORTER-veins-auth/1";
    return SSL_export_keying_material(static_cast<SSL*>(ssl), out, len, label, sizeof(label) - 1,
                                      nullptr, 0, 0) == 1;
}

bool tls_peer_sha256(void* ssl, std::uint8_t* out) {
    X509* cert = SSL_get1_peer_certificate(static_cast<SSL*>(ssl));
    if (!cert)
        return false;
    unsigned int len = 0;
    const bool ok = X509_digest(cert, EVP_sha256(), out, &len) == 1 && len == 32;
    X509_free(cert);
    return ok;
}

void tls_free(void* ssl) {
    if (!ssl)
        return;
    SSL_shutdown(static_cast<SSL*>(ssl));
    SSL_free(static_cast<SSL*>(ssl));
}

void tls_ctx_free(void* ctx) {
    if (ctx)
        SSL_CTX_free(static_cast<SSL_CTX*>(ctx));
}

std::string tls_error() {
    return ssl_error_string();
}

std::string to_hex(Bytes data) {
    static constexpr char digits[] = "0123456789abcdef";
    std::string out;
    out.reserve(data.size() * 2);
    for (std::uint8_t byte : data) {
        out.push_back(digits[byte >> 4]);
        out.push_back(digits[byte & 15]);
    }
    return out;
}

bool hex_equal(std::string_view a, std::string_view b) {
    auto skip = [](std::string_view text, std::size_t& index) {
        while (index < text.size() && text[index] == ':')
            ++index;
    };
    std::size_t ai = 0;
    std::size_t bi = 0;
    for (;;) {
        skip(a, ai);
        skip(b, bi);
        if (ai >= a.size() || bi >= b.size())
            return ai >= a.size() && bi >= b.size();
        auto lower = [](char c) { return static_cast<char>((c >= 'A' && c <= 'Z') ? c + 32 : c); };
        if (lower(a[ai]) != lower(b[bi]))
            return false;
        ++ai;
        ++bi;
    }
}

} // namespace vn::net
