/* Copyright (c) 2021, Oracle and/or its affiliates.
   Copyright (c) 2022, Percona and/or its affiliates.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.

This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation.  The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License, version 2.0, for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */

#include <cstring>
#include <memory>

#include "keyring_kms.h"

/* Keyring_encryption_service_impl */
#include <components/keyrings/common/component_helpers/include/keyring_encryption_service_definition.h>
/* Keyring_generator_service_impl */
#include <components/keyrings/common/component_helpers/include/keyring_generator_service_definition.h>
/* Keyring_load_service_impl */
#include <components/keyrings/common/component_helpers/include/keyring_load_service_definition.h>
/* Keyring_keys_metadata_iterator_service_impl */
#include <components/keyrings/common/component_helpers/include/keyring_keys_metadata_iterator_service_definition.h>
/* Log_builtins_keyring */
#include <components/keyrings/common/component_helpers/include/keyring_log_builtins_definition.h>
/* Keyring_metadata_query_service_impl */
#include <components/keyrings/common/component_helpers/include/keyring_metadata_query_service_definition.h>
/* Keyring_reader_service_impl */
#include <components/keyrings/common/component_helpers/include/keyring_reader_service_definition.h>
/* Keyring_writer_service_impl */
#include <components/keyrings/common/component_helpers/include/keyring_writer_service_definition.h>

#include <mysql/components/services/psi_memory.h>

/* clang-format off */
/**
  @page PAGE_COMPONENT_KEYRING_KMS component_keyring_kms

  This is keyring component services' implementation with kms as backend to
  store data. This component implements following keyring services:

  - keyring_aes
  - keyring_generate
  - keyring_keys_metadata_iterator
  - keyring_component_status
  - keyring_metadata_query
  - keyring_reader
  - keyring_reload
  - keyring_writer

  Data is stored in JSON format.
  @code
  {
    "version": "1.0",
    "elements": [
      {
        "user": "<user_name>",
        "data_id": "<name>",
        "data_type": "<data_type>",
        "data": "<hex_of_data>",
        "extension": []
      },
      ...
      ...
    ]
  }
  @endcode

  For most parts, component_keyring_kms relies on keyring_common library
  for implementation.

  The component relies on component_keyring_kms.cnf kms for configuration.

  Location of this configuration kms is same directory where component_keyring_kms
  shared library is located. This configuration kms should contain information
  in one of the following formats.

  1. Signal component to read configuration from current working directory
  @code
  {
    "read_local_config": true
  }
  @endcode

  2. Details of data kms and nature of keyring
  @code
  {
    "path": <path to data kms>,
    "read_only": <boolean value to signal state of the keyring>
  }
  @endcode

  If configuration kms co-located with shared library signals to read
  configuration locally, current working directory is searched for
  component_keyring_kms.cnf and expected format is 2.

  The component exposes following status information through
  keyring_metadata_query service implementation.

  1. Name of the keyring
  2. Author
  3. Implementation name
  4. Version
  5. Component status
  6. Data kms location
  7. Read only status

  <b>
    Note: Implementation does not provide concurrency control.
          That is responsibilty of users of the services.
  </b>
*/
/* clang-format on */

using keyring_common::operations::Keyring_operations;
using keyring_kms::backend::Keyring_kms_backend;
using keyring_kms::config::Config_pod;
using keyring_kms::config::g_component_path;
using keyring_kms::config::g_instance_path;

/** Dependencies */
REQUIRES_SERVICE_PLACEHOLDER(log_builtins);
REQUIRES_SERVICE_PLACEHOLDER(log_builtins_string);

SERVICE_TYPE(log_builtins) * log_bi;
SERVICE_TYPE(log_builtins_string) * log_bs;

namespace keyring_kms {
/** Keyring operations object */
Keyring_operations<Keyring_kms_backend> *g_keyring_operations = nullptr;

/** Keyring data source */
Config_pod *g_config_pod = nullptr;

/** Keyring state */
bool g_keyring_kms_inited = false;

/**
  Set path to component

  @param [in] component_path  Path to component library
  @param [in] instance_path   Path to instance specific config

  @returns initialization status
    @retval false Successful initialization
    @retval true  Error
*/
bool set_paths(const char *component_path, const char *instance_path) {
  char *save_c = g_component_path;
  char *save_i = g_instance_path;
  g_component_path = strdup(component_path != nullptr ? component_path : "");
  g_instance_path = strdup(instance_path != nullptr ? instance_path : "");
  if (g_component_path == nullptr || g_instance_path == nullptr) {
    g_component_path = save_c;
    g_instance_path = save_i;
    return true;
  }

  if (save_c != nullptr) free(save_c);
  if (save_i != nullptr) free(save_i);
  return false;
}

/**
  Intialize or re-initialize keyring.
  1. Read configuration kms
  2. Read keyring kms
  3. Initialize internal cache

  @returns Status of read operations
    @retval false Read config and data
    @retval true  Error reading config or data.
                  Existing data remains as it is.
*/
bool init_or_reinit_keyring() {
  /* Get config */
  std::unique_ptr<Config_pod> new_config_pod;
  if (keyring_kms::config::find_and_read_config_file(new_config_pod))
    return true;

  /* Initialize backend handler */
  std::unique_ptr<Keyring_kms_backend> new_backend =
      std::make_unique<Keyring_kms_backend>(
          new_config_pod.get()->config_file_path_,
          new_config_pod.get()->read_only_, *new_config_pod.get());
  if (!new_backend || !new_backend.get()->valid()) return true;

  /* Create new operations class */
  Keyring_operations<Keyring_kms_backend> *new_operations = new (std::nothrow)
      Keyring_operations<Keyring_kms_backend>(true, new_backend.release());
  if (new_operations == nullptr) return true;

  if (!new_operations->valid()) {
    delete new_operations;
    return true;
  }

  std::swap(g_keyring_operations, new_operations);
  Config_pod *current = g_config_pod;
  g_config_pod = new_config_pod.release();
  if (current != nullptr) delete current;
  if (new_operations != nullptr) delete new_operations;
  return false;
}

/**
  Initialization function for component - Used when loading the component
*/
static mysql_service_status_t keyring_kms_init() {
  log_bi = mysql_service_log_builtins;
  log_bs = mysql_service_log_builtins_string;

  g_component_callbacks = new (std::nothrow)
      keyring_common::service_implementation::Component_callbacks();

  return false;
}

/**
  De-initialization function for component - Used when unloading the component
*/
static mysql_service_status_t keyring_kms_deinit() {
  g_keyring_kms_inited = false;
  if (g_component_path) free(g_component_path);
  g_component_path = nullptr;
  if (g_instance_path) free(g_instance_path);
  g_instance_path = nullptr;

  if (g_keyring_operations != nullptr) delete g_keyring_operations;
  g_keyring_operations = nullptr;

  if (g_config_pod) delete g_config_pod;
  g_config_pod = nullptr;

  if (g_component_callbacks) delete g_component_callbacks;
  g_component_callbacks = nullptr;

  return false;
}

}  // namespace keyring_kms

/** ======================================================================= */

/** Component declaration related stuff */

/** This component provides implementation of following component services */
KEYRING_AES_IMPLEMENTOR(component_keyring_kms);
KEYRING_GENERATOR_IMPLEMENTOR(component_keyring_kms);
KEYRING_LOAD_IMPLEMENTOR(component_keyring_kms);
KEYRING_KEYS_METADATA_FORWARD_ITERATOR_IMPLEMENTOR(component_keyring_kms);
KEYRING_COMPONENT_STATUS_IMPLEMENTOR(component_keyring_kms);
KEYRING_COMPONENT_METADATA_QUERY_IMPLEMENTOR(component_keyring_kms);
KEYRING_READER_IMPLEMENTOR(component_keyring_kms);
KEYRING_WRITER_IMPLEMENTOR(component_keyring_kms);
/* Used if log_builtins is not available */
KEYRING_LOG_BUILTINS_IMPLEMENTOR(component_keyring_kms);
KEYRING_LOG_BUILTINS_STRING_IMPLEMENTOR(component_keyring_kms);

/** Component provides */
BEGIN_COMPONENT_PROVIDES(component_keyring_kms)
PROVIDES_SERVICE(component_keyring_kms, keyring_aes),
    PROVIDES_SERVICE(component_keyring_kms, keyring_generator),
    PROVIDES_SERVICE(component_keyring_kms, keyring_load),
    PROVIDES_SERVICE(component_keyring_kms, keyring_keys_metadata_iterator),
    PROVIDES_SERVICE(component_keyring_kms, keyring_component_status),
    PROVIDES_SERVICE(component_keyring_kms, keyring_component_metadata_query),
    PROVIDES_SERVICE(component_keyring_kms, keyring_reader_with_status),
    PROVIDES_SERVICE(component_keyring_kms, keyring_writer),
    PROVIDES_SERVICE(component_keyring_kms, log_builtins),
    PROVIDES_SERVICE(component_keyring_kms, log_builtins_string),
    END_COMPONENT_PROVIDES();

REQUIRES_SERVICE_PLACEHOLDER(psi_memory_v2);

/** List of dependencies */
BEGIN_COMPONENT_REQUIRES(component_keyring_kms)
REQUIRES_SERVICE(registry), REQUIRES_SERVICE(log_builtins),
    REQUIRES_SERVICE(log_builtins_string), REQUIRES_PSI_MEMORY_SERVICE,
    END_COMPONENT_REQUIRES();

/** Component description */
BEGIN_COMPONENT_METADATA(component_keyring_kms)
METADATA("mysql.author", "Percona Corporation"),
    METADATA("mysql.license", "GPL"),
    METADATA("component_keyring_kms_service", "1"), END_COMPONENT_METADATA();

/** Component declaration */
DECLARE_COMPONENT(component_keyring_kms, "component_keyring_kms")
keyring_kms::keyring_kms_init,
    keyring_kms::keyring_kms_deinit END_DECLARE_COMPONENT();

/** Component contained in this library */
DECLARE_LIBRARY_COMPONENTS &COMPONENT_REF(component_keyring_kms)
    END_DECLARE_LIBRARY_COMPONENTS
