/*
  This file is part of Anastasis
  Copyright (C) 2020, 2021 Anastasis SARL

  Anastasis is free software; you can redistribute it and/or modify it under the
  terms of the GNU General Public License as published by the Free Software
  Foundation; either version 3, or (at your option) any later version.

  Anastasis 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 for more details.

  You should have received a copy of the GNU General Public License along with
  Anastasis; see the file COPYING.GPL.  If not, see <http://www.gnu.org/licenses/>
*/
/**
 * @file restclient/anastasis_api_config.c
 * @brief Implementation of the /config GET
 * @author Christian Grothoff
 * @author Dennis Neufeld
 * @author Dominik Meister
 */
#include "platform.h"
#include <curl/curl.h>
#include <microhttpd.h> /* just for HTTP status codes */
#include "anastasis_service.h"
#include "anastasis_api_curl_defaults.h"
#include <gnunet/gnunet_json_lib.h>
#include <taler/taler_json_lib.h>


/**
 * Which version of the Taler protocol is implemented
 * by this library?  Used to determine compatibility.
 *
 * Raised to 1 when the key derivation was fixed to use the full context
 * string: every key derived by a 0:x:x client differs, so backups written by
 * one side cannot be recovered by the other.  Hence 0 must stay outside of
 * the compatibility range.
 *
 * Raised to 3 for multi-currency pricing, which only *added* the plural
 * fee fields and "currencies" to /config.  The age therefore stays at 1:
 * a version 2 provider is still usable, we just synthesize the plural
 * fields from the scalar ones below.
 */
#define ANASTASIS_PROTOCOL_CURRENT 3

/**
 * How many versions are we backwards compatible with?
 */
#define ANASTASIS_PROTOCOL_AGE 1


struct ANASTASIS_ConfigOperation
{
  /**
   * The url for this request.
   */
  char *url;

  /**
   * Handle for the request.
   */
  struct GNUNET_CURL_Job *job;

  /**
   * Reference to the execution context.
   */
  struct GNUNET_CURL_Context *ctx;

  /**
  * The callback to pass the backend response to
  */
  ANASTASIS_ConfigCallback cb;

  /**
   * Closure for @a cb.
   */
  void *cb_cls;

};


/**
 * Parse a successful GET /config response and hand it to @a cb.
 *
 * Kept apart from #handle_config_finished() because the price lists are
 * heap allocated: every exit path from here has to release them, and a
 * flat sequence of `break's out of a switch cannot express that.
 *
 * @param json the response to parse
 * @param url provider URL, for logging
 * @param[in,out] acfg configuration to fill in and report
 * @param cb function to call with the parsed configuration
 * @param cb_cls closure for @a cb
 * @return #GNUNET_OK if @a cb was invoked, #GNUNET_SYSERR if @a json was
 *         unusable and the caller must report the failure itself
 */
static enum GNUNET_GenericReturnValue
handle_config_ok (const json_t *json,
                  const char *url,
                  struct ANASTASIS_Config *acfg,
                  ANASTASIS_ConfigCallback cb,
                  void *cb_cls)
{
  const char *name;
  const json_t *methods;
  const json_t *currencies = NULL;
  struct TALER_JSON_ProtocolVersion pv;
  struct ANASTASIS_AuthorizationMethodConfig *mcfg = NULL;
  const char **carr = NULL;
  unsigned int carr_len = 0;
  enum GNUNET_GenericReturnValue ret = GNUNET_SYSERR;
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_string ("name",
                             &name),
    GNUNET_JSON_spec_string ("business_name",
                             &acfg->details.ok.business_name),
    GNUNET_JSON_spec_string ("version",
                             &acfg->details.ok.version),
    TALER_JSON_spec_version ("version",
                             &pv),
    GNUNET_JSON_spec_array_const ("methods",
                                  &methods),
    GNUNET_JSON_spec_uint32 ("storage_limit_in_megabytes",
                             &acfg->details.ok.storage_limit_in_megabytes),
    TALER_JSON_spec_amount_any ("annual_fee",
                                &acfg->details.ok.annual_fee),
    TALER_JSON_spec_amount_any ("truth_upload_fee",
                                &acfg->details.ok.truth_upload_fee),
    TALER_JSON_spec_amount_any ("liability_limit",
                                &acfg->details.ok.liability_limit),
    /* Added in protocol version 3.  A version 2 provider omits them, and
       they are synthesized from the scalar fields further down. */
    GNUNET_JSON_spec_mark_optional (
      GNUNET_JSON_spec_array_const ("currencies",
                                    &currencies),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      TALER_JSON_spec_amount_list ("annual_fees",
                                   &acfg->details.ok.annual_fees),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      TALER_JSON_spec_amount_list ("truth_upload_fees",
                                   &acfg->details.ok.truth_upload_fees),
      NULL),
    GNUNET_JSON_spec_mark_optional (
      TALER_JSON_spec_amount_list ("liability_limits",
                                   &acfg->details.ok.liability_limits),
      NULL),
    GNUNET_JSON_spec_fixed_auto ("provider_salt",
                                 &acfg->details.ok.provider_salt),
    GNUNET_JSON_spec_end ()
  };

  if (GNUNET_OK !=
      GNUNET_JSON_parse (json,
                         spec,
                         NULL, NULL))
  {
    GNUNET_break_op (0);
    json_dumpf (json,
                stderr,
                JSON_INDENT (2));
    acfg->ec = TALER_EC_GENERIC_REPLY_MALFORMED;
    return GNUNET_SYSERR;
  }
  if (0 != strcmp (name,
                   "anastasis"))
  {
    GNUNET_break_op (0);
    acfg->ec = TALER_EC_GENERIC_REPLY_MALFORMED;
    goto cleanup;
  }
  if ( (ANASTASIS_PROTOCOL_CURRENT < pv.current) &&
       (ANASTASIS_PROTOCOL_CURRENT < pv.current - pv.age) )
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Provider protocol version too new\n");
    acfg->ec = TALER_EC_GENERIC_VERSION_MALFORMED;
    goto cleanup;
  }
  if ( (ANASTASIS_PROTOCOL_CURRENT > pv.current) &&
       (ANASTASIS_PROTOCOL_CURRENT - ANASTASIS_PROTOCOL_AGE > pv.current) )
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Provider protocol version too old\n");
    GNUNET_break_op (0);
    acfg->ec = TALER_EC_GENERIC_VERSION_MALFORMED;
    goto cleanup;
  }
  acfg->details.ok.methods_length = (unsigned int) json_array_size (methods);
  if (((size_t) acfg->details.ok.methods_length) !=
      json_array_size (methods))
  {
    GNUNET_break_op (0);
    acfg->ec = TALER_EC_GENERIC_REPLY_MALFORMED;
    goto cleanup;
  }
  /* Bound the arrays so a malicious provider cannot force an unbounded
     allocation (a ~40 MB response could otherwise yield ~10^6 elements). */
  if (acfg->details.ok.methods_length > 1024)
  {
    GNUNET_break_op (0);
    acfg->ec = TALER_EC_GENERIC_REPLY_MALFORMED;
    goto cleanup;
  }

  /* Currencies: given outright by a version 3 provider, otherwise the
     single currency the provider was already quoting everything in. */
  if (NULL != currencies)
  {
    size_t clen = json_array_size (currencies);
    size_t idx;
    json_t *entry;

    if ( (0 == clen) ||
         (clen > 1024) )
    {
      GNUNET_break_op (0);
      acfg->ec = TALER_EC_GENERIC_REPLY_MALFORMED;
      goto cleanup;
    }
    carr = GNUNET_new_array (clen,
                             const char *);
    json_array_foreach (currencies, idx, entry)
    {
      if (! json_is_string (entry))
      {
        GNUNET_break_op (0);
        acfg->ec = TALER_EC_GENERIC_REPLY_MALFORMED;
        goto cleanup;
      }
      carr[idx] = json_string_value (entry);
      carr_len = idx + 1;
    }
  }
  else
  {
    carr = GNUNET_new_array (1,
                             const char *);
    carr[0] = acfg->details.ok.annual_fee.currency;
    carr_len = 1;
  }
  acfg->details.ok.currencies = carr;
  acfg->details.ok.currencies_len = carr_len;

  /* Plural fee fields: a version 2 provider has none, so make a
     one-element list out of what it did send.  Everything downstream can
     then work with lists only. */
  {
    struct
    {
      const struct TALER_Amount *scalar;
      struct TALER_AmountList *list;
    } fees[] = {
      { &acfg->details.ok.annual_fee, &acfg->details.ok.annual_fees },
      { &acfg->details.ok.truth_upload_fee,
        &acfg->details.ok.truth_upload_fees },
      { &acfg->details.ok.liability_limit,
        &acfg->details.ok.liability_limits }
    };

    for (unsigned int i = 0; i<sizeof (fees) / sizeof (fees[0]); i++)
    {
      if (0 != fees[i].list->tal_len)
        continue;
      GNUNET_array_append (fees[i].list->tal,
                           fees[i].list->tal_len,
                           *fees[i].scalar);
    }
  }

  mcfg = GNUNET_new_array (GNUNET_NZL (acfg->details.ok.methods_length),
                           struct ANASTASIS_AuthorizationMethodConfig);
  for (unsigned int i = 0; i<acfg->details.ok.methods_length; i++)
  {
    struct ANASTASIS_AuthorizationMethodConfig *m = &mcfg[i];
    struct GNUNET_JSON_Specification ispec[] = {
      GNUNET_JSON_spec_string ("type",
                               &m->type),
      TALER_JSON_spec_amount_any ("cost",
                                  &m->usage_fee),
      GNUNET_JSON_spec_mark_optional (
        TALER_JSON_spec_amount_list ("costs",
                                     &m->usage_fees),
        NULL),
      GNUNET_JSON_spec_end ()
    };

    if (GNUNET_OK !=
        GNUNET_JSON_parse (json_array_get (methods,
                                           i),
                           ispec,
                           NULL, NULL))
    {
      GNUNET_break_op (0);
      acfg->ec = TALER_EC_GENERIC_REPLY_MALFORMED;
      goto cleanup;
    }
    if (0 == m->usage_fees.tal_len)
      GNUNET_array_append (m->usage_fees.tal,
                           m->usage_fees.tal_len,
                           m->usage_fee);
  }
  acfg->details.ok.methods = mcfg;
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Good backend found at `%s'\n",
              url);
  cb (cb_cls,
      acfg);
  ret = GNUNET_OK;
cleanup:
  if (NULL != mcfg)
  {
    for (unsigned int i = 0; i<acfg->details.ok.methods_length; i++)
      TALER_amount_list_free (&mcfg[i].usage_fees);
    GNUNET_free (mcfg);
  }
  GNUNET_free (carr);
  GNUNET_JSON_parse_free (spec);
  if (GNUNET_OK != ret)
  {
    /* Everything in there points into memory just released, and the
       caller is about to report a failure with the same struct. */
    memset (&acfg->details.ok,
            0,
            sizeof (acfg->details.ok));
  }
  return ret;
}


/**
 * Function called when we're done processing the
 * HTTP /config request.
 *
 * @param cls the `struct ANASTASIS_ConfigOperation`
 * @param response_code HTTP response code, 0 on error
 * @param response parsed JSON result, NULL on error
 */
static void
handle_config_finished (void *cls,
                        long response_code,
                        const void *response)
{
  struct ANASTASIS_ConfigOperation *co = cls;
  const json_t *json = response;
  struct ANASTASIS_Config acfg = {
    .http_status = response_code,
    .response = json
  };

  co->job = NULL;
  switch (response_code)
  {
  case 0:
    /* No reply received */
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                "Backend `%s' failed to respond to GET /config\n",
                co->url);
    break;
  case MHD_HTTP_OK:
    if (GNUNET_OK ==
        handle_config_ok (json,
                          co->url,
                          &acfg,
                          co->cb,
                          co->cb_cls))
    {
      ANASTASIS_config_cancel (co);
      return;
    }
    acfg.http_status = 0;
    break;
  case MHD_HTTP_BAD_REQUEST:
    /* This should never happen, either us or the anastasis server is buggy
       (or API version conflict); just pass JSON reply to the application */
    break;
  case MHD_HTTP_NOT_FOUND:
    /* Nothing really to verify */
    break;
  case MHD_HTTP_INTERNAL_SERVER_ERROR:
    /* Server had an internal issue; we should retry, but this API
       leaves this to the application */
    break;
  default:
    /* unexpected response code */
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Unexpected response code %u\n",
                (unsigned int) response_code);
    GNUNET_break_op (0);
    break;
  }
  co->cb (co->cb_cls,
          &acfg);
  ANASTASIS_config_cancel (co);
}


struct ANASTASIS_ConfigOperation *
ANASTASIS_get_config (struct GNUNET_CURL_Context *ctx,
                      const char *base_url,
                      ANASTASIS_ConfigCallback cb,
                      void *cb_cls)
{
  struct ANASTASIS_ConfigOperation *co;

  co = GNUNET_new (struct ANASTASIS_ConfigOperation);
  co->url = TALER_url_join (base_url,
                            "config",
                            NULL);
  co->ctx = ctx;
  co->cb = cb;
  co->cb_cls = cb_cls;
  {
    CURL *eh;

    eh = ANASTASIS_curl_easy_get_ (co->url);
    co->job = GNUNET_CURL_job_add (ctx,
                                   eh,
                                   &handle_config_finished,
                                   co);
  }
  if (NULL == co->job)
  {
    GNUNET_free (co->url);
    GNUNET_free (co);
    return NULL;
  }
  return co;
}


void
ANASTASIS_config_cancel (struct ANASTASIS_ConfigOperation *co)
{
  if (NULL != co->job)
  {
    GNUNET_CURL_job_cancel (co->job);
    co->job = NULL;
  }
  GNUNET_free (co->url);
  GNUNET_free (co);
}


/* end of anastasis_api_config.c */
