Exemplo n.º 1
0
/*
 * Internal function to open an XML file
 *
 * Returns the XML doc pointer, or NULL on failure.  It will validate the
 * document, as well as removing any comments from the document structure.
 */
static xmlDocPtr
open_xml_file(const char *file)
{
	xmlDocPtr doc;
	xmlValidCtxtPtr cvp;
	int valid;

	if (!libbrand_initialize())
		return (NULL);

	/*
	 * Parse the file
	 */
	if ((doc = xmlParseFile(file)) == NULL)
		return (NULL);

	/*
	 * Validate the file
	 */
	if ((cvp = xmlNewValidCtxt()) == NULL) {
		xmlFreeDoc(doc);
		return (NULL);
	}
	cvp->error = brand_error_func;
	cvp->warning = brand_error_func;
	valid = xmlValidateDocument(cvp, doc);
	xmlFreeValidCtxt(cvp);
	if (valid == 0) {
		xmlFreeDoc(doc);
		return (NULL);
	}

	return (doc);
}
Exemplo n.º 2
0
/**
 * Fonction de validation d'un arbre DOM à l'aide d'une DTD
 **/
int validation_dtd(xmlDocPtr doc, const char *fichier_dtd, int afficher_erreurs) {
    int ret;
    xmlDtdPtr dtd;
    xmlValidCtxtPtr vctxt;

    // Traitement de la DTD
    if (NULL == (dtd = xmlParseDTD(NULL, BAD_CAST fichier_dtd))) {
        return ERROR_OCCURED;
    }
    // Création du contexte de validation
    if (NULL == (vctxt = xmlNewValidCtxt())) {
        xmlFreeDtd(dtd);
        return ERROR_OCCURED;
    }
    // Affichage des erreurs de validation
    if (afficher_erreurs) {
        vctxt->userData = (void *) stderr;
        vctxt->error = (xmlValidityErrorFunc) fprintf;
        vctxt->warning = (xmlValidityWarningFunc) fprintf;
    }
    // Validation
    ret = xmlValidateDtd(vctxt, doc, dtd);
    // Libération de la mémoire
    xmlFreeValidCtxt(vctxt);
    xmlFreeDtd(dtd);

    return ret;
}
Exemplo n.º 3
0
int validateXML(const char *input_file, const char *DTDdata)
{
    int ret = 0;
    char *XMLdata;
    xmlDocPtr doc = 0;
    xmlDtdPtr dtd = 0;
    xmlValidCtxtPtr cvp = 0;
    xmlParserInputBufferPtr bp;

    doc = xmlParseFile(input_file);
    if (!doc) {
    	printf("xmlParseFile(\"%s\") failed\n", input_file);
	ret = 1;
	goto exit;
    }

    bp = xmlParserInputBufferCreateMem(DTDdata, strlen(DTDdata), 
    				       XML_CHAR_ENCODING_NONE);
    dtd = xmlIOParseDTD(NULL, bp, XML_CHAR_ENCODING_NONE);
    if (!dtd) {
    	printf("xmlIOParseDTD() failed\n");
	ret = 2;
	goto exit;
    }

    cvp = xmlNewValidCtxt();
    if (!cvp) {
    	printf("xmlNewValidCtxt() failed\n");
	ret = 3;
	goto exit;
    }
    cvp->userData = (void*)stderr;
    cvp->error = (xmlValidityErrorFunc)fprintf;
    cvp->warning = (xmlValidityWarningFunc)fprintf; 

    if (!xmlValidateDtd(cvp, doc, dtd)) {
    	printf("xmlValidateDtd() failed\n");
	ret = 4;
	goto exit;
    }

    ret = 0;

exit:

    if (doc) {
    	xmlFreeDoc(doc);
    }
    if (dtd) {
    	xmlFreeDtd(dtd);
    }
    if (cvp) {
    	xmlFreeValidCtxt(cvp);
    }
    return ret;
}
Exemplo n.º 4
0
void Validator::release_underlying()
{
  if(valid_)
  {
    valid_->userData = 0; //Not really necessary.

    xmlFreeValidCtxt(valid_);
    valid_ = 0;
  }
}
Exemplo n.º 5
0
/**
 * Destroys the parser 
 */
void parser_destroy()
{
	if (dtdCtxt){
		xmlFreeValidCtxt(dtdCtxt);
	}
	if (xsdCtxt){
		xmlSchemaFreeValidCtxt(xsdCtxt);
		xmlSchemaCleanupTypes();
	}
	xmlCleanupParser();
	
}
Exemplo n.º 6
0
static bool
is_dtd_valid(FILE *input, const char *filename)
{
	bool rc = true;
#if HAVE_LIBXML
	xmlParserCtxtPtr ctx = NULL;
	xmlDocPtr doc = NULL;
	xmlDtdPtr dtd = NULL;
	xmlValidCtxtPtr	dtdctx;
	xmlParserInputBufferPtr	buffer;
	int fd = fileno(input);

	dtdctx = xmlNewValidCtxt();
	ctx = xmlNewParserCtxt();
	if (!ctx || !dtdctx)
		abort();

	buffer = xmlParserInputBufferCreateMem(&DTD_DATA_begin,
					       DTD_DATA_len,
					       XML_CHAR_ENCODING_UTF8);
	if (!buffer) {
		fprintf(stderr, "Failed to init buffer for DTD.\n");
		abort();
	}

	dtd = xmlIOParseDTD(NULL, buffer, XML_CHAR_ENCODING_UTF8);
	if (!dtd) {
		fprintf(stderr, "Failed to parse DTD.\n");
		abort();
	}

	doc = xmlCtxtReadFd(ctx, fd, filename, NULL, 0);
	if (!doc) {
		fprintf(stderr, "Failed to read XML\n");
		abort();
	}

	rc = xmlValidateDtd(dtdctx, doc, dtd);
	xmlFreeDoc(doc);
	xmlFreeParserCtxt(ctx);
	xmlFreeDtd(dtd);
	xmlFreeValidCtxt(dtdctx);
	/* xmlIOParseDTD consumes buffer */

	if (lseek(fd, 0, SEEK_SET) != 0) {
		fprintf(stderr, "Failed to reset fd, output would be garbage.\n");
		abort();
	}
#endif
	return rc;
}
Exemplo n.º 7
0
/*******************  FUNCTION  *********************/
void CMRXmlDoc::validateWithDTD ( const string& dtdFile )
{
	/* vars */
	bool status = true;
	xmlDtdPtr dtd;
	xmlValidCtxtPtr vctxt;

	/* errors */
	assert(doc != NULL);
	assert(rootNode != NULL);
	assert(dtdFile.empty() == false);
	
	/* Nothing to do */
	if (rootNode == NULL || dtdFile.empty())
		return;

	/* Open XML schema file */
	dtd = xmlParseDTD(NULL, BAD_CAST(dtdFile.c_str()));
	assert(dtd != NULL);
	//assume_m(pctxt != NULL,"Fail to open XML schema file to validate config : %s.",xml_shema_path);


	/* Create validation context */
	if ((vctxt = xmlNewValidCtxt()) == NULL) {
		assert(vctxt != NULL);
		//sctk_fatal("Fail to create validation context from XML schema file : %s.",xml_shema_path);
	}

	/* Create validation output system */
	vctxt->userData = (void *) stderr;
	vctxt->error = (xmlValidityErrorFunc) fprintf;
	vctxt->warning = (xmlValidityWarningFunc) fprintf;

	/* Validation */
	status = (xmlValidateDtd(vctxt, doc,dtd) == 0);

	/* Free the schema */
	xmlFreeDtd(dtd);
	 xmlFreeValidCtxt(vctxt);

	if (!status)
		throw LatexException("XML file is invalid.");
}
Exemplo n.º 8
0
/*
 * call-seq:
 *   validate(document)
 *
 * Validate +document+ returning a list of errors
 */
static VALUE validate(VALUE self, VALUE document)
{
  xmlDocPtr doc;
  xmlDtdPtr dtd;

  Data_Get_Struct(self, xmlDtd, dtd);
  Data_Get_Struct(document, xmlDoc, doc);
  VALUE error_list      = rb_ary_new();

  xmlValidCtxtPtr ctxt = xmlNewValidCtxt();

  xmlSetStructuredErrorFunc((void *)error_list, Nokogiri_error_array_pusher);

  xmlValidateDtd(ctxt, doc, dtd);

  xmlSetStructuredErrorFunc(NULL, NULL);

  xmlFreeValidCtxt(ctxt);

  return error_list;
}
Exemplo n.º 9
0
int main(int argc, const char *argv[]) {
  int status = 0;
  xmlParserCtxtPtr parser_context = 0;
  xmlDocPtr doc = 0;
  xmlDtdPtr dtd = 0;
  xmlValidCtxtPtr valid_context = 0;

  do {
    if (argc < 3) {
      status = 2;
      fprintf(stderr, "Too few arguments.\n");
      break;
    }

    parser_context = xmlNewParserCtxt();
    doc = xmlCtxtReadFile(parser_context, argv[1], NULL, 0);
    if (!doc) {
      status = 3;
      fprintf(stderr, "Can't read xml.\n");
      break;
    }

    dtd = xmlParseDTD(NULL, (const xmlChar *)argv[2]);
    if (!dtd) {
      status = 4;
      fprintf(stderr, "Can't read dtd.\n");
      break;
    }

    valid_context = xmlNewValidCtxt();
    status = xmlValidateDtd(valid_context, doc, dtd) ? 0 : 1;
  } while (0);

  if (parser_context) xmlFreeParserCtxt(parser_context);
  if (doc) xmlFreeDoc(doc);
  if (dtd) xmlFreeDtd(dtd);
  if (valid_context) xmlFreeValidCtxt(valid_context);

  return status;
}
Exemplo n.º 10
0
void TrackerConfig::loadConfigFile(const string& sFilename)
{
    // TODO: There is duplicated code here and in Player::loadFile which belongs
    // in a lower-level xml handling class.
    registerDTDEntityLoader("trackerconfig.dtd", g_pTrackerConfigDTD);
    xmlDtdPtr dtd;
    string sDTDFName = "trackerconfig.dtd";
    dtd = xmlParseDTD(NULL, (const xmlChar*) sDTDFName.c_str());
    if (!dtd) {
        AVG_LOG_WARNING("DTD not found at " << sDTDFName 
                << ". Not validating trackerconfig files.");
    }

    // xmlParseFile crashes for some reason under Lion.
    string sFileContents;
    readWholeFile(sFilename, sFileContents);
    m_Doc = xmlParseMemory(sFileContents.c_str(), sFileContents.length());
    if (!m_Doc) {
        AVG_LOG_ERROR("Could not open tracker config file " << sFilename <<
                ". Using defaults which will probably not work.");
        return;
    }

    xmlValidCtxtPtr cvp = xmlNewValidCtxt();
    cvp->error = xmlParserValidityError;
    cvp->warning = xmlParserValidityWarning;
    int isValid = xmlValidateDtd(cvp, m_Doc, dtd);  
    xmlFreeValidCtxt(cvp);
    if (!isValid) {
        throw (Exception(AVG_ERR_XML_PARSE, sFilename + " does not validate."));
    }

    m_pRoot = xmlDocGetRootElement(m_Doc);
    xmlFreeDtd(dtd);
    m_sFilename = sFilename;

    AVG_TRACE(Logger::category::CONFIG, Logger::severity::INFO,
            "Reading Tracker config file from " << sFilename);
}
Exemplo n.º 11
0
XMLParser::~XMLParser()
{
    if (m_Schema) {
        xmlSchemaFree(m_Schema);
    }
    if (m_SchemaParserCtxt) {
        xmlSchemaFreeParserCtxt(m_SchemaParserCtxt);
    }
    if (m_SchemaValidCtxt) {
        xmlSchemaFreeValidCtxt(m_SchemaValidCtxt);
    }
    if (m_DTD) {
        xmlFreeDtd(m_DTD);
    }
    if (m_DTDValidCtxt) {
        xmlFreeValidCtxt(m_DTDValidCtxt);
    }
    if (m_Doc) {
        xmlFreeDoc(m_Doc);
    }
    xmlSetGenericErrorFunc(0, 0);
}
int oph_hier_validate(oph_hier_document * document)
{
	int result;
	if ((result = oph_hier_basic_control(document)) != OPH_HIER_OK)
		return result;
	xmlDtdPtr dtd = xmlParseDTD(NULL, (xmlChar *) OPH_FRAMEWORK_HIERARCHY_DTD_PATH);
	if (!dtd) {
		pmesg(LOG_ERROR, __FILE__, __LINE__, "DTD file '%s' not found\n", OPH_FRAMEWORK_HIERARCHY_DTD_PATH);
		return OPH_HIER_IO_ERR;
	}
	xmlValidCtxtPtr cvp = xmlNewValidCtxt();
	if (!cvp) {
		xmlFreeDtd(dtd);
		pmesg(LOG_ERROR, __FILE__, __LINE__, "Context is not gettable\n");
		return OPH_HIER_SYSTEM_ERR;
	}
	if (!xmlValidateDtd(cvp, document->document, dtd)) {
		pmesg(LOG_WARNING, __FILE__, __LINE__, "File is not valid\n");
		result = OPH_HIER_XML_ERR;
	}
	xmlFreeValidCtxt(cvp);
	xmlFreeDtd(dtd);
	return result;
}
Exemplo n.º 13
0
gboolean loadConfig(const gchar *filename, CfgFile *lcfg) {
    /* Parse hosts.xml document. */
    xmlDocPtr xcfg = xmlParseFile(filename);
    if(xcfg == NULL)
      return(FALSE);

    /* Handle Xincludes. */
    xmlSetGenericErrorFunc(NULL, xmlErrIgnoreHandler);
    xmlXIncludeProcess(xcfg);
    handleXMLError( xmlGetLastError() );
    xmlSetGenericErrorFunc(NULL, NULL);

    /* Validate against DTD. */
    xmlValidCtxtPtr xval = xmlNewValidCtxt();
    if(xmlValidateDocument(xval, xcfg) == 0) {
      xmlFreeValidCtxt(xval);
      return(FALSE);
    }
    xmlFreeValidCtxt(xval);

    /* Allocate XPath context. */
    xmlXPathContextPtr xctx = xmlXPathNewContext(xcfg);
    if(!xctx) {
      g_error("%s: xmlXPathNewContext failed!\n", filename);
      return(FALSE);
    }

    xmlNodePtr s_ssh[2] = {getXNode(xctx, "/apt-dater/ssh"), NULL};
    xmlNodePtr s_path[2] = {getXNode(xctx, "/apt-dater/paths"), NULL};
#ifdef FEAT_TMUX
    xmlNodePtr s_tmux[2] = {getXNode(xctx, "/apt-dater/tmux"), NULL};
#else
    xmlNodePtr s_screen[2] = {getXNode(xctx, "/apt-dater/screen"), NULL};
#endif
    xmlNodePtr s_appearance[2] = {getXNode(xctx, "/apt-dater/appearance"), NULL};
    xmlNodePtr s_notify[2] = {getXNode(xctx, "/apt-dater/notify"), NULL};
    xmlNodePtr s_hooks[2] = {getXNode(xctx, "/apt-dater/hooks"), NULL};
#ifdef FEAT_AUTOREF
    xmlNodePtr s_autoref[2] = {getXNode(xctx, "/apt-dater/auto-ref"), NULL};
#endif
#ifdef FEAT_HISTORY
    xmlNodePtr s_history[2] = {getXNode(xctx, "/apt-dater/history"), NULL};
#endif
#ifdef FEAT_TCLFILTER
    xmlNodePtr s_tclfilter[2] = {getXNode(xctx, "/apt-dater/tcl-filter"), NULL};
#endif

    lcfg->ssh_optflags = getXPropStr(s_ssh, "opt-cmd-flags", "-t");
    lcfg->ssh_cmd = getXPropStr(s_ssh, "cmd", "/usr/bin/ssh");
    lcfg->sftp_cmd = getXPropStr(s_ssh, "sftp-cmd", "/usr/bin/sftp");

    lcfg->umask = getXPropInt(s_path, "umask", S_IRWXG | S_IRWXO);
    umask(lcfg->umask);

    lcfg->hostsfile = getXPropStr(s_path, "hosts-file", g_strdup_printf("%s/%s/%s", g_get_user_config_dir(), PROG_NAME, "hosts.xml"));
    lcfg->statsdir = getXPropStr(s_path, "stats-dir", g_strdup_printf("%s/%s/%s", g_get_user_cache_dir(), PROG_NAME, "stats"));
    if(g_mkdir_with_parents(lcfg->statsdir, S_IRWXU | S_IRWXG) == -1) {
      g_warning("Failed to create %s: %s", lcfg->statsdir, g_strerror(errno));
      exit(1);
    }

#ifdef FEAT_TMUX
    lcfg->tmuxconffile = getXPropStr(s_tmux, "conf-file", g_strdup_printf("%s/%s/%s", g_get_user_config_dir(), PROG_NAME, "tmux.conf"));
    lcfg->tmuxsockpath = getXPropStr(s_tmux, "socket-path", g_strdup_printf("%s/%s/%s", g_get_user_cache_dir(), PROG_NAME, "tmux"));
    if(g_mkdir_with_parents(lcfg->tmuxsockpath, S_IRWXU | S_IRWXG) == -1) {
      g_warning("Failed to create %s: %s", lcfg->tmuxsockpath, g_strerror(errno));
      exit(1);
    }
#else
    lcfg->screenrcfile = getXPropStr(s_screen, "rc-file", g_strdup_printf("%s/%s/%s", g_get_user_config_dir(), PROG_NAME, "screenrc"));
    lcfg->screentitle = getXPropStr(s_screen, "title", g_strdup("%m # %U%H"));
#endif

    lcfg->ssh_agent = getXPropBool(s_ssh, "spawn-agent", FALSE);

    xmlNodeSetPtr s_addkeys = getXNodes(xctx, "/apt-dater/ssh/add-key");
    if(!xmlXPathNodeSetIsEmpty(s_addkeys)) {
      lcfg->ssh_add = g_new0(char*, s_addkeys->nodeNr + 1);
      int i;
      for(i = 0; i < s_addkeys->nodeNr; i++) {
	lcfg->ssh_add[i] = g_strdup((gchar *)xmlGetProp(s_addkeys->nodeTab[i], BAD_CAST("name")));
	xmlChar *c = xmlGetProp(s_addkeys->nodeTab[i], BAD_CAST("fn"));
	if(!c) {
	    g_printerr(_("Empty SSH key filename (%s/@fn) in configuration."), xmlGetNodePath(s_addkeys->nodeTab[i]));
	    exit(1);
	}
	lcfg->ssh_add[i] = g_strdup((gchar *)c);
      }
      lcfg->ssh_numadd = s_addkeys->nodeNr;
    }
Exemplo n.º 14
0
/* Parse the configuration file. */
int sechk_lib_parse_xml_file(const char *filename, sechk_lib_t * lib)
{
	xmlTextReaderPtr reader = NULL;
	xmlDtdPtr dtd = NULL;
	xmlDocPtr xml = NULL;
	xmlValidCtxtPtr ctxt = NULL;
	int tmp, ret = 0;
	char *dtd_path = NULL;

	/* this initializes the XML library and checks potential ABI mismatches
	 * between the version it was compiled for and the actual shared
	 * library used. */
	LIBXML_TEST_VERSION;
	reader = xmlReaderForFile(filename, NULL, 0);
	if (!reader) {
		ret = errno;
		if (ret != ENOENT)
			fprintf(stderr, "Error: Could not create xmlReader.\n");
		goto exit_err;
	}

	dtd_path = build_dtd_path();
	if (!dtd_path) {
		fprintf(stderr, "Error: getting DTD path\n");
		goto exit_err;
	}
	dtd = xmlParseDTD(NULL, (const xmlChar *)dtd_path);
	free(dtd_path);

	if (!dtd) {
		fprintf(stderr, "Error: parsing DTD\n");
		goto exit_err;
	}

	xml = xmlParseFile(filename);
	if (!xml) {
		fprintf(stderr, "Error: parsing sechecker profile\n");
		goto exit_err;
	}

	ctxt = xmlNewValidCtxt();
	if (!ctxt) {
		fprintf(stderr, "Error: out of memory\n");
		goto exit_err;
	}
	/* validate profile against the DTD */
	if (xmlValidateDtd(ctxt, xml, dtd) == 0) {
		fprintf(stderr, "Error: SEChecker profile contains invalid XML. Aborting.\n");
		goto exit_err;
	}
	xmlFreeValidCtxt(ctxt);
	xmlFreeDoc(xml);
	xmlFreeDtd(dtd);

	while (1) {
		ret = xmlTextReaderRead(reader);
		if (ret == -1) {
			ret = errno;
			fprintf(stderr, "Error: Error reading xml.\n");
			goto exit_err;
		}
		if (ret == 0)	       /* no more nodes to read */
			break;

		tmp = sechk_lib_process_xml_node(reader, lib);
		if (tmp == -1)
			goto exit_err;
		if (tmp == 1) {
			ret = xmlTextReaderNext(reader);
			if (ret == 0)
				break;
			if (ret == -1) {
				ret = errno;
				fprintf(stderr, "Error in xmlTextReaderNext()\n");
				goto exit_err;
			}
		}
	}

	/* cleanup function for the XML library */
	xmlCleanupParser();
	xmlFreeTextReader(reader);
	return 0;

      exit_err:
	xmlCleanupParser();
	if (reader)
		xmlFreeTextReader(reader);
	if (ret)
		errno = ret;
	return -1;
}
Exemplo n.º 15
0
static adr_data_t *
read_panel_path(rad_locale_t *rlocale, const char *path)
{
	xmlParserCtxt *ctx;
	xmlValidCtxt *vctx;
	xmlDoc *doc;
	adr_data_t *panel = NULL;

	ctx = xmlNewParserCtxt();
	vctx = xmlNewValidCtxt();
	if (vctx == NULL || ctx == NULL)
		return (NULL);

	doc = xmlCtxtReadFile(ctx, path, NULL, 0);
	if (doc == NULL) {
		xmlFreeValidCtxt(vctx);
		xmlFreeParserCtxt(ctx);
		rad_log(RL_WARN, "Empty/no such document: %s\n", path);
		return (NULL);
	}

	/*
	 * Validate against *our* DTD.
	 */
	if (xmlValidateDtd(vctx, doc, dtd) == 0) {
		rad_log(RL_WARN, "Invalid document: %s\n", path);
		goto out;
	}

	xmlNodePtr root = xmlDocGetRootElement(doc);
	if (root == NULL || strcmp((const char *)root->name, "panel") != 0) {
		rad_log(RL_WARN, "Not a panel definition: %s\n", path);
		goto out;
	}

	panel = adr_data_new_struct(&t__CustomPanel);
	adr_struct_set(panel, "locale",
	    adr_data_new_string(rlocale->locale, LT_COPY));

	adr_data_t *pname = get_prop(root, "name");
	adr_struct_set(panel, "name", pname);

	adr_data_t *farray =
	    adr_data_new_array(&t_array__ResourceDescriptor, 1);
	adr_struct_set(panel, "resourceDescriptors", farray);

	char *aroot = NULL;
	for (xmlNode *np = root->children; np != NULL; np = np->next) {
		if (np->type != XML_ELEMENT_NODE)
			continue;
		if (strcmp((const char *)np->name, "mainclass") == 0) {
			adr_data_t *mc = get_text(doc, np->children);
			adr_struct_set(panel, "panelDescriptorClassName", mc);
		} else if (strcmp((const char *)np->name, "approot") == 0) {
			if (aroot != NULL)
				continue;	/* schema violation */
			aroot = get_text_str(doc, np->children);
		} else if (strcmp((const char *)np->name, "file") == 0) {
			char *file = get_text_str(doc, np->children);
			if (file == NULL) {
				rad_log(RL_WARN,
				    "Empty <file> declaration within %s\n",
				    path);
				continue;
			}

			if (aroot == NULL) {
				rad_log(RL_WARN, "App root not specified\n");
				continue;
			}

			char full[PATH_MAX];
			(void) snprintf(full, RAD_COUNT(full), "%s/%s", aroot,
			    file);
			free(file);

			add_localized(rlocale, adr_data_to_string(pname),
			    farray, full);
		}
	}
	if (aroot != NULL)
		free(aroot);
out:
	xmlFreeValidCtxt(vctx);
	xmlFreeDoc(doc);
	xmlFreeParserCtxt(ctx);

	return (adr_data_purify_deep(panel));
}
Exemplo n.º 16
0
/**
 *  Validate XML document against DTD
 */
int
valAgainstDtd(valOptionsPtr ops, char* dtdvalid, xmlDocPtr doc, char* filename)
{
    int result = 0;

    if (dtdvalid != NULL)
    {
        xmlDtdPtr dtd;

#if !defined(LIBXML_VALID_ENABLED)
	xmlGenericError(xmlGenericErrorContext,
	"libxml2 has no validation support");
	return 2;
#endif
        dtd = xmlParseDTD(NULL, (const xmlChar *)dtdvalid);
        if (dtd == NULL)
        {
            xmlGenericError(xmlGenericErrorContext,
            "Could not parse DTD %s\n", dtdvalid);
            result = 2;
        }
        else
        {
            xmlValidCtxtPtr cvp;

            if ((cvp = xmlNewValidCtxt()) == NULL) 
            {
                xmlGenericError(xmlGenericErrorContext,
                    "Couldn't allocate validation context\n");
                exit(-1);
            }
        
            if (ops->err)
            {
                cvp->userData = (void *) stderr;
                cvp->error    = (xmlValidityErrorFunc) fprintf;
                cvp->warning  = (xmlValidityWarningFunc) fprintf;
            }
            else
            {
                cvp->userData = (void *) NULL;
                cvp->error    = (xmlValidityErrorFunc) NULL;
                cvp->warning  = (xmlValidityWarningFunc) NULL;
            }
                        
            if (!xmlValidateDtd(cvp, doc, dtd))
            {
                if ((ops->listGood < 0) && !ops->show_val_res)
                {
                    fprintf(stdout, "%s\n", filename);
                }
                else if (ops->listGood == 0)
                    xmlGenericError(xmlGenericErrorContext,
                                    "%s: does not match %s\n",
                                    filename, dtdvalid);
                result = 3;
            }
            else
            {
                if ((ops->listGood > 0) && !ops->show_val_res)
                {
                    fprintf(stdout, "%s\n", filename);
                }
            }
            xmlFreeDtd(dtd);
            xmlFreeValidCtxt(cvp);
        }
    }

    return result;
}
Exemplo n.º 17
0
/**
 * Validation function take first argument as XML type, then check if is
 * well formated. If so, do the same for DTD document. If both success, check
 * XML document against DTD schema restrictions.
 * @return true if pass, false otherwise
 */
Datum xmlvalidate_dtd(PG_FUNCTION_ARGS)
{
#ifdef USE_LIBXML
	int ret = -1;
	xmlValidCtxtPtr validctxt   = NULL;
	xmlDtdPtr       dtd         = NULL;
    bool			result		= false;
    text			*data		= NULL;
	char			*dtdstr		= NULL;
    xmltype			*xmldata	= NULL;
    char			*xmldataint = NULL;
    xmlChar			*xmldatastr = NULL;
    int				lenxml  = -1;       // length of xml data
    xmlDocPtr               doc = NULL;

	 // creating xmlChar * from internal xmltype of stored XML
    xmldata     = PG_GETARG_XML_P(0);
    xmldataint  = VARDATA(xmldata);
    lenxml      = VARSIZE(xmldata) - VARHDRSZ;
    xmldatastr  = (xmlChar *) palloc((lenxml + 1) * sizeof(xmlChar));
	memcpy(xmldatastr, xmldataint, lenxml);
	xmldatastr[lenxml] = '\0';

    // creating xmlChar* from text representation of DTD
    data = PG_GETARG_TEXT_P(1);
	dtdstr = text_to_cstring(data);

    //initialize LibXML structures, if allready done -> do nothing
    pg_xml_init();
	xmlInitParser();

    doc = xmlReadMemory((const char *)xmldatastr, lenxml, "include.xml", NULL, 0);

     if (doc == NULL) {
        elog(ERROR, "Failed to parse XML document");
        PG_RETURN_BOOL (false);
    }

	// create DTD from memory, must use XML_CHAR_ENCODING_NONE 
	dtd = xmlIOParseDTD(NULL,
				xmlParserInputBufferCreateMem(dtdstr, strlen(dtdstr),
						 XML_CHAR_ENCODING_NONE),
				XML_CHAR_ENCODING_NONE);

    if (dtd == NULL)
    { // unable to create parser context
        elog(ERROR, "Error with creating DTD schema, check if schema is valid");
        PG_RETURN_BOOL (false);
    }

	validctxt = xmlNewValidCtxt();
	if (validctxt == NULL)
	{ // cant create validation context
		elog(INFO ,"cant create validation context");
		xmlFreeDtd(dtd);
		PG_RETURN_BOOL (false);
	}

	ret = xmlValidateDtd(validctxt, doc, dtd);
	if (ret == 0)
    {
        elog(INFO, "Validates");
        result = true;
    } else if (ret > 0)
    {
        elog(INFO, "Dont validates");
        result = false;
    } else
    {
        elog(INFO, "Validation generated an internal error");
        result = false;
    }

	xmlFreeDtd(dtd);
	xmlFreeValidCtxt(validctxt);

	xmlFreeDoc(doc);    // clean up document in memmory
    xmlCleanupParser(); // clean up stream parser
	PG_RETURN_BOOL (result);
#else
    NO_XML_SUPPORT();
    PG_RETURN_BOOL (false);
#endif
	}