/*
  This file is part of TALER
  Copyright (C) 2026 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 xml.c
 * @brief Common utility functions for XML handling
 * @author Christian Grothoff
 */
#include "taler/taler_util.h"


/**
 * We allow [a-zA-Z0-9-.:] in extra_wire_subject_metadata.
 * Test @a c for it.
 *
 * @param c character to test
 * @return true if OK
 */
static inline bool
is_allowed_metachar (char c)
{
  return (c >= 'a' && c <= 'z') ||
         (c >= 'A' && c <= 'Z') ||
         (c >= '0' && c <= '9') ||
         c == '-' ||
         c == '.' ||
         c == ':';
}


bool
TALER_is_valid_subject_metadata_string (const char *src)
{
  unsigned int len = 0;
  if (NULL == src)
    return true;

  while (*src)
  {
    if (! is_allowed_metachar (*src++))
      return false;
    if (++len > 40)
      return false;
  }
  return true;
}


char *
TALER_escape_xml (const char *str)
{
  struct GNUNET_Buffer out = { 0 };
  const char *p = str;

  while (*p)
  {
    const char *esc = NULL;

    switch (*p)
    {
    case '&':
      esc = "&amp;";
      break;
    case '<':
      esc = "&lt;";
      break;
    case '>':
      esc = "&gt;";
      break;
    case '"':
      esc = "&quot;";
      break;
    case '\'':
      esc = "&apos;";
      break;
    }
    if (NULL != esc)
      GNUNET_buffer_write_str (&out,
                               esc);
    else
      GNUNET_buffer_write (&out,
                           p,
                           1);
    p++;
  }
  return GNUNET_buffer_reap_str (&out);
}
