/*
  This file is part of TALER
  Copyright (C) 2014-2025 Taler Systems SA

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

  TALER 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 Affero General Public License for more details.

  You should have received a copy of the GNU Affero General Public License along with
  TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
*/
/**
 * @file mhd2_responses.c
 * @brief API for generating HTTP replies
 * @author Florian Dold
 * @author Benedikt Mueller
 * @author Christian Grothoff
 */
#include "platform.h"
#include <zlib.h>
#include "taler_util.h"
#include "taler_mhd2_lib.h"


/**
 * Global options for response generation.
 */
static enum TALER_MHD2_GlobalOptions TM_go;


void
TALER_MHD2_setup (enum TALER_MHD2_GlobalOptions go)
{
  TM_go = go;
}


void
TALER_MHD2_add_global_headers (struct MHD_Response *response)
{
  if (0 != (TM_go & TALER_MHD2_GO_FORCE_CONNECTION_CLOSE))
    GNUNET_break (MHD_SC_OK ==
                  MHD_response_add_header (response,
                                           MHD_HTTP_HEADER_CONNECTION,
                                           "close"));
  /* The wallet, operating from a background page, needs CORS to
     be disabled otherwise browsers block access. */
  GNUNET_break (MHD_SC_OK ==
                MHD_response_add_header (response,
                                         MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN,
                                         "*"));
  GNUNET_break (MHD_SC_OK ==
                MHD_response_add_header (response,
                                         /* Not available as MHD constant yet */
                                         "Access-Control-Expose-Headers",
                                         "*"));
}


bool
TALER_MHD2_can_compress (struct MHD_Request *request)
{
  const struct MHD_StringNullable *aeb;
  const char *ae;
  const char *de;

  if (0 != (TM_go & TALER_MHD2_GO_DISABLE_COMPRESSION))
    return MHD_NO;
  aeb = MHD_request_get_value (request,
                               MHD_VK_HEADER,
                               MHD_HTTP_HEADER_ACCEPT_ENCODING);
  if (NULL == aeb)
    return false;
  ae = aeb->cstr;
  if (NULL == ae)
    return false;
  if (0 == strcmp (ae,
                   "*"))
    return true;
  de = strstr (ae,
               "deflate");
  if (NULL == de)
    return false;
  if ( ( (de == ae) ||
         (de[-1] == ',') ||
         (de[-1] == ' ') ) &&
       ( (de[strlen ("deflate")] == '\0') ||
         (de[strlen ("deflate")] == ',') ||
         (de[strlen ("deflate")] == ';') ) )
    return true;
  return false;
}


bool
TALER_MHD2_body_compress (void **buf,
                          size_t *buf_size)
{
  Bytef *cbuf;
  uLongf cbuf_size;
  int ret;

  cbuf_size = compressBound (*buf_size);
  cbuf = malloc (cbuf_size);
  if (NULL == cbuf)
    return false;
  ret = compress (cbuf,
                  &cbuf_size,
                  (const Bytef *) *buf,
                  *buf_size);
  if ( (Z_OK != ret) ||
       (cbuf_size >= *buf_size) )
  {
    /* compression failed */
    free (cbuf);
    return false;
  }
  free (*buf);
  *buf = (void *) cbuf;
  *buf_size = (size_t) cbuf_size;
  return true;
}


struct MHD_Response *
TALER_MHD2_make_json (enum MHD_HTTP_StatusCode sc,
                      const json_t *json)
{
  struct MHD_Response *response;
  char *json_str;

  json_str = json_dumps (json,
                         JSON_INDENT (2));
  if (NULL == json_str)
  {
    GNUNET_break (0);
    return NULL;
  }
  response = MHD_response_from_buffer (sc,
                                       strlen (json_str),
                                       json_str,
                                       &free,
                                       json_str);
  if (NULL == response)
  {
    free (json_str);
    GNUNET_break (0);
    return NULL;
  }
  TALER_MHD2_add_global_headers (response);
  GNUNET_break (MHD_SC_OK ==
                MHD_response_add_header (response,
                                         MHD_HTTP_HEADER_CONTENT_TYPE,
                                         "application/json"));
  return response;
}


struct MHD_Response *
TALER_MHD2_make_json_steal (enum MHD_HTTP_StatusCode sc,
                            json_t *json)
{
  struct MHD_Response *res;

  res = TALER_MHD2_make_json (sc,
                              json);
  json_decref (json);
  return res;
}


const struct MHD_Action *
TALER_MHD2_reply_json (struct MHD_Request *request,
                       const json_t *json,
                       enum MHD_HTTP_StatusCode sc)
{
  struct MHD_Response *response;
  void *json_str;
  size_t json_len;
  bool is_compressed;

  json_str = json_dumps (json,
                         JSON_INDENT (2));
  if (NULL == json_str)
  {
    /**
     * This log helps to figure out which
     * function called this one and assert-failed.
     */
    TALER_LOG_ERROR ("Aborting json-packing for HTTP code: %u\n",
                     sc);

    GNUNET_assert (0);
    return NULL;
  }
  json_len = strlen (json_str);
  /* try to compress the body */
  is_compressed = MHD_NO;
  if (TALER_MHD2_can_compress (request))
    is_compressed = TALER_MHD2_body_compress (&json_str,
                                              &json_len);
  response = MHD_response_from_buffer (sc,
                                       json_len,
                                       json_str,
                                       &free,
                                       json_str);
  if (NULL == response)
  {
    free (json_str);
    GNUNET_break (0);
    return NULL;
  }
  TALER_MHD2_add_global_headers (response);
  GNUNET_break (MHD_SC_OK ==
                MHD_response_add_header (response,
                                         MHD_HTTP_HEADER_CONTENT_TYPE,
                                         "application/json"));
  if (is_compressed)
  {
    /* Need to indicate to client that body is compressed */
    if (MHD_SC_OK ==
        MHD_response_add_header (response,
                                 MHD_HTTP_HEADER_CONTENT_ENCODING,
                                 "deflate"))
    {
      GNUNET_break (0);
      MHD_response_destroy (response);
      return NULL;
    }
  }

  return MHD_action_from_response (request,
                                   response);
}


const struct MHD_Action *
TALER_MHD2_reply_json_steal (struct MHD_Request *request,
                             json_t *json,
                             enum MHD_HTTP_StatusCode sc)
{
  const struct MHD_Action *ret;

  ret = TALER_MHD2_reply_json (request,
                               json,
                               sc);
  json_decref (json);
  return ret;
}


const struct MHD_Action *
TALER_MHD2_reply_cors_preflight (struct MHD_Request *request)
{
  struct MHD_Response *response;

  response = MHD_response_from_empty (MHD_HTTP_STATUS_NO_CONTENT);
  if (NULL == response)
    return NULL;
  /* This adds the Access-Control-Allow-Origin header.
   * All endpoints of the exchange allow CORS. */
  TALER_MHD2_add_global_headers (response);
  GNUNET_break (MHD_SC_OK ==
                MHD_response_add_header (response,
                                         /* Not available as MHD constant yet */
                                         "Access-Control-Allow-Headers",
                                         "*"));
  GNUNET_break (MHD_SC_OK ==
                MHD_response_add_header (response,
                                         /* Not available as MHD constant yet */
                                         "Access-Control-Allow-Methods",
                                         "*"));
  return MHD_action_from_response (request,
                                   response);
}


struct MHD_Response *
TALER_MHD2_make_error (enum TALER_ErrorCode ec,
                       const char *detail)
{
  return TALER_MHD2_MAKE_JSON_PACK (
    TALER_ErrorCode_get_http_status (ec),
    TALER_MHD2_PACK_EC (ec),
    GNUNET_JSON_pack_allow_null (
      GNUNET_JSON_pack_string ("detail", detail)));
}


const struct MHD_Action *
TALER_MHD2_reply_with_error (struct MHD_Request *request,
                             enum MHD_HTTP_StatusCode sc,
                             enum TALER_ErrorCode ec,
                             const char *detail)
{
  return TALER_MHD2_REPLY_JSON_PACK (
    request,
    sc,
    TALER_MHD2_PACK_EC (ec),
    GNUNET_JSON_pack_allow_null (
      GNUNET_JSON_pack_string ("detail", detail)));
}


const struct MHD_Action *
TALER_MHD2_reply_with_ec (struct MHD_Request *request,
                          enum TALER_ErrorCode ec,
                          const char *detail)
{
  unsigned int hc
    = TALER_ErrorCode_get_http_status (ec);

  if ( (0 == hc) ||
       (UINT_MAX == hc) )
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Invalid Taler error code %u provided for response!\n",
                (unsigned int) ec);
    hc = MHD_HTTP_STATUS_INTERNAL_SERVER_ERROR;
  }
  return TALER_MHD2_reply_with_error (request,
                                      (enum MHD_HTTP_StatusCode) hc,
                                      ec,
                                      detail);
}


const struct MHD_Action *
TALER_MHD2_reply_request_too_large (struct MHD_Request *request)
{
  return TALER_MHD2_reply_with_error (
    request,
    MHD_HTTP_STATUS_CONTENT_TOO_LARGE,
    TALER_EC_GENERIC_UPLOAD_EXCEEDS_LIMIT,
    NULL);
}


const struct MHD_Action *
TALER_MHD2_reply_agpl (struct MHD_Request *request,
                       const char *url)
{
  const char *agpl =
    "This server is licensed under the Affero GPL. You will now be redirected to the source code.";
  struct MHD_Response *response;

  response = MHD_response_from_buffer_static (MHD_HTTP_STATUS_FOUND,
                                              strlen (agpl),
                                              (void *) agpl);
  if (NULL == response)
  {
    GNUNET_break (0);
    return MHD_NO;
  }
  TALER_MHD2_add_global_headers (response);
  GNUNET_break (MHD_SC_OK ==
                MHD_response_add_header (response,
                                         MHD_HTTP_HEADER_CONTENT_TYPE,
                                         "text/plain"));
  if (MHD_SC_OK ==
      MHD_response_add_header (response,
                               MHD_HTTP_HEADER_LOCATION,
                               url))
  {
    GNUNET_break (0);
    MHD_response_destroy (response);
    return NULL;
  }
  return MHD_action_from_response (request,
                                   response);
}


const struct MHD_Action *
TALER_MHD2_reply_static (struct MHD_Request *request,
                         enum MHD_HTTP_StatusCode sc,
                         const char *mime_type,
                         const char *body,
                         size_t body_size)
{
  struct MHD_Response *response;

  response = MHD_response_from_buffer_static (sc,
                                              body_size,
                                              body);
  if (NULL == response)
  {
    GNUNET_break (0);
    return NULL;
  }
  TALER_MHD2_add_global_headers (response);
  if (NULL != mime_type)
    GNUNET_break (MHD_SC_OK ==
                  MHD_response_add_header (response,
                                           MHD_HTTP_HEADER_CONTENT_TYPE,
                                           mime_type));
  return MHD_action_from_response (request,
                                   response);
}


void
TALER_MHD2_get_date_string (struct GNUNET_TIME_Absolute at,
                            char date[128])
{
  static const char *const days[] =
  { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  static const char *const mons[] =
  { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
    "Nov", "Dec"};
  struct tm now;
  time_t t;
#if ! defined(HAVE_C11_GMTIME_S) && ! defined(HAVE_W32_GMTIME_S) && \
  ! defined(HAVE_GMTIME_R)
  struct tm*pNow;
#endif

  date[0] = 0;
  t = (time_t) (at.abs_value_us / 1000LL / 1000LL);
#if defined(HAVE_C11_GMTIME_S)
  if (NULL == gmtime_s (&t, &now))
    return;
#elif defined(HAVE_W32_GMTIME_S)
  if (0 != gmtime_s (&now, &t))
    return;
#elif defined(HAVE_GMTIME_R)
  if (NULL == gmtime_r (&t, &now))
    return;
#else
  pNow = gmtime (&t);
  if (NULL == pNow)
    return;
  now = *pNow;
#endif
  sprintf (date,
           "%3s, %02u %3s %04u %02u:%02u:%02u GMT",
           days[now.tm_wday % 7],
           (unsigned int) now.tm_mday,
           mons[now.tm_mon % 12],
           (unsigned int) (1900 + now.tm_year),
           (unsigned int) now.tm_hour,
           (unsigned int) now.tm_min,
           (unsigned int) now.tm_sec);
}


/* end of mhd_responses.c */
