/*
 * unity-webapps-sanitizer.c
 * Copyright (C) Canonical LTD 2011
 *
 * Author: Robert Carr <racarr@canonical.com>
 * 
 unity-webapps is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * unity-webapps 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 Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.";
 */

#include "unity-webapps-sanitizer.h"
#include <string.h>

static gboolean 
_is_valid_utf8 (const gchar *string, gsize length) 
{
  const gchar *end;
  gboolean ret;
  
  ret = g_utf8_validate (string, -1, &end);
  
  if (ret == FALSE)
    {
      gchar *sane_string;
      
      sane_string = g_malloc ((length+1) * sizeof(gchar));
      
      g_strlcpy (sane_string, string, end-string < length ? end-string : length);
      g_warning ("String is invalid UTF8, becomes invalid after: %s", sane_string);
      
      g_free (sane_string);
    }
  
  return ret;

}

gchar **
unity_webapps_sanitizer_limit_strv_argument (const gchar *const *strv,
					     gsize length,
					     gsize element_length)
{
  gchar **limited;
  gint i,vlen;
  
  if (strv == NULL)
    {
      limited = g_malloc(sizeof(gchar*));
      limited[0] = g_strdup("");
      return limited;
    }
  
  vlen = g_strv_length ((gchar **)strv);
  if (vlen > length)
    {
      vlen = length;
    }
  limited = g_malloc0((vlen+1) * sizeof(gchar *));
  for (i = 0; i < vlen; i++)
    {
      limited[i] = unity_webapps_sanitizer_limit_string_argument (strv[i], element_length);
    }
  limited[i] = NULL;

  return limited;

}

gchar *
unity_webapps_sanitizer_limit_string_argument (const gchar *string,
					       gsize length)
{
  gchar *ret_string;
  
  if (string == NULL)
    {
      return g_strdup ("");
    }
  
  if (_is_valid_utf8 (string, length) == FALSE)
    {
      return g_strdup ("");
    }

  if (strlen(string) <= length)
    {
      return g_strdup (string);
    }
  
  ret_string = g_malloc ((length + 1) * sizeof(gchar));

  g_strlcpy (ret_string, string, length);
  
  return ret_string;
}
