/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *   Copyright 2020-2021 Couchbase, Inc.
 *
 *   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.
 */

#pragma once

#include "core/tls_context_provider.hxx"
#include "core/utils/movable_function.hxx"
#include "ip_protocol.hxx"

#include <asio/error.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/ip/udp.hpp>
#include <asio/ssl/context.hpp>
#include <asio/ssl/stream.hpp>
#include <asio/strand.hpp>

#include <cstdint>
#include <string>
#include <vector>

namespace couchbase::core::io
{

template<typename Resolver, typename Handler>
static void
async_resolve(ip_protocol protocol,
              Resolver& resolver,
              const std::string& hostname,
              const std::string& service,
              Handler&& handler)
{

  switch (protocol) {
    case ip_protocol::force_ipv4:
      return resolver.async_resolve(
        asio::ip::tcp::v4(), hostname, service, std::forward<Handler>(handler));
    case ip_protocol::force_ipv6:
      return resolver.async_resolve(
        asio::ip::tcp::v6(), hostname, service, std::forward<Handler>(handler));
    case ip_protocol::any:
      [[fallthrough]];
    default:
      /* use any protocol */
      break;
  }
  return resolver.async_resolve(hostname, service, std::forward<Handler>(handler));
}

/**
 * Configure server-identity verification on a client TLS stream prior to the
 * handshake: install a hostname (SAN/CN) verification callback and set the SNI
 * server name. When the underlying context is in verify_none mode the callback
 * has no effect, but SNI is still set.
 *
 * Without this, asio::ssl::verify_peer only validates that the certificate
 * chains to a trusted CA -- it does NOT check that the certificate identifies
 * the host being contacted (CWE-297).
 *
 * @param stream the client TLS stream that has connected but not yet handshaken
 * @param hostname the canonical hostname the caller intended to reach; must not
 * be empty (an empty hostname is rejected to avoid silently falling back to
 * CA-only validation)
 * @return a non-empty error_code if the hostname is empty, SNI could not be set,
 * or the hostname-verification callback could not be installed; empty on success
 */
[[nodiscard]] auto
configure_tls_handshake(asio::ssl::stream<asio::ip::tcp::socket>& stream,
                        const std::string& hostname) -> std::error_code;

class inherited_stream_registry;

// For a forked child, after io_context::notify_fork(fork_child) and before anything runs on ctx:
// releases and closes every registered stream and socket on ctx that another process opened,
// without shutdown(2). No pending operation on them can then read or write a connection the
// parent is still using. The DNS client registers its sockets through register_inherited_socket().
void
detach_inherited_sockets(asio::io_context& ctx);

// Records a socket on ctx that is not a stream, so that detach_inherited_sockets() in a forked
// child releases it. Held weakly: the registry does not keep the socket alive.
void
register_inherited_socket(asio::io_context& ctx,
                          const std::shared_ptr<asio::ip::tcp::socket>& socket);
void
register_inherited_socket(asio::io_context& ctx,
                          const std::shared_ptr<asio::ip::udp::socket>& socket);

class stream_impl
{
protected:
  inherited_stream_registry& inherited_;
  asio::strand<asio::io_context::executor_type> strand_;
  bool tls_;
  std::string id_{};
  // Identifies the process that opened this socket. close() compares it against
  // the process running at that moment to tell a socket inherited across fork(2)
  // apart from one this process opened itself, because an inherited socket must not
  // be shut down: shutdown(2) acts on the open file description, which fork(2)
  // shares, so it would tear down a connection the parent is still using.
  std::int64_t owner_pid_;

public:
  stream_impl(asio::io_context& ctx, bool is_tls);

  virtual ~stream_impl() = default;

  [[nodiscard]] auto log_prefix() const -> std::string_view;

  [[nodiscard]] auto id() const -> const std::string&;

  [[nodiscard]] auto get_executor() const noexcept
  {
    return strand_;
  }

  [[nodiscard]] virtual auto local_endpoint() const -> asio::ip::tcp::endpoint = 0;

  [[nodiscard]] virtual auto is_open() const -> bool = 0;

  virtual void close(utils::movable_function<void(std::error_code)>&& handler) = 0;

  virtual void set_options() = 0;

  // `hostname` is the canonical name the caller intends to reach; TLS streams use
  // it to verify the server certificate's identity (SAN/CN) and to set SNI.
  virtual void async_connect(const asio::ip::tcp::resolver::results_type::endpoint_type& endpoint,
                             const std::string& hostname,
                             utils::movable_function<void(std::error_code)>&& handler) = 0;

  virtual void async_write(
    std::vector<asio::const_buffer>& buffers,
    utils::movable_function<void(std::error_code, std::size_t)>&& handler) = 0;

  virtual void async_read_some(
    asio::mutable_buffer buffer,
    utils::movable_function<void(std::error_code, std::size_t)>&& handler) = 0;
};

class plain_stream_impl : public stream_impl
{
private:
  std::shared_ptr<asio::ip::tcp::socket> stream_;

public:
  explicit plain_stream_impl(asio::io_context& ctx);

  [[nodiscard]] auto local_endpoint() const -> asio::ip::tcp::endpoint override;

  [[nodiscard]] auto is_open() const -> bool override;

  void close(utils::movable_function<void(std::error_code)>&& handler) override;

  void set_options() override;

  void async_connect(const asio::ip::tcp::resolver::results_type::endpoint_type& endpoint,
                     const std::string& hostname,
                     utils::movable_function<void(std::error_code)>&& handler) override;

  void async_write(std::vector<asio::const_buffer>& buffers,
                   utils::movable_function<void(std::error_code, std::size_t)>&& handler) override;

  void async_read_some(
    asio::mutable_buffer buffer,
    utils::movable_function<void(std::error_code, std::size_t)>&& handler) override;
};

class tls_stream_impl : public stream_impl
{
private:
  tls_context_provider& tls_;
  std::shared_ptr<asio::ssl::stream<asio::ip::tcp::socket>> stream_;

public:
  tls_stream_impl(asio::io_context& ctx, tls_context_provider& tls);

  [[nodiscard]] auto local_endpoint() const -> asio::ip::tcp::endpoint override;

  [[nodiscard]] auto is_open() const -> bool override;

  void close(utils::movable_function<void(std::error_code)>&& handler) override;

  void set_options() override;

  void async_connect(const asio::ip::tcp::resolver::results_type::endpoint_type& endpoint,
                     const std::string& hostname,
                     utils::movable_function<void(std::error_code)>&& handler) override;

  void async_write(std::vector<asio::const_buffer>& buffers,
                   utils::movable_function<void(std::error_code, std::size_t)>&& handler) override;

  void async_read_some(
    asio::mutable_buffer buffer,
    utils::movable_function<void(std::error_code, std::size_t)>&& handler) override;
};

} // namespace couchbase::core::io
