/*
* (C) 2015,2016,2017 Jack Lloyd
* (C) 2016 Daniel Neus
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/internal/socket.h>

#include <botan/exceptn.h>
#include <botan/mem_ops.h>
#include <botan/internal/fmt.h>
#include <botan/internal/stl_util.h>
#include <botan/internal/target_info.h>
#include <chrono>

#if defined(BOTAN_HAS_BOOST_ASIO)
   /*
  * We don't need serial port support anyway, and asking for it causes
  * macro conflicts with termios.h when this file is included in the
  * amalgamation.
  */
   #define BOOST_ASIO_DISABLE_SERIAL_PORT
   #include <boost/asio.hpp>
   #include <boost/asio/system_timer.hpp>

#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS)
   #include <errno.h>
   #include <fcntl.h>
   #include <netdb.h>
   #include <netinet/in.h>
   #include <string.h>
   #include <sys/socket.h>
   #include <sys/time.h>
   #include <unistd.h>

#elif defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
   #include <ws2tcpip.h>
#endif

namespace Botan {

namespace {

#if defined(BOTAN_HAS_BOOST_ASIO)

class Asio_Socket final : public OS::Socket {
   public:
      Asio_Socket(std::string_view hostname, std::string_view service, std::chrono::milliseconds timeout) :
            m_timeout(timeout), m_timer(m_io), m_tcp(m_io) {
         m_timer.expires_after(m_timeout);
         check_timeout();

         // Resolve asynchronously so the timer covers DNS as well as connect.
         // check_timeout() only closes m_tcp, which isn't open yet during the
         // resolve, so cancel the resolver inline if the deadline passes; that
         // delivers operation_aborted to the callback and breaks the loop.
         boost::asio::ip::tcp::resolver resolver(m_io);
         boost::asio::ip::tcp::resolver::results_type dns_iter;
         boost::system::error_code resolve_ec = boost::asio::error::would_block;
         resolver.async_resolve(
            std::string{hostname}, std::string{service}, [&](const boost::system::error_code& e, auto results) {
               resolve_ec = e;
               dns_iter = std::move(results);
            });
         while(resolve_ec == boost::asio::error::would_block) {
            if(m_timer.expiry() < decltype(m_timer)::clock_type::now()) {
               resolver.cancel();
            }
            m_io.run_one();
         }
         if(resolve_ec) {
            throw boost::system::system_error(resolve_ec);
         }

         boost::system::error_code ec = boost::asio::error::would_block;

         auto connect_cb = [&ec](const boost::system::error_code& e, const auto&) { ec = e; };

         boost::asio::async_connect(m_tcp, dns_iter.begin(), dns_iter.end(), connect_cb);

         while(ec == boost::asio::error::would_block) {
            m_io.run_one();
         }

         if(ec) {
            throw boost::system::system_error(ec);
         }
         if(!m_tcp.is_open()) {
            throw System_Error(fmt("Connection to host {} failed", hostname));
         }
      }

      void write(std::span<const uint8_t> buf) override {
         m_timer.expires_after(m_timeout);

         boost::system::error_code ec = boost::asio::error::would_block;

         boost::asio::async_write(m_tcp,
                                  boost::asio::buffer(buf.data(), buf.size()),
                                  [&ec](const boost::system::error_code& e, size_t) { ec = e; });

         while(ec == boost::asio::error::would_block) {
            m_io.run_one();
         }

         if(ec) {
            throw boost::system::system_error(ec);
         }
      }

      size_t read(uint8_t buf[], size_t len) override {
         m_timer.expires_after(m_timeout);

         boost::system::error_code ec = boost::asio::error::would_block;
         size_t got = 0;

         m_tcp.async_read_some(boost::asio::buffer(buf, len), [&](boost::system::error_code cb_ec, size_t cb_got) {
            ec = cb_ec;
            got = cb_got;
         });

         while(ec == boost::asio::error::would_block) {
            m_io.run_one();
         }

         if(ec) {
            if(ec == boost::asio::error::eof) {
               return 0;
            }
            throw boost::system::system_error(ec);  // Some other error.
         }

         return got;
      }

   private:
      void check_timeout() {
         if(m_tcp.is_open() && m_timer.expiry() < decltype(m_timer)::clock_type::now()) {
            boost::system::error_code err;

            // NOLINTNEXTLINE(bugprone-unused-return-value,cert-err33-c)
            m_tcp.close(err);
         }

         // NOLINTNEXTLINE(*-avoid-bind) FIXME - unclear why we can't use a lambda here
         m_timer.async_wait(std::bind(&Asio_Socket::check_timeout, this));
      }

      const std::chrono::milliseconds m_timeout;
      boost::asio::io_context m_io;
      boost::asio::system_timer m_timer;
      boost::asio::ip::tcp::socket m_tcp;
};

#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)

namespace {

// MSG_NOSIGNAL on the send call prevents SIGPIPE when the peer has gone away
// (Linux, the BSDs, Cygwin). macOS doesn't define it; we set SO_NOSIGPIPE on
// the socket instead. Windows has no SIGPIPE.
   #if defined(MSG_NOSIGNAL)
constexpr int botan_send_flags = MSG_NOSIGNAL;
   #else
constexpr int botan_send_flags = 0;
   #endif

}  // namespace

class BSD_Socket final : public OS::Socket {
   private:
   #if defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
      typedef SOCKET socket_type;
      typedef int socket_op_ret_type;
      typedef int socklen_type;
      typedef int sendrecv_len_type;

      static socket_type invalid_socket() { return INVALID_SOCKET; }

      static void close_socket(socket_type s) { ::closesocket(s); }

      static int last_socket_error() { return ::WSAGetLastError(); }

      static std::string get_last_socket_error() { return std::to_string(::WSAGetLastError()); }

      static bool nonblocking_connect_in_progress() { return (::WSAGetLastError() == WSAEWOULDBLOCK); }

      static bool last_error_is_retryable() { return (::WSAGetLastError() == WSAEINTR); }

      static void set_nonblocking(socket_type s) {
         u_long nonblocking = 1;
         ::ioctlsocket(s, FIONBIO, &nonblocking);
      }

      static void socket_init() {
         WSAData wsa_data;
         WORD wsa_version = MAKEWORD(2, 2);

         if(::WSAStartup(wsa_version, &wsa_data) != 0) {
            throw System_Error("WSAStartup() failed", WSAGetLastError());
         }

         if(LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2) {
            ::WSACleanup();
            throw System_Error("Could not find a usable version of Winsock.dll");
         }
      }

      static void socket_fini() { ::WSACleanup(); }
   #else
      typedef int socket_type;
      typedef ssize_t socket_op_ret_type;
      typedef socklen_t socklen_type;
      typedef size_t sendrecv_len_type;

      static socket_type invalid_socket() { return -1; }

      static void close_socket(socket_type s) { ::close(s); }

      static int last_socket_error() { return errno; }

      static std::string get_last_socket_error() { return ::strerror(errno); }

      static bool nonblocking_connect_in_progress() { return (errno == EINPROGRESS); }

      static bool last_error_is_retryable() { return (errno == EINTR); }

      static void set_nonblocking(socket_type s) {
         // NOLINTNEXTLINE(*-vararg)
         if(::fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
            throw System_Error("Setting socket to non-blocking state failed", errno);
         }
      }

      static void socket_init() {}

      static void socket_fini() {}
   #endif

   public:
      BSD_Socket(std::string_view hostname, std::string_view service, std::chrono::microseconds timeout) :
            m_timeout(timeout), m_socket(invalid_socket()) {
         socket_init();

         // A constructor that throws does not run its destructor, so do
         // cleanup explicitly on any failure between socket_init() above and
         // the end of construction below.
         try {
            do_connect(hostname, service);
         } catch(...) {
            if(m_socket != invalid_socket()) {
               close_socket(m_socket);
               m_socket = invalid_socket();
            }
            socket_fini();
            throw;
         }
      }

   private:
      void do_connect(std::string_view hostname, std::string_view service) {
         const std::string hostname_str(hostname);
         const std::string service_str(service);

         addrinfo hints{};
         hints.ai_family = AF_UNSPEC;
         hints.ai_socktype = SOCK_STREAM;

         unique_addr_info_ptr res = nullptr;

         // getaddrinfo blocks; POSIX has no portable way to time-bound it
         // without spinning up a thread. Time spent here is not deducted
         // from the connect budget below.
         const int rc = ::getaddrinfo(hostname_str.c_str(), service_str.c_str(), &hints, Botan::out_ptr(res));
         if(rc != 0) {
            throw System_Error(fmt("Name resolution failed for {}", hostname), rc);
         }

         // Bound the total connect phase by the requested timeout, regardless of
         // how many candidate addresses getaddrinfo returns.
         const auto connect_deadline = std::chrono::steady_clock::now() + m_timeout;

         for(const addrinfo* rp = res.get(); (m_socket == invalid_socket()) && (rp != nullptr); rp = rp->ai_next) {
            if(rp->ai_family != AF_INET && rp->ai_family != AF_INET6) {
               continue;
            }

            const auto remaining = std::chrono::duration_cast<std::chrono::microseconds>(
               connect_deadline - std::chrono::steady_clock::now());
            if(remaining <= std::chrono::microseconds::zero()) {
               break;
            }

            m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);

            if(m_socket == invalid_socket()) {
               // unsupported socket type?
               continue;
            }

   #if !defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
            // POSIX fd_set is a bitfield indexed by fd value, so FD_SET(fd, ...)
            // with fd >= FD_SETSIZE writes past the end of the structure. Refuse
            // up front rather than corrupt memory in the select() path below.
            // (Windows fd_set is an array of SOCKET handles, not vulnerable.)
            if(m_socket >= FD_SETSIZE) {
               close_socket(m_socket);
               m_socket = invalid_socket();
               throw System_Error("Socket descriptor exceeds FD_SETSIZE; select() would be unsafe");
            }
   #endif

   #if defined(SO_NOSIGPIPE)
            // macOS doesn't have MSG_NOSIGNAL; set the socket option instead so
            // ::send() on a peer-closed socket returns EPIPE rather than
            // delivering SIGPIPE to the process. Ignore failures (best-effort).
            {
               const int on = 1;
               (void)::setsockopt(m_socket, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof(on));
            }
   #endif

            set_nonblocking(m_socket);

            const int err = ::connect(m_socket, rp->ai_addr, static_cast<socklen_type>(rp->ai_addrlen));

            if(err == -1) {
               int active = 0;
               if(nonblocking_connect_in_progress()) {
                  struct timeval timeout_tv = make_timeout_tv_from(remaining);
                  fd_set write_set;
                  FD_ZERO(&write_set);
                  FD_SET(m_socket, &write_set);

                  active = ::select(static_cast<int>(m_socket + 1), nullptr, &write_set, nullptr, &timeout_tv);

                  if(active > 0) {
                     int socket_error = 0;
                     socklen_t len = sizeof(socket_error);

                     if(::getsockopt(m_socket, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&socket_error), &len) <
                        0) {
                        throw System_Error("Error calling getsockopt", last_socket_error());
                     }

                     if(socket_error != 0) {
                        active = 0;
                     }
                  }
               }

               // 0 = select timeout, < 0 = select error: both indicate the
               // connect attempt failed and the socket is not usable.
               if(active <= 0) {
                  close_socket(m_socket);
                  m_socket = invalid_socket();
                  continue;
               }
            }
         }

         if(m_socket == invalid_socket()) {
            throw System_Error(
               fmt("Connecting to {} for service {} failed with errno {}", hostname, service, last_socket_error()),
               last_socket_error());
         }
      }

   public:
      ~BSD_Socket() override {
         close_socket(m_socket);
         m_socket = invalid_socket();
         socket_fini();
      }

      BSD_Socket(const BSD_Socket& other) = delete;
      BSD_Socket(BSD_Socket&& other) = delete;
      BSD_Socket& operator=(const BSD_Socket& other) = delete;
      BSD_Socket& operator=(BSD_Socket&& other) = delete;

      void write(std::span<const uint8_t> buf) override {
         const size_t len = buf.size();

         size_t sent_so_far = 0;
         while(sent_so_far != len) {
            fd_set write_set;
            FD_ZERO(&write_set);
            FD_SET(m_socket, &write_set);

            struct timeval timeout = make_timeout_tv();
            const int active = ::select(static_cast<int>(m_socket + 1), nullptr, &write_set, nullptr, &timeout);

            if(active < 0) {
               if(last_error_is_retryable()) {
                  continue;
               }
               throw System_Error("Socket select failed", last_socket_error());
            }

            if(active == 0) {
               throw System_Error("Timeout during socket write");
            }

            const size_t left = len - sent_so_far;
            const socket_op_ret_type sent = ::send(m_socket,
                                                   cast_uint8_ptr_to_char(&buf[sent_so_far]),
                                                   static_cast<sendrecv_len_type>(left),
                                                   botan_send_flags);
            if(sent < 0) {
               if(last_error_is_retryable()) {
                  continue;
               }
               throw System_Error("Socket write failed", last_socket_error());
            } else {
               sent_so_far += static_cast<size_t>(sent);
            }
         }
      }

      size_t read(uint8_t buf[], size_t len) override {
         for(;;) {
            fd_set read_set;
            FD_ZERO(&read_set);
            FD_SET(m_socket, &read_set);

            struct timeval timeout = make_timeout_tv();
            const int active = ::select(static_cast<int>(m_socket + 1), &read_set, nullptr, nullptr, &timeout);

            if(active < 0) {
               if(last_error_is_retryable()) {
                  continue;
               }
               throw System_Error("Socket select failed", last_socket_error());
            }

            if(active == 0) {
               throw System_Error("Timeout during socket read");
            }

            const socket_op_ret_type got =
               ::recv(m_socket, cast_uint8_ptr_to_char(buf), static_cast<sendrecv_len_type>(len), 0);

            if(got < 0) {
               if(last_error_is_retryable()) {
                  continue;
               }
               throw System_Error("Socket read failed", last_socket_error());
            }

            return static_cast<size_t>(got);
         }
      }

   private:
      struct timeval make_timeout_tv() const { return make_timeout_tv_from(m_timeout); }

      static struct timeval make_timeout_tv_from(std::chrono::microseconds us) {
         struct timeval tv {};

         tv.tv_sec = static_cast<decltype(timeval::tv_sec)>(us.count() / 1000000);
         tv.tv_usec = static_cast<decltype(timeval::tv_usec)>(us.count() % 1000000);
         return tv;
      }

      const std::chrono::microseconds m_timeout;
      socket_type m_socket;

      using unique_addr_info_ptr = std::unique_ptr<addrinfo, decltype([](addrinfo* p) {
                                                      if(p != nullptr) {
                                                         ::freeaddrinfo(p);
                                                      }
                                                   })>;
};

#endif

}  // namespace

std::unique_ptr<OS::Socket> OS::open_socket(std::string_view hostname,
                                            std::string_view service,
                                            std::chrono::milliseconds timeout) {
#if defined(BOTAN_HAS_BOOST_ASIO)
   return std::make_unique<Asio_Socket>(hostname, service, timeout);

#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
   return std::make_unique<BSD_Socket>(hostname, service, timeout);

#else
   BOTAN_UNUSED(hostname, service, timeout);
   // No sockets for you
   return std::unique_ptr<Socket>();
#endif
}

}  // namespace Botan
