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

  TALER 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.

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

  You should have received a copy of the GNU General Public License along with
  TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
*/
/**
 * @file mhd.c
 * @brief MHD utility functions (used by the merchant backend)
 * @author Christian Grothoff
 */
#include "platform.h"
#include "taler_util.h"
#include "taler_mhd_lib.h"


enum GNUNET_GenericReturnValue
TALER_mhd_is_https (struct MHD_Connection *connection)
{
  const union MHD_ConnectionInfo *ci;
  const union MHD_DaemonInfo *di;
  const char *forwarded_proto = MHD_lookup_connection_value (connection,
                                                             MHD_HEADER_KIND,
                                                             "X-Forwarded-Proto");

  if (NULL != forwarded_proto)
  {
    if (0 == strcasecmp (forwarded_proto,
                         "https"))
      return GNUNET_YES;
    if (0 == strcasecmp (forwarded_proto,
                         "http"))
      return GNUNET_NO;
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  /* likely not reverse proxy, figure out if we are
     http by asking MHD */
  ci = MHD_get_connection_info (connection,
                                MHD_CONNECTION_INFO_DAEMON);
  if (NULL == ci)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  di = MHD_get_daemon_info (ci->daemon,
                            MHD_DAEMON_INFO_FLAGS);
  if (NULL == di)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if (0 != (di->flags & MHD_USE_TLS))
    return GNUNET_YES;
  return GNUNET_NO;
}


bool
TALER_MHD_arg_to_yna (struct MHD_Connection *connection,
                      const char *arg,
                      enum TALER_EXCHANGE_YesNoAll default_val,
                      enum TALER_EXCHANGE_YesNoAll *yna)
{
  const char *str;

  str = MHD_lookup_connection_value (connection,
                                     MHD_GET_ARGUMENT_KIND,
                                     arg);
  if (NULL == str)
  {
    *yna = default_val;
    return true;
  }
  if (0 == strcasecmp (str, "yes"))
  {
    *yna = TALER_EXCHANGE_YNA_YES;
    return true;
  }
  if (0 == strcasecmp (str, "no"))
  {
    *yna = TALER_EXCHANGE_YNA_NO;
    return true;
  }
  if (0 == strcasecmp (str, "all"))
  {
    *yna = TALER_EXCHANGE_YNA_ALL;
    return true;
  }
  return false;
}
