/*
 * Copyright (c) 1996-2007, OpenFWTK Development Group
 * All rights reserved. See LICENSE.
 */

#include <string.h>
#include <stdlib.h>

#include "firewall2.h"
#include "fwfunc.h"

static int match_ctype(Cfg *cf, const char *ctype)
{
  int i = 0;
  char *found_type = xstrdup(ctype);
  char *found_subtype = strchr (found_type, '/');
  char *p;

  /* Strip charset (if any)	*/

  if ((p = strchr(found_type, ';')))
    *p = '\0';

  if (!found_subtype)
	found_subtype = "unknown";
  else
	*(found_subtype++) = '\0';

  while (i < cf->argc && cf->argv[i][0] != '-')
    {
      char *conf_type = xstrdup(cf->argv[i++]);
      char *conf_subtype = strchr (conf_type, '/');
      if (!conf_subtype)
	conf_subtype = "*";
      else
	*(conf_subtype++) = '\0';
      if (nacasematch(conf_type, found_type) && 
	  nacasematch(conf_subtype, found_subtype)) {
	free(found_type);
	free(conf_type);
	return(0);
      }
      free(conf_type);
    }
  free(found_type);
  return(-1);
}

int config_havemagic ()
{
  return(cfg_get ("content-type", proxy_confp) != NULL);
}

int config_ctype (const char *ctype, char ***filters)
{
  Cfg *cf = cfg_get ("content-type", proxy_confp);
  while (cf != NULL && match_ctype (cf, ctype) != 0)
    cf = cfg_get ("content-type", (Cfg *)0);

  /* Grant access if there's no match. */

  if (cf == NULL)
    return 0;

  if (cf->flags & PERM_DENY)
    return -1;
  else
    {
      int i = 0;
      while (++i < cf->argc)
	{
	  if (i + 1 < cf->argc && strcmp (cf->argv[i], "-milter") == 0)
	    while (++i < cf->argc)
	      if (!*filters || searchlist(cf->argv[i], *filters))
	        addlist(cf->argv[i], filters);
	}
      return 0;
    }
}
