Beispiel #1
0
SEXP 
RS_XML_xmlSchemaValidateDoc(SEXP r_schema, SEXP r_doc, SEXP r_options, SEXP r_errorHandlers)
{
    xmlSchemaValidCtxtPtr ctxt;
    xmlDocPtr doc = (xmlDocPtr) R_ExternalPtrAddr(r_doc);
    xmlSchemaPtr schema = (xmlSchemaPtr) R_ExternalPtrAddr(r_schema);
//    ctxt = (xmlSchemaValidCtxtPtr) R_ExternalPtrAddr(r_ctxt);

    int status;
    int numErrHandlers;

    ctxt = xmlSchemaNewValidCtxt(schema);
    if(LENGTH(r_options))
	xmlSchemaSetValidOptions(ctxt, INTEGER(r_options)[0]);

    numErrHandlers = Rf_length(r_errorHandlers);
    if(numErrHandlers > 0) {
	R_SchemaValidCallback cbinfo;
	PROTECT(cbinfo.fun = allocVector(LANGSXP, 2));
	SETCAR(cbinfo.fun, VECTOR_ELT(r_errorHandlers, 0));
	xmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) R_schemaValidityErrorFunc, 
                                      (xmlSchemaValidityWarningFunc) R_schemaValidityWarningFunc, &cbinfo);
    }

    status = xmlSchemaValidateDoc(ctxt, doc);
    xmlSchemaFreeValidCtxt(ctxt); /* R_alloc this if possible. */
    if(numErrHandlers > 0) 
	UNPROTECT(1);

    return(ScalarInteger(status));
}
Beispiel #2
0
 validity schema::validate(document& doc) const
 {
     // Check if the schema has been loaded.
     if (raw_ == 0)
     {
         throw bad_dom_operation("failed to validate XML document: schema not loaded");
     }
     // Create a schema validation context from the schema.
     schema_valid_context valid_ctxt(raw_);
     if (valid_ctxt.get() == 0)
     {
         throw internal_dom_error("failed to create xmlSchemaValidCtxt from xmlSchema");
     }
     // Set validation callback functions, and validate the XML document.
     validity result;
     xmlSchemaSetValidErrors( valid_ctxt.get(),
                              &detail::on_validity_error,
                              &detail::on_validity_warning,
                              static_cast<void*>(&result) );
     int ret_code = xmlSchemaValidateDoc(valid_ctxt.get(), doc.raw_doc());
     // Check the return code: 0 if the document is schemas valid, a positive error code number
     // otherwise, -1 in case of internal or API error.
     if (ret_code >= 0)
     {
         return result;
     }
     else
     {
         throw internal_dom_error("fail to validate: xmlSchemaValidateDoc returned -1");
     }
 }
Beispiel #3
0
int xml_validate(struct xml_node_ctx *ctx, xml_node_t *node,
		 const char *xml_schema_fname, char **ret_err)
{
	xmlDocPtr doc;
	xmlNodePtr n;
	xmlSchemaParserCtxtPtr pctx;
	xmlSchemaValidCtxtPtr vctx;
	xmlSchemaPtr schema;
	int ret;
	struct str_buf errors;

	if (ret_err)
		*ret_err = NULL;

	doc = xmlNewDoc((xmlChar *) "1.0");
	if (doc == NULL)
		return -1;
	n = xmlDocCopyNode((xmlNodePtr) node, doc, 1);
	if (n == NULL) {
		xmlFreeDoc(doc);
		return -1;
	}
	xmlDocSetRootElement(doc, n);

	os_memset(&errors, 0, sizeof(errors));

	pctx = xmlSchemaNewParserCtxt(xml_schema_fname);
	xmlSchemaSetParserErrors(pctx, (xmlSchemaValidityErrorFunc) add_str,
				 (xmlSchemaValidityWarningFunc) add_str,
				 &errors);
	schema = xmlSchemaParse(pctx);
	xmlSchemaFreeParserCtxt(pctx);

	vctx = xmlSchemaNewValidCtxt(schema);
	xmlSchemaSetValidErrors(vctx, (xmlSchemaValidityErrorFunc) add_str,
				(xmlSchemaValidityWarningFunc) add_str,
				&errors);

	ret = xmlSchemaValidateDoc(vctx, doc);
	xmlSchemaFreeValidCtxt(vctx);
	xmlFreeDoc(doc);
	xmlSchemaFree(schema);

	if (ret == 0) {
		os_free(errors.buf);
		return 0;
	} else if (ret > 0) {
		if (ret_err)
			*ret_err = errors.buf;
		else
			os_free(errors.buf);
		return -1;
	} else {
		if (ret_err)
			*ret_err = errors.buf;
		else
			os_free(errors.buf);
		return -1;
	}
}
/**
 * Initializes the libxml2 parser.
 * @param dtd_filename - path to the DTD or NULL if none
 * @param xsd_filename - path to the XSD or NULL if none
 * @returns 1 on success or 0 on error
 */
int parser_init(char *dtd_filename, char *xsd_filename)
{
	if (dtd_filename){
		dtd = xmlParseDTD(NULL,(unsigned char*)dtd_filename);
		if (!dtd){
			LM_ERR("unsuccesful DTD parsing from file <%s>\n",
				dtd_filename);
			return 0;
		}
		dtdCtxt = xmlNewValidCtxt();
		dtdCtxt->userData = (void*)stderr;
		dtdCtxt->error = (xmlValidityErrorFunc) fprintf;
		dtdCtxt->warning = (xmlValidityWarningFunc) fprintf;
	}
	if (xsd_filename){
		xmlSchemaParserCtxtPtr ctxt;
		ctxt = xmlSchemaNewParserCtxt(xsd_filename);
		if (!ctxt) {
			LM_ERR("unsuccesful XSD parsing from file <%s>\n",
				xsd_filename);
			return 0;
		}
		xmlSchemaSetParserErrors(ctxt,(xmlValidityErrorFunc) fprintf,(xmlValidityWarningFunc) fprintf,stderr);
		xsd = xmlSchemaParse(ctxt);
		xmlSchemaFreeParserCtxt(ctxt);		
		
		xsdCtxt = xmlSchemaNewValidCtxt(xsd);
		xmlSchemaSetValidErrors(xsdCtxt,(xmlValidityErrorFunc) fprintf,(xmlValidityWarningFunc) fprintf,stderr);
	}
	ctxtInit=1;
	return 1;
}
/*
 * call-seq:
 *    document.validate_schema(schema) -> (true|false)
 *
 * Validate this document against the specified XML::Schema.
 *
 * If a block is provided it is used as an error handler for validaten errors.
 * The block is called with two argument, the message and a flag indication
 * if the message is an error (true) or a warning (false).
 */
static VALUE rxml_document_validate_schema(VALUE self, VALUE schema)
{
  xmlSchemaValidCtxtPtr vptr;
  xmlDocPtr xdoc;
  xmlSchemaPtr xschema;
  int is_invalid;

  Data_Get_Struct(self, xmlDoc, xdoc);
  Data_Get_Struct(schema, xmlSchema, xschema);

  vptr = xmlSchemaNewValidCtxt(xschema);

  xmlSchemaSetValidErrors(vptr,
      (xmlSchemaValidityErrorFunc) LibXML_validity_error,
      (xmlSchemaValidityWarningFunc) LibXML_validity_warning, NULL);

  is_invalid = xmlSchemaValidateDoc(vptr, xdoc);
  xmlSchemaFreeValidCtxt(vptr);
  if (is_invalid)
  {
    rxml_raise(&xmlLastError);
    return Qfalse;
  }
  else
  {
    return Qtrue;
  }
}
Beispiel #6
0
HRESULT SchemaCache_validate_tree(IXMLDOMSchemaCollection2* iface, xmlNodePtr tree)
{
    schema_cache* This = impl_from_IXMLDOMSchemaCollection2(iface);
    cache_entry* entry;
    xmlChar const* ns = NULL;
    TRACE("(%p, %p)\n", This, tree);

    if (!tree)
        return E_POINTER;

    if ((xmlNodePtr)tree->doc == tree)
    {
        xmlNodePtr root = xmlDocGetRootElement(tree->doc);
        if (root && root->ns)
            ns = root->ns->href;
    }
    else if (tree->ns)
    {
        ns = tree->ns->href;
    }

    entry = xmlHashLookup(This->cache, ns);
    /* TODO: if the ns is not in the cache, and it's a URL,
     *       do we try to load from that? */
    if (entry)
    {
        if (entry->type == SCHEMA_TYPE_XDR)
        {
            FIXME("partial stub: XDR schema support not implemented\n");
            return S_OK;
        }
        else if (entry->type == SCHEMA_TYPE_XSD)
        {
            xmlSchemaValidCtxtPtr svctx;
            int err;
            /* TODO: if validateOnLoad property is false,
             *       we probably need to validate the schema here. */
            svctx = xmlSchemaNewValidCtxt(entry->schema);
            xmlSchemaSetValidErrors(svctx, validate_error, validate_warning, NULL);
#ifdef HAVE_XMLSCHEMASSETVALIDSTRUCTUREDERRORS
            xmlSchemaSetValidStructuredErrors(svctx, validate_serror, NULL);
#endif

            if ((xmlNodePtr)tree->doc == tree)
                err = xmlSchemaValidateDoc(svctx, (xmlDocPtr)tree);
            else
                err = xmlSchemaValidateOneElement(svctx, tree);

            xmlSchemaFreeValidCtxt(svctx);
            return err? S_FALSE : S_OK;
        }
    }

    return E_FAIL;
}
Beispiel #7
0
/*******************  FUNCTION  *********************/
void CMRXmlDoc::validateWithSchema ( const string& xsltFile )
{
	/* vars */
	bool status = true;
	xmlSchemaPtr schema;
	xmlSchemaValidCtxtPtr vctxt;
	xmlSchemaParserCtxtPtr pctxt;

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

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

	/* Parse the schema */
	schema = xmlSchemaParse(pctxt);
	xmlSchemaFreeParserCtxt(pctxt);
	assert(schema != NULL);
	//assume_m(schema != NULL,"Fail to parse the XML schema file to validate config : %s.",xml_shema_path);

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

	/* Create validation output system */
	xmlSchemaSetValidErrors(vctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);

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

	/* Free the schema */
	xmlSchemaFree(schema);
	xmlSchemaFreeValidCtxt(vctxt);

	if (!status)
		throw LatexException("XML file is invalid.");
}
Beispiel #8
0
void validateDoc(xmlDocPtr doc, std::string baseUri, std::string schemaFile) {
    xmlSchemaParserCtxtPtr ctx = xmlSchemaNewParserCtxt(schemaFile.c_str());
    if (ctx) {
        xmlSchemaSetParserErrors(ctx,(xmlSchemaValidityErrorFunc)errorHandler,(xmlSchemaValidityWarningFunc)warningHandler,nullptr);
        xmlSchemaPtr schema = xmlSchemaParse(ctx);
        xmlSchemaFreeParserCtxt(ctx);
        // validate
        xmlSchemaValidCtxtPtr vctx = xmlSchemaNewValidCtxt(schema);
        xmlSchemaSetValidErrors(vctx, (xmlSchemaValidityErrorFunc)errorHandler, (xmlSchemaValidityErrorFunc)warningHandler,nullptr);
        int ret = xmlSchemaValidateDoc(vctx, doc);
        xmlSchemaFreeValidCtxt(vctx);
        xmlSchemaFree(schema);
        if (ret != 0) {
            THROW_EXC("xml file '" << baseUri << "' is not valid");
        }
    }
}
Beispiel #9
0
SEXP
RS_XML_xmlSchemaNewValidCtxt(SEXP r_schema, SEXP r_options, SEXP r_errorHandlers)
{
    xmlSchemaPtr schema = (xmlSchemaPtr) R_ExternalPtrAddr(r_schema);
    xmlSchemaValidCtxtPtr ctxt;
    int numErrHandlers;
    ctxt = xmlSchemaNewValidCtxt(schema);
    if(LENGTH(r_options))
	xmlSchemaSetValidOptions(ctxt, INTEGER(r_options)[0]);

    numErrHandlers = LENGTH(r_errorHandlers);
    if(numErrHandlers > 0) {
	R_SchemaValidCallback *cbinfo = (R_SchemaValidCallback*) malloc(sizeof(R_SchemaValidCallback));
	cbinfo->fun = VECTOR_ELT(r_errorHandlers);
	xmlSchemaSetValidErrors(routine);
    }
    
    return();
}
/*-----------------------------------------------------------------------------------------------------------------------*/
static FIXErrCode xml_validate(xmlDoc* doc, FIXError** error)
{
   xmlSchemaParserCtxtPtr pctx = xmlSchemaNewMemParserCtxt(fix_xsd, strlen(fix_xsd));
   xmlSchemaPtr schema = xmlSchemaParse(pctx);
   if (!schema)
   {
      return FIX_FAILED;
   }
   xmlSchemaValidCtxtPtr validCtx = xmlSchemaNewValidCtxt(schema);
   xmlSchemaSetValidErrors(validCtx, &xmlErrorHandler, &xmlErrorHandler, error);

   int32_t res = xmlSchemaValidateDoc(validCtx, doc);

   xmlSchemaFreeValidCtxt(validCtx);
   xmlSchemaFree(schema);
   xmlSchemaFreeParserCtxt(pctx);

   return res ? FIX_FAILED : FIX_SUCCESS;
}
void CLibXmlValidator::validate()
{
    if (!xmlFile.length() && !xml.length())
        throw MakeStringException(XMLERR_MissingSource, "Source XML not provided");
    if (!xsdFile.length() && !xsd.length())
        throw MakeStringException(XMLERR_MissingSource, "XML Schema not provided");

    xmlParserInputBufferPtr input;
    if (xmlFile.length())
        input = xmlParserInputBufferCreateFilename(xmlFile.get(), XML_CHAR_ENCODING_NONE);
    else
        input = xmlParserInputBufferCreateMem(xml.str(), xml.length()+1, XML_CHAR_ENCODING_NONE);
    if (!input)
        throw MakeStringException(XMLERR_InvalidXml, "Failed to create XML input stream");

    xmlSchemaParserCtxtPtr xsdParser;
    if (xsdFile.length())
        xsdParser = xmlSchemaNewParserCtxt(xsdFile.get());
    else
        xsdParser = xmlSchemaNewMemParserCtxt(xsd.str(), xsd.length());
    if (!xsdParser)
        throw MakeStringException(XMLERR_InvalidXsd, "Failed to load XML Schema");

    xmlSchemaSetParserErrors(xsdParser, libxmlXsdErrorMsgHandler, libxmlXsdErrorMsgHandler, this);
    xmlSchemaPtr schema = xmlSchemaParse(xsdParser);
    xmlSchemaFreeParserCtxt(xsdParser);

    if (!schema)
        throw MakeStringException(XMLERR_InvalidXsd, "XSD schema parsing failed");

    xmlSchemaValidCtxtPtr validator = xmlSchemaNewValidCtxt(schema);
    xmlSchemaSetValidErrors(validator, libxmlXsdErrorMsgHandler, libxmlXsdErrorMsgHandler, this);

    int ret = xmlSchemaValidateStream(validator, input, XML_CHAR_ENCODING_NONE, emptySAXHandler, (void *)this);
    if (ret != 0)
    {
        ensureExceptions()->append(*MakeStringException(XMLERR_XsdValidationFailed, "XML validation failed"));
        throw exceptions.getClear();
    }
    xmlSchemaFreeValidCtxt(validator);
}
Beispiel #12
0
int xml2lpc_validate(xml2lpc_context *xmlCtx) {
	xmlSchemaValidCtxtPtr validCtx;
	xmlSchemaParserCtxtPtr parserCtx;
	int ret;

	xml2lpc_context_clear_logs(xmlCtx);
	parserCtx = xmlSchemaNewDocParserCtxt(xmlCtx->xsd);
	validCtx = xmlSchemaNewValidCtxt(xmlSchemaParse(parserCtx));
	xmlSchemaSetValidErrors(validCtx, xml2lpc_genericxml_error, xml2lpc_genericxml_warning, xmlCtx);
	ret = xmlSchemaValidateDoc(validCtx, xmlCtx->doc);
	if(ret > 0) {
		if(strlen(xmlCtx->warningBuffer) > 0)
			xml2lpc_log(xmlCtx, XML2LPC_WARNING, "%s", xmlCtx->warningBuffer);
		if(strlen(xmlCtx->errorBuffer) > 0)
			xml2lpc_log(xmlCtx, XML2LPC_ERROR, "%s", xmlCtx->errorBuffer);
	} else if(ret < 0) {
		xml2lpc_log(xmlCtx, XML2LPC_ERROR, "Internal error");
	}
	xmlSchemaFreeValidCtxt(validCtx);
	return ret;
}
Beispiel #13
0
/* process interface.cfg file
	iface - name of the interface to process, or "" for all interfaces
	dry_run = 1 - test xml without applying anything
	dry_run = 0 - test + apply
 */
void opt_process(char *iface, int dry_run) {
	char cfg_file_name[FILENAME_MAX];
	sprintf(cfg_file_name, "%s/%s", KB_CONFIG_DIR, KB_IFACE_CFG);
	xmlDocPtr document = xmlReadFile(cfg_file_name, NULL, 0);
	if (NULL == document) { /* can't load */
		form_sys_result(KB_ERR, "Can't parse config file");
	} else { /* process */
		/* check schema compliance */
		char schema_file_name[FILENAME_MAX];
		sprintf(schema_file_name, "%s/%s", KB_CONFIG_DIR, KB_IFACE_SCHEMA);
		xmlSchemaParserCtxtPtr schemaParser = xmlSchemaNewParserCtxt(schema_file_name);
		if (NULL != schemaParser) {
			xmlSchemaPtr schema = xmlSchemaParse(schemaParser);
			if (NULL != schema) {
				xmlSchemaValidCtxtPtr validityContext = xmlSchemaNewValidCtxt(schema);
				xmlSchemaSetValidErrors(validityContext, schemaErrorCallback, schemaWarningCallback, 0);
				if (NULL != validityContext) {
					if (0 != xmlSchemaValidateFile(validityContext, cfg_file_name, 0)) {
						/* validation error */
						schema_error_end();
					} else {
						/* additional processing */
						kb_process_xml(document, iface, dry_run);
					}
					xmlSchemaFreeValidCtxt(validityContext);
				} else {
					form_sys_result(KB_ERR, "Can't create validation context");
				}
				xmlSchemaFree(schema);
			} else {
				form_sys_result(KB_ERR, "Can't parse schema");
			}
			xmlSchemaFreeParserCtxt(schemaParser);
		} else {
			form_sys_result(KB_ERR, "Can't parse schema file");
		}
		xmlFreeDoc(document);
	}
}
Beispiel #14
0
bool XMLSchema::validate(xmlDocPtr doc, const std::string& xsd)
{
    xmlParserOption parserOption(XML_PARSE_NONET);

    xmlDocPtr schemaDoc = xmlReadMemory(xsd.c_str(), xsd.size(),
        NULL, NULL, parserOption);
    xmlSchemaParserCtxtPtr parserCtxt = xmlSchemaNewDocParserCtxt(schemaDoc);
    xmlSchemaSetParserStructuredErrors(parserCtxt,
        &OCISchemaParserStructuredErrorHandler, m_global_context);
    xmlSchemaPtr schema = xmlSchemaParse(parserCtxt);
    xmlSchemaValidCtxtPtr validCtxt = xmlSchemaNewValidCtxt(schema);
    xmlSchemaSetValidErrors(validCtxt, &OCISchemaValidityError,
        &OCISchemaValidityDebug, m_global_context);
    bool valid = (xmlSchemaValidateDoc(validCtxt, doc) == 0);

    xmlFreeDoc(schemaDoc);
    xmlSchemaFreeParserCtxt(parserCtxt);
    xmlSchemaFree(schema);
    xmlSchemaFreeValidCtxt(validCtxt);

    return valid;
}
Beispiel #15
0
static inline HRESULT Schema_validate_tree(xmlSchemaPtr schema, xmlNodePtr tree)
{
    xmlSchemaValidCtxtPtr svctx;
    int err;

    TRACE("(%p, %p)\n", schema, tree);
    /* TODO: if validateOnLoad property is false,
     *       we probably need to validate the schema here. */
    svctx = xmlSchemaNewValidCtxt(schema);
    xmlSchemaSetValidErrors(svctx, validate_error, validate_warning, NULL);
#ifdef HAVE_XMLSCHEMASSETVALIDSTRUCTUREDERRORS
    xmlSchemaSetValidStructuredErrors(svctx, validate_serror, NULL);
#endif

    if (tree->type == XML_DOCUMENT_NODE)
        err = xmlSchemaValidateDoc(svctx, (xmlDocPtr)tree);
    else
        err = xmlSchemaValidateOneElement(svctx, tree);

    xmlSchemaFreeValidCtxt(svctx);
    return err? S_FALSE : S_OK;
}
Beispiel #16
0
int main(int argc, char **argv) {

    int i;

    int files = 0;

    xmlSchemaPtr schema = NULL;

    for (i = 1; i < argc ; i++) {

#ifdef LIBXML_DEBUG_ENABLED

	if ((!strcmp(argv[i], "-debug")) || (!strcmp(argv[i], "--debug")))

	    debug++;

	else

#endif

#ifdef HAVE_SYS_MMAN_H

	if ((!strcmp(argv[i], "-memory")) || (!strcmp(argv[i], "--memory"))) {

	    memory++;

        } else

#endif

	if ((!strcmp(argv[i], "-noout")) || (!strcmp(argv[i], "--noout"))) {

	    noout++;

        }

    }

    /*xmlLineNumbersDefault(1);*/

    for (i = 1; i < argc ; i++) {

	if (argv[i][0] != '-') {

	    if (schema == NULL) {

		xmlSchemaParserCtxtPtr ctxt;



#ifdef HAVE_SYS_MMAN_H

		if (memory) {

		    int fd;

		    struct stat info;

		    const char *base;

		    if (stat(argv[i], &info) < 0) 

			break;

		    if ((fd = open(argv[i], O_RDONLY)) < 0)

			break;

		    base = mmap(NULL, info.st_size, PROT_READ,

			        MAP_SHARED, fd, 0) ;

		    if (base == (void *) MAP_FAILED)

			break;



		    ctxt = xmlSchemaNewMemParserCtxt((char *)base,info.st_size);



		    xmlSchemaSetParserErrors(ctxt,

			    (xmlSchemaValidityErrorFunc) fprintf,

			    (xmlSchemaValidityWarningFunc) fprintf,

			    stderr);

		    schema = xmlSchemaParse(ctxt);

		    xmlSchemaFreeParserCtxt(ctxt);

		    munmap((char *) base, info.st_size);

		} else

#endif

		{	

		    /*printf("\n**** CALLING :: xmlSchemaNewParserCtxt argv[i] = %s \n ", argv[i]);*/



		    printf("\n**** CALLING :: xmlSchemaNewParserCtxt \n ");



		    ctxt = xmlSchemaNewParserCtxt(argv[i]);

		    //ctxt = xmlSchemaNewParserCtxt("/root/Code/libxml2-2.6.15/ixml/basic/memory_test.xsd");



		    printf("\n**** CALLING :: xmlSchemaParse \n ");



		    xmlSchemaSetParserErrors(ctxt,

			    (xmlSchemaValidityErrorFunc) fprintf,

			    (xmlSchemaValidityWarningFunc) fprintf,

			    stderr);

		    printf("\n**** CALLING :: xmlSchemaParse \n ");

		    schema = xmlSchemaParse(ctxt);

		    xmlSchemaFreeParserCtxt(ctxt);

		}

#if 0		

#ifdef LIBXML_OUTPUT_ENABLED

#ifdef LIBXML_DEBUG_ENABLED

		if (debug)

		    xmlSchemaDump(stdout, schema);

#endif

#endif /* LIBXML_OUTPUT_ENABLED */

#endif /*#if 0*/		

		if (schema == NULL) 

		    goto failed_schemas;

	    } else {



		IXML_Document *doc;



       	printf("\n ***** CALLING :: xmlReadFile:> %s ", argv[i]);



		//doc = xmlReadFile(argv[i],NULL,0);

		//doc = ixmlLoadDocument("/root/Code/libxml2-2.6.15/ixml/basic/memory_test.xml");

		doc = ixmlLoadDocument(argv[i]);

#if 0		

	printf("nodeName = %s\n",doc->n.firstChild->nodeName);

	printf("firstAttr->nodeName = %s\n",doc->n.firstChild->firstChild->firstAttr->nodeName);

	printf("firstAttr->nodeValue = %s\n",doc->n.firstChild->firstChild->firstAttr->nodeValue);

	printf("firstAttr->nextSibling->nodeName = %s\n",doc->n.firstChild->firstChild->firstAttr->nextSibling->nodeName);

	printf("firstAttr->nextSibling->nodeValue = %s\n",doc->n.firstChild->firstChild->firstAttr->nextSibling->nodeValue);

#endif

		if (doc == NULL) {

		    fprintf(stderr, "Could not parse %s\n", argv[i]);

		} else {

		    xmlSchemaValidCtxtPtr ctxt;

		    int ret;

	        	printf("\n ***** CALLING :: xmlSchemaNewValidCtxt *****\n ");



		    ctxt = xmlSchemaNewValidCtxt(schema);



	        	printf("\n ***** CALLING :: xmlSchemaSetValidErrors *****\n ");



		    xmlSchemaSetValidErrors(ctxt,

			    (xmlSchemaValidityErrorFunc) fprintf,

			    (xmlSchemaValidityWarningFunc) fprintf,

			    stderr);

		    ret = xmlSchemaValidateDoc(ctxt, doc);

			

#if 0			

			printf("nodeName = %s\n",doc->n.firstChild->nodeName);

			printf("firstAttr->nodeName = %s\n",doc->n.firstChild->firstChild->firstAttr->nodeName);

			printf("firstAttr->nodeValue = %s\n",doc->n.firstChild->firstChild->firstAttr->nodeValue);

			printf("firstAttr->nextSibling->nodeName = %s\n",doc->n.firstChild->firstChild->firstAttr->nextSibling->nodeName);

			printf("firstAttr->nextSibling->nodeValue = %s\n",doc->n.firstChild->firstChild->firstAttr->nextSibling->nodeValue);

#endif			

		    if (ret == 0) {

			printf("%s validates\n", argv[i]);

		    } else if (ret > 0) {

			printf("%s fails to validate\n", argv[i]);

		    } else {

			printf("%s validation generated an internal error\n",

			       argv[i]);

		    }

		    xmlSchemaFreeValidCtxt(ctxt);



		    ixmlDocument_free(doc);

		}

	    }

	    files ++;

	}

    }

    if (schema != NULL)

	xmlSchemaFree(schema);

    if (files == 0) {

	printf("Usage : %s [--debug] [--noout] schemas XMLfiles ...\n",

	       argv[0]);

	printf("\tParse the HTML files and output the result of the parsing\n");

#ifdef LIBXML_DEBUG_ENABLED

	printf("\t--debug : dump a debug tree of the in-memory document\n");

#endif

	printf("\t--noout : do not print the result\n");

#ifdef HAVE_SYS_MMAN_H

	printf("\t--memory : test the schemas in memory parsing\n");

#endif

    }

failed_schemas:

	/*printf("\n**** failed_schemas\n");*/

    xmlSchemaCleanupTypes();

    /*xmlCleanupParser();

	xmlResetLastError();

    xmlMemoryDump();*/



    return(0);

}
Beispiel #17
0
int main( int argc, char * argv[] )
{
   char * inputname = NULL;
   char * dirname = NULL, * dummy = NULL;
   int fd = -1, errcode = 0, rc = 0, debug = 0;
   size_t length, i, j;
   int separator = -1;
   psocOptionHandle optHandle;
   char * buff = NULL;
   bool ok;
   
#if HAVE_STAT || HAVE__STAT
   struct stat status;

   struct psocOptStruct opts[2] = {
      { 'i', "input",    0, "input_filename", "Filename for the input (XML)" },
      { 'o', "output",   0, "output_dirname", "Directory name for the output files" }
   };

#else
   struct psocOptStruct opts[3] = {
      { 'i', "input",    0, "input_filename", "Filename for the input (XML)" },
      { 'l', "length",   0, "input length",   "Length of input if stat() not supported" },
      { 'o', "output",   0, "output_dirname", "Directory name for the output files" }
   };

#endif

   xmlSchemaPtr schema = NULL;
   xmlSchemaValidCtxtPtr  validCtxt = NULL;
   xmlSchemaParserCtxtPtr parserCtxt = NULL;
   xmlNode * root = NULL;
   xmlDoc  * doc = NULL;
   xmlChar * prop = NULL;
   
#if HAVE_STAT || HAVE__STAT
   ok = psocSetSupportedOptions( 2, opts, &optHandle );
#else
   ok = psocSetSupportedOptions( 3, opts, &optHandle );
#endif
   PSO_POST_CONDITION( ok == true || ok == false );
   if ( ! ok ) {
      fprintf( stderr, "Internal error in psocSetSupportedOptions\n" );
      return 1;
   }
   
   errcode = psocValidateUserOptions( optHandle, argc, argv, 1 );
   if ( errcode < 0 ) {
      psocShowUsage( optHandle, argv[0], "" );
      return 1;
   }
   
   if ( errcode > 0 ) {
      psocShowUsage( optHandle, argv[0], "" );
      return 0;
   }

   psocGetShortOptArgument( optHandle, 'i', &inputname );
   psocGetShortOptArgument( optHandle, 'o', &dirname );

#if HAVE_STAT || HAVE__STAT
   errcode = stat( inputname, &status );
   if ( errcode != 0) {
      fprintf( stderr, "Cannot access the size of the input file\n" );
      return 1;
   }
   length = status.st_size;
#else   
   psocGetShortOptArgument( optHandle, 'o', &dummy );
   sscanf( dummy, PSO_SIZE_T_FORMAT, &length );
#endif

   fd = open( inputname, O_RDONLY );
   if ( fd == -1 ) {
      fprintf( stderr, "Cannot open the input file\n" );
      return 1;
   }

   buff = (char *)malloc(length + 1 );
   if ( buff == NULL ) {
      fprintf( stderr, "Memory allocation error\n" );
      goto cleanup;
   }
   
   i = read( fd, buff, length );
   if ( i != length ) {
      fprintf( stderr, "Cannot read the input file\n" );
      goto cleanup;
   }
   buff[length] = 0;
   
   if ( debug ) {
      doc = xmlReadMemory( buff, i, NULL, NULL, 0 );
   }
   else {
      doc = xmlReadMemory( buff, i, NULL, NULL, XML_PARSE_NOERROR | XML_PARSE_NOWARNING );
   }
   if ( doc == NULL ) {
      fprintf( stderr, "Error reading xml in memory\n" );
      errcode = -1;
      goto cleanup;
   }
   
   root = xmlDocGetRootElement( doc );
   if ( root == NULL ) {
      fprintf( stderr, "Error: no root\n" );
      goto cleanup;
   }

//   if ( xmlStrcmp( root->name, BAD_CAST "quasar_config") != 0 ) {
//      errcode = PSOW_XML_INVALID_ROOT;
//      goto cleanup;
//   }
   
   prop = xmlGetProp( root, BAD_CAST "schemaLocation" );
   if ( prop == NULL ) {
      fprintf( stderr, "Error: no schemaLocation property (of root)\n" );
      goto cleanup;
   }
   
   for ( i = 0; i < xmlStrlen(prop)-1; ++i ) {
      if ( isspace(prop[i]) ) {
         for ( j = i+1; j < xmlStrlen(prop)-1; ++j ) {
            if ( isspace(prop[j]) == 0 ) {
               separator = j;
               break;
            }
         }
         break;
      }
   }
   if ( separator == -1 ) {
      fprintf( stderr, "Error: invalid schemaLocation property (of root)\n" );
      goto cleanup;
   }
   
   parserCtxt = xmlSchemaNewParserCtxt( (char*)&prop[separator] );
   if ( parserCtxt == NULL ) {
      fprintf( stderr, "Error: creating new parser context failed\n" );
      goto cleanup;
   }
   
   schema = xmlSchemaParse( parserCtxt );
   if ( schema == NULL ) {
      fprintf( stderr, "Error: parsing the schema failed\n" );
      goto cleanup;
   }
   
   xmlFree( prop );
   prop = NULL;

   validCtxt = xmlSchemaNewValidCtxt( schema );
   if ( validCtxt == NULL ) {
      fprintf( stderr, "Error: creating new validation context failed\n" );
      goto cleanup;
   }
   
   if ( debug ) {
      xmlSchemaSetValidErrors( validCtxt,
                               (xmlSchemaValidityErrorFunc) fprintf,
                               (xmlSchemaValidityWarningFunc) fprintf,
                               stderr );
   }
   else {
      xmlSchemaSetValidErrors( validCtxt,
                               (xmlSchemaValidityErrorFunc) dummyErrorFunc,
                               (xmlSchemaValidityWarningFunc) dummyErrorFunc,
                               stderr );
   }
   
   if ( xmlSchemaValidateDoc( validCtxt, doc ) != 0 ) {
      fprintf( stderr, "Error: document validation failed\n" );
      goto cleanup;
   }

   if ( xmlStrcmp( root->name, BAD_CAST "photon" ) == 0 ) {
      /* This is a topFolder and has no name */
      errcode = doFolder( root, dirname );
   }
   else {
      prop = xmlGetProp( root, BAD_CAST "objName" );
      if ( prop == NULL ) {
         fprintf( stderr, "Error getting the name of the root\n" );
         goto cleanup;
      }
      if ( validateName( prop ) != 0 ) {
         fprintf( stderr, "Invalid object name = %s\n", (char *) prop );
         goto cleanup;
      }

      rc = mkdir( dirname, 0755 );
      if ( rc != 0 ) {
         if ( errno != EEXIST ) {
            fprintf( stderr, "Creating directory %s failed\n", dirname );
            goto cleanup;
         }
      }
      rc = chdir( dirname );
      if ( rc != 0 ) {
         fprintf( stderr, "cd to directory %s failed\n", dirname );
         goto cleanup;
      }
      
      if ( xmlStrcmp( root->name, BAD_CAST "folder" ) == 0 ) {
         errcode = doFolder( root, (char *)prop );
      }
      else if ( xmlStrcmp( root->name, BAD_CAST "hashmap") == 0 ) {
         rc = doHashMap( root, (char *)prop );
      }
      else if ( xmlStrcmp( root->name, BAD_CAST "queue") == 0 ) {
         rc = doQueue( root, (char *)prop );
      }
      else {
         fprintf( stderr, "Error: root type is invalid\n" );
         errcode = -1;
      }

      rc = chdir( ".." );
      if ( rc != 0 ) {
         fprintf( stderr, "cd to directory \"..\" failed\n" );
      }
   }

cleanup:
   
   if ( buff != NULL ) free( buff );
   if ( fd != -1 ) close(fd);
   if ( parserCtxt ) xmlSchemaFreeParserCtxt( parserCtxt );
   if ( schema ) xmlSchemaFree( schema );
   if ( validCtxt ) xmlSchemaFreeValidCtxt( validCtxt );
   if ( prop ) xmlFree( prop );
   if ( doc ) xmlFreeDoc( doc );

   /* In case this program is include in a script */
   if ( errcode != 0  || rc != 0 ) return 1;

   return 0;   
}
Beispiel #18
0
/**
 * \fn msiXmlDocSchemaValidate(msParam_t *xmlObj, msParam_t *xsdObj, msParam_t *status, ruleExecInfo_t *rei)
 *
 * \brief  This microservice validates an XML file against an XSD schema, both iRODS objects.
 * 
 * \module xml
 * 
 * \since pre-2.1
 * 
 * \author  Antoine de Torcy
 * \date    2008/05/29
 * 
 * \usage See clients/icommands/test/rules3.0/
 *
 * \param[in] xmlObj - a msParam of type DataObjInp_MS_T or STR_MS_T which is irods path of the XML object.
 * \param[in] xsdObj - a msParam of type DataObjInp_MS_T or STR_MS_T which is irods path of the XSD object.
 * \param[out] status - a msParam of type INT_MS_T which is a validation result.
 * \param[in,out] rei - The RuleExecInfo structure that is automatically
 *    handled by the rule engine. The user does not include rei as a
 *    parameter in the rule invocation.
 *
 * \DolVarDependence None
 * \DolVarModified None
 * \iCatAttrDependence None
 * \iCatAttrModified None
 * \sideeffect None
 *
 * \return integer
 * \retval 0 on success
 * \pre None
 * \post None
 * \sa None
**/
int 
msiXmlDocSchemaValidate(msParam_t *xmlObj, msParam_t *xsdObj, msParam_t *status, ruleExecInfo_t *rei) 
{
	/* for parsing msParams and to open iRODS objects */
	dataObjInp_t xmlObjInp, *myXmlObjInp;
	dataObjInp_t xsdObjInp, *myXsdObjInp;
	int xmlObjID, xsdObjID;

	/* for getting size of objects to read from */
	rodsObjStat_t *rodsObjStatOut = NULL;

	/* for reading from iRODS objects */
	openedDataObjInp_t openedDataObjInp;
	bytesBuf_t *xmlBuf = NULL;
	char *tail;

	/* for xml parsing and validating */
	xmlDocPtr doc, xsd_doc;
	xmlSchemaParserCtxtPtr parser_ctxt;
	xmlSchemaPtr schema;
	xmlSchemaValidCtxtPtr valid_ctxt;
	bytesBuf_t *errBuf;

	/* misc. to avoid repeating rei->rsComm */
	rsComm_t *rsComm;



	/*************************************  USUAL INIT PROCEDURE **********************************/
	
	/* For testing mode when used with irule --test */
	RE_TEST_MACRO ("    Calling msiXmlDocSchemaValidate")


	/* Sanity checks */
	if (rei == NULL || rei->rsComm == NULL)
	{
		rodsLog (LOG_ERROR, "msiXmlDocSchemaValidate: input rei or rsComm is NULL.");
		return (SYS_INTERNAL_NULL_INPUT_ERR);
	}

	rsComm = rei->rsComm;



	/************************************ ADDITIONAL INIT SETTINGS *********************************/

	/* XML constants */
	xmlSubstituteEntitiesDefault(1);
	xmlLoadExtDtdDefaultValue = 1;


	/* allocate memory for output error buffer */
	errBuf = (bytesBuf_t *)malloc(sizeof(bytesBuf_t));
	errBuf->buf = strdup("");
	errBuf->len = strlen((char*)errBuf->buf);

	/* Default status is failure, overwrite if success */
	fillBufLenInMsParam (status, -1, NULL);

	
	/********************************** RETRIEVE INPUT PARAMS **************************************/

	/* Get path of XML document */
	rei->status = parseMspForDataObjInp (xmlObj, &xmlObjInp, &myXmlObjInp, 0);
	if (rei->status < 0)
	{
		rodsLog (LOG_ERROR, "msiXmlDocSchemaValidate: input xmlObj error. status = %d", rei->status);
		free(errBuf);
		return (rei->status);
	}


	/* Get path of schema */
	rei->status = parseMspForDataObjInp (xsdObj, &xsdObjInp, &myXsdObjInp, 0);
	if (rei->status < 0)
	{
		rodsLog (LOG_ERROR, "msiXmlDocSchemaValidate: input xsdObj error. status = %d", rei->status);
		free(errBuf);
		return (rei->status);
	}


	/******************************** OPEN AND READ FROM XML OBJECT ********************************/

	/* Open XML file */
	if ((xmlObjID = rsDataObjOpen(rsComm, &xmlObjInp)) < 0) 
	{
		rodsLog (LOG_ERROR, "msiXmlDocSchemaValidate: Cannot open XML data object. status = %d", xmlObjID);
		free(errBuf);
		return (xmlObjID);
	}


	/* Get size of XML file */
	rei->status = rsObjStat (rsComm, &xmlObjInp, &rodsObjStatOut);
	if (rei->status < 0 || !rodsObjStatOut)
	{
		rodsLog (LOG_ERROR, "msiXmlDocSchemaValidate: Cannot stat XML data object. status = %d", rei->status);
		free(errBuf);
		return (rei->status);
	}


	/* xmlBuf init */
	/* memory for xmlBuf->buf is allocated in rsFileRead() */
	xmlBuf = (bytesBuf_t *) malloc (sizeof (bytesBuf_t));
	memset (xmlBuf, 0, sizeof (bytesBuf_t));


	/* Read content of XML file */
	memset (&openedDataObjInp, 0, sizeof (openedDataObjInp_t));
	openedDataObjInp.l1descInx = xmlObjID;
	openedDataObjInp.len = (int)rodsObjStatOut->objSize + 1;	/* extra byte to add a null char */

	rei->status = rsDataObjRead (rsComm, &openedDataObjInp, xmlBuf);

	/* add terminating null character */
	tail = (char*)xmlBuf->buf;
	tail[openedDataObjInp.len - 1] = '\0';


	/* Close XML file */
	rei->status = rsDataObjClose (rsComm, &openedDataObjInp);

	/* cleanup */
	freeRodsObjStat (rodsObjStatOut);



	/*************************************** PARSE XML DOCUMENT **************************************/

	/* Parse xmlBuf.buf into an xmlDocPtr */
	doc = xmlParseDoc((xmlChar*)xmlBuf->buf);
	clearBBuf(xmlBuf);

	if (doc == NULL)
	{
		rodsLog (LOG_ERROR, "msiXmlDocSchemaValidate: XML document cannot be loaded or is not well-formed.");
		free(errBuf);
	    xmlCleanupParser();

	    return (USER_INPUT_FORMAT_ERR);
	}



	/******************************** OPEN AND READ FROM XSD OBJECT ********************************/

	/* Open schema file */
	if ((xsdObjID = rsDataObjOpen(rsComm, &xsdObjInp)) < 0) 
	{
		rodsLog (LOG_ERROR, "msiXmlDocSchemaValidate: Cannot open XSD data object. status = %d", xsdObjID);
		free(errBuf);
		xmlFreeDoc(doc);
	    xmlCleanupParser();

		return (xsdObjID);
	}


	/* Get size of schema file */
	rei->status = rsObjStat (rsComm, &xsdObjInp, &rodsObjStatOut);


	/* Read entire schema file */
	memset (&openedDataObjInp, 0, sizeof (openedDataObjInp_t));
	openedDataObjInp.l1descInx = xsdObjID;
	openedDataObjInp.len = (int)rodsObjStatOut->objSize + 1;	/* to add null char */

	rei->status = rsDataObjRead (rsComm, &openedDataObjInp, xmlBuf);

	/* add terminating null character */
	tail = (char*)xmlBuf->buf;
	tail[openedDataObjInp.len - 1] = '\0';


	/* Close schema file */
	rei->status = rsDataObjClose (rsComm, &openedDataObjInp);

	/* cleanup */
	freeRodsObjStat (rodsObjStatOut);



	/*************************************** PARSE XSD DOCUMENT **************************************/

	/* Parse xmlBuf.buf into an xmlDocPtr */
	xsd_doc = xmlParseDoc((xmlChar*)xmlBuf->buf);
	clearBBuf(xmlBuf);

	if (xsd_doc == NULL)
	{
		rodsLog (LOG_ERROR, "msiXmlDocSchemaValidate: XML Schema cannot be loaded or is not well-formed.");
		free(errBuf);
		xmlFreeDoc(doc);
		xmlCleanupParser();

	    return (USER_INPUT_FORMAT_ERR);
	}



	/**************************************** VALIDATE DOCUMENT **************************************/

	/* Create a parser context */
	parser_ctxt = xmlSchemaNewDocParserCtxt(xsd_doc);
	if (parser_ctxt == NULL)
	{
		rodsLog (LOG_ERROR, "msiXmlDocSchemaValidate: Unable to create a parser context for the schema.");
		free(errBuf);
		xmlFreeDoc(xsd_doc);
		xmlFreeDoc(doc);
	    xmlCleanupParser();

	    return (USER_INPUT_FORMAT_ERR);
	}


	/* Parse the XML schema */
	schema = xmlSchemaParse(parser_ctxt);
	if (schema == NULL) 
	{
		rodsLog (LOG_ERROR, "msiXmlDocSchemaValidate: Invalid schema.");
		free(errBuf);
		xmlSchemaFreeParserCtxt(parser_ctxt);
		xmlFreeDoc(doc);
		xmlFreeDoc(xsd_doc);
        xmlCleanupParser();

	    return (USER_INPUT_FORMAT_ERR);
	}


	/* Create a validation context */
	valid_ctxt = xmlSchemaNewValidCtxt(schema);
	if (valid_ctxt == NULL) 
	{
		rodsLog (LOG_ERROR, "msiXmlDocSchemaValidate: Unable to create a validation context for the schema.");
		free(errBuf);
		xmlSchemaFree(schema);
		xmlSchemaFreeParserCtxt(parser_ctxt);
		xmlFreeDoc(xsd_doc);
		xmlFreeDoc(doc);
	    xmlCleanupParser();

	    return (USER_INPUT_FORMAT_ERR);
	}


	/* Set myErrorCallback() as the default handler for error messages and warnings */
	xmlSchemaSetValidErrors(valid_ctxt, (xmlSchemaValidityErrorFunc)myErrorCallback, (xmlSchemaValidityWarningFunc)myErrorCallback, errBuf);


	/* Validate XML doc */
	rei->status = xmlSchemaValidateDoc(valid_ctxt, doc);



	/******************************************* WE'RE DONE ******************************************/

	/* return both error code and messages through status */
	resetMsParam (status);
	fillBufLenInMsParam (status, rei->status, errBuf);


	/* cleanup of all xml parsing stuff */
	xmlSchemaFreeValidCtxt(valid_ctxt);
	xmlSchemaFree(schema);
	xmlSchemaFreeParserCtxt(parser_ctxt);
	xmlFreeDoc(doc);
	xmlFreeDoc(xsd_doc);
	xmlCleanupParser();

	return (rei->status);
}
Beispiel #19
0
/**
 * Validation function take first argument as XML type, then check if is
 * well formated. If so, do the same for XSD document. If both success, check
 * XML document against XSD schema restrictions.
 * @return true if pass, false otherwise
 */
Datum
xmlvalidate_xsd(PG_FUNCTION_ARGS)
{
#ifdef USE_LIBXML

	text        *data   = NULL;
	unsigned char   *xsd    = NULL;
	xmlChar     *utf8xsd    = NULL;
	xmltype     *xmldata    = NULL;
	char        *xmldataint = NULL;
	xmlChar     *xmldatastr = NULL;
	bool        result  = false;
	int         lenxml  = -1;       // length of xml data
	int         lenxsd  = -1;       // length of xsd data
	xmlDocPtr               doc = NULL;
	int ret = -1;

	xmlSchemaParserCtxtPtr  ctxt    = NULL;
	xmlSchemaPtr            schema  = NULL;
	xmlSchemaValidCtxtPtr   validctxt = NULL;


    // creating xmlChar * from internal XML type
    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 XSD
    data = PG_GETARG_TEXT_P(1);
    lenxsd = VARSIZE(data) - VARHDRSZ;
    xsd = (unsigned char*)text_to_cstring(data);

    //encode XML to internal representation with UTF-8, only one used in LibXML
	utf8xsd = pg_do_encoding_conversion(xsd,
										   lenxsd,
										   GetDatabaseEncoding(),
										   PG_UTF8);

    //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) {
		 ereport(ERROR,
				(errcode(ERRCODE_INVALID_XML_DOCUMENT),
				 errmsg("Failed to parse XML document")));
        PG_RETURN_BOOL (false);
    }

    ctxt = xmlSchemaNewMemParserCtxt((const char*)xsd, lenxsd);

    if (ctxt == NULL)
    { // unable to create parser context
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_XML_DOCUMENT),
				 errmsg("Error with creating schema, check if XSD schema is valid")));
        PG_RETURN_BOOL (false);
    }

    schema = xmlSchemaParse(ctxt);  // parse schema
    xmlSchemaFreeParserCtxt(ctxt);  // realease parser context

    validctxt = xmlSchemaNewValidCtxt(schema);
    if (validctxt == NULL)
    { // cant create validation context
        xmlSchemaFree(schema);
        elog(ERROR, "Cant create validation context");
        PG_RETURN_BOOL (false);
    }

    // set errors to SQL errors
	xmlSchemaSetValidErrors(validctxt,
			    xml_error_handler,
			    NULL,
			    stderr);


    ret = xmlSchemaValidateDoc(validctxt, doc);
    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;
    }

    xmlSchemaFree(schema);
    xmlSchemaFreeValidCtxt(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
}
Beispiel #20
0
int CPLValidateXML(const char* pszXMLFilename,
                   const char* pszXSDFilename,
                   CPL_UNUSED char** papszOptions)
{
    char szHeader[2048];
    CPLString osTmpXSDFilename;

    if( pszXMLFilename[0] == '<' )
    {
        strncpy(szHeader, pszXMLFilename, sizeof(szHeader));
        szHeader[sizeof(szHeader)-1] = '\0';
    }
    else
    {
        VSILFILE* fpXML = VSIFOpenL(pszXMLFilename, "rb");
        if (fpXML == NULL)
        {
            CPLError(CE_Failure, CPLE_OpenFailed,
                     "Cannot open %s", pszXMLFilename);
            return FALSE;
        }
        int nRead = (int)VSIFReadL(szHeader, 1, sizeof(szHeader)-1, fpXML);
        szHeader[nRead] = '\0';
        CPL_IGNORE_RET_VAL(VSIFCloseL(fpXML));
    }

    /* Workaround following bug : "element FeatureCollection: Schemas validity error : Element '{http://www.opengis.net/wfs}FeatureCollection': No matching global declaration available for the validation root" */
    /* We create a wrapping XSD that imports the WFS .xsd (and possibly the GML .xsd too) and the application schema */
    /* This is a known libxml2 limitation */
    if (strstr(szHeader, "<wfs:FeatureCollection") ||
            (strstr(szHeader, "<FeatureCollection") && strstr(szHeader, "xmlns:wfs=\"http://www.opengis.net/wfs\"")))
    {
        const char* pszWFSSchemaNamespace = "http://www.opengis.net/wfs";
        const char* pszWFSSchemaLocation = NULL;
        const char* pszGMLSchemaLocation = NULL;
        if (strstr(szHeader, "wfs/1.0.0/WFS-basic.xsd"))
        {
            pszWFSSchemaLocation = "http://schemas.opengis.net/wfs/1.0.0/WFS-basic.xsd";
        }
        else if (strstr(szHeader, "wfs/1.1.0/wfs.xsd"))
        {
            pszWFSSchemaLocation = "http://schemas.opengis.net/wfs/1.1.0/wfs.xsd";
        }
        else if (strstr(szHeader, "wfs/2.0/wfs.xsd"))
        {
            pszWFSSchemaNamespace = "http://www.opengis.net/wfs/2.0";
            pszWFSSchemaLocation = "http://schemas.opengis.net/wfs/2.0/wfs.xsd";
        }

        VSILFILE* fpXSD = VSIFOpenL(pszXSDFilename, "rb");
        if (fpXSD == NULL)
        {
            CPLError(CE_Failure, CPLE_OpenFailed,
                     "Cannot open %s", pszXSDFilename);
            return FALSE;
        }
        int nRead = (int)VSIFReadL(szHeader, 1, sizeof(szHeader)-1, fpXSD);
        szHeader[nRead] = '\0';
        CPL_IGNORE_RET_VAL(VSIFCloseL(fpXSD));

        if (strstr(szHeader, "gml/3.1.1") != NULL &&
                strstr(szHeader, "gml/3.1.1/base/gml.xsd") == NULL)
        {
            pszGMLSchemaLocation = "http://schemas.opengis.net/gml/3.1.1/base/gml.xsd";
        }

        if (pszWFSSchemaLocation != NULL)
        {
            osTmpXSDFilename = CPLSPrintf("/vsimem/CPLValidateXML_%p_%p.xsd", pszXMLFilename, pszXSDFilename);
            char* pszEscapedXSDFilename = CPLEscapeString(pszXSDFilename, -1, CPLES_XML);
            VSILFILE* fpMEM = VSIFOpenL(osTmpXSDFilename, "wb");
            CPL_IGNORE_RET_VAL(VSIFPrintfL(fpMEM, "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n"));
            CPL_IGNORE_RET_VAL(VSIFPrintfL(fpMEM, "   <xs:import namespace=\"%s\" schemaLocation=\"%s\"/>\n", pszWFSSchemaNamespace, pszWFSSchemaLocation));
            CPL_IGNORE_RET_VAL(VSIFPrintfL(fpMEM, "   <xs:import namespace=\"ignored\" schemaLocation=\"%s\"/>\n", pszEscapedXSDFilename));
            if (pszGMLSchemaLocation)
                CPL_IGNORE_RET_VAL(VSIFPrintfL(fpMEM, "   <xs:import namespace=\"http://www.opengis.net/gml\" schemaLocation=\"%s\"/>\n", pszGMLSchemaLocation));
            CPL_IGNORE_RET_VAL(VSIFPrintfL(fpMEM, "</xs:schema>\n"));
            CPL_IGNORE_RET_VAL(VSIFCloseL(fpMEM));
            CPLFree(pszEscapedXSDFilename);
        }
    }

    CPLXMLSchemaPtr pSchema = CPLLoadXMLSchema(osTmpXSDFilename.size() ? osTmpXSDFilename.c_str() : pszXSDFilename);
    if (osTmpXSDFilename.size())
        VSIUnlink(osTmpXSDFilename);
    if (pSchema == NULL)
        return FALSE;

    xmlSchemaValidCtxtPtr pSchemaValidCtxt;

    pSchemaValidCtxt = xmlSchemaNewValidCtxt((xmlSchemaPtr)pSchema);

    if (pSchemaValidCtxt == NULL)
    {
        CPLFreeXMLSchema(pSchema);
        return FALSE;
    }

    xmlSchemaSetValidErrors(pSchemaValidCtxt,
                            CPLLibXMLWarningErrorCallback,
                            CPLLibXMLWarningErrorCallback,
                            (void*) pszXMLFilename);

    bool bValid = false;
    if( pszXMLFilename[0] == '<' )
    {
        xmlDocPtr pDoc = xmlParseDoc((const xmlChar *)pszXMLFilename);
        if (pDoc != NULL)
        {
            bValid = xmlSchemaValidateDoc(pSchemaValidCtxt, pDoc) == 0;
        }
        xmlFreeDoc(pDoc);
    }
    else if (!STARTS_WITH(pszXMLFilename, "/vsi"))
    {
        bValid =
            xmlSchemaValidateFile(pSchemaValidCtxt, pszXMLFilename, 0) == 0;
    }
    else
    {
        char* pszXML = CPLLoadContentFromFile(pszXMLFilename);
        if (pszXML != NULL)
        {
            xmlDocPtr pDoc = xmlParseDoc((const xmlChar *)pszXML);
            if (pDoc != NULL)
            {
                bValid = xmlSchemaValidateDoc(pSchemaValidCtxt, pDoc) == 0;
            }
            xmlFreeDoc(pDoc);
        }
        CPLFree(pszXML);
    }
    xmlSchemaFreeValidCtxt(pSchemaValidCtxt);
    CPLFreeXMLSchema(pSchema);

    return bValid;
}
Beispiel #21
0
int
test (const char* base) {
    xmlDocPtr docPtr = NULL;
    char filename[100];
    xmlSchemaPtr wxschemas = NULL;

    Handle2Path = xmlHashCreate(0);

    /* Read the schema. */
    {
        /* There is no visitibility into parserCtxt. */
	xmlSchemaParserCtxtPtr parserCtxt;

        /* parserCtxt->ctxtType is xmlSchemaTypePtr */

        snprintf(filename, 100, "%s.xsd", base);
        printf("\n\n\n----------------------------------------------------------------\n\n\n");
        printf("\n----> Reading schema %s...\n", filename);

	parserCtxt = xmlSchemaNewParserCtxt(filename);
	xmlSchemaSetParserErrors(parserCtxt,
		(xmlSchemaValidityErrorFunc) fprintf,
		(xmlSchemaValidityWarningFunc) fprintf,
		stdout);
	xmlSchemaSetParserAnnotation(parserCtxt, schema_annotation_callback, NULL);
	wxschemas = xmlSchemaParse(parserCtxt);
	if (wxschemas == NULL)
        {
            printf("***** schema parsing failed!\n");
	}
	xmlSchemaFreeParserCtxt(parserCtxt);
        printf("\n<---- Schema read!\n\n");
    }

    /* Read the XML. */
    {
        snprintf(filename, 100, "%s.xml", base);
        if ((docPtr = xmlReadFile(filename, NULL, 0)) == NULL)
        {
            printf("failed to parse \"%s\".\n", filename);
            return -1;
        }
    }

    if (!SKIP) {
        /* There is no visibility into schemaCtxt. */
	xmlSchemaValidCtxtPtr schemaCtxt;
	int ret;

        printf("\n----------------------------------------------------------------\n");
        printf("\n----> Validating document %s...\n", filename);

        /* This sets up the schemaCtxt, including a pointer to wxschemas. */
	schemaCtxt = xmlSchemaNewValidCtxt(wxschemas);
	xmlSchemaSetValidErrors(schemaCtxt,
		(xmlSchemaValidityErrorFunc) fprintf,
		(xmlSchemaValidityWarningFunc) fprintf,
		stdout);
	ret = xmlSchemaValidateDoc(schemaCtxt, docPtr);	/* read me! */
	if (ret == 0)
        {
	    /* printf("%s validates\n", filename); */
	}
        else if (ret > 0)
        {
	    printf("%s fails to validate\n", filename);
	}
        else
        {
	    printf("%s validation generated an internal error\n",
		   filename);
	}
	xmlSchemaFreeValidCtxt(schemaCtxt);
        printf("\n<---- Document validated!\n");

    }

    /* Generate a doc and validate it. */
    {
	xmlDocPtr newDoc = xmlNewDoc(BAD_CAST "1.0");
	{
	    xmlSchemaValidCtxtPtr schemaCtxt;
	    int ret;

	    schemaCtxt = xmlSchemaNewValidCtxt(wxschemas);
	    xmlSchemaSetValidErrors(schemaCtxt,
				    (xmlSchemaValidityErrorFunc) fprintf,
				    (xmlSchemaValidityWarningFunc) fprintf,
				    stdout);
	    xmlSchemaSetGeneratorCallback(schemaCtxt, BAD_CAST "people", NULL, &generation_callback, newDoc);
	    ret = xmlSchemaValidateDoc(schemaCtxt, newDoc);
	    if (ret == 0) {
/* 		xmlDocSetRootElement(newDoc, vctxt->node); */
		dump_doc(newDoc, NULL);
	    } else if (ret > 0)
		printf("%s fails to validate\n", filename);
	    else
		printf("%s validation generated an internal error\n",
		       filename);
	    xmlSchemaFreeValidCtxt(schemaCtxt);
	    printf("\n<---- Schema read!\n\n");
	}

	{
	    xmlSchemaValidCtxtPtr schemaCtxt;
	    int ret;

	    schemaCtxt = xmlSchemaNewValidCtxt(wxschemas);
	    xmlSchemaSetValidErrors(schemaCtxt,
				    (xmlSchemaValidityErrorFunc) fprintf,
				    (xmlSchemaValidityWarningFunc) fprintf,
				    stdout);
	    ret = xmlSchemaValidateDoc(schemaCtxt, newDoc);
	    if (ret == 0)
		;
	    else if (ret > 0)
		printf("%s fails to validate\n", filename);
	    else
		printf("%s validation generated an internal error\n",
		       filename);
	    xmlSchemaFreeValidCtxt(schemaCtxt);
	    printf("\n<---- Schema read!\n\n");
	}

	xmlFreeDoc(newDoc);
    }

#if 0
    /* why can't I just start with doc->children? */
    tree_trunk = xmlDocGetRootElement(docPtr);
#endif

#if 0
    tree_trunk = docPtr->children;

    printf("\n\n\n----------------------------------------------------------------\n\n\n");
    printf("\nWalking doc tree...\n");
    walk_doc_tree(tree_trunk, 0);
    printf("\n");
#endif
    printf("\n\n\n----------------------------------------------------------------\n\n\n");
    printf("\nWalking schema tree...\n");
    walk_schema_tree(wxschemas);
    printf("\n");

    /*****************************************************************/
    /*****************************************************************/
    /*****************************************************************/
    /*****************************************************************/
    /* This will tell me, for example, how to decode sequences. */
    printf("\n\n\n----------------------------------------------------------------\n\n\n");
    xmlSchemaDump(stdout, wxschemas);
    /*****************************************************************/
    /*****************************************************************/
    /*****************************************************************/
    /*****************************************************************/

    xmlFreeDoc(docPtr);

    xmlCleanupParser();

    xmlHashFree(Handle2Path, NULL);

    return 0;
}
/* ************************************************** */
int do_configuration(void) {
    xmlSchemaValidCtxtPtr sv_ctxt = NULL;
    xmlSchemaParserCtxtPtr sp_ctxt = NULL;
    xmlSchemaPtr schema = NULL;
    xmlParserCtxtPtr p_ctxt = NULL;
    xmlDocPtr doc = NULL;
    xmlXPathContextPtr xp_ctx = NULL; 
    xmlXPathObjectPtr simul_xobj = NULL;
    xmlXPathObjectPtr entity_xobj = NULL; 
    xmlXPathObjectPtr environment_xobj = NULL; 
    xmlXPathObjectPtr bundle_xobj = NULL; 
    xmlXPathObjectPtr node_xobj = NULL; 
    xmlNodeSetPtr nodeset;
    xmlpathobj_t xpathobj[] = {{&simul_xobj, (xmlChar *) XML_X_SIMULATION}, 
                               {&entity_xobj, (xmlChar *) XML_X_ENTITY},
                               {&environment_xobj, (xmlChar *) XML_X_ENVIRONMENT},
                               {&bundle_xobj, (xmlChar *) XML_X_BUNDLE},
                               {&node_xobj, (xmlChar *) XML_X_NODE}};
    int ok = 0, i;

    /* Check XML version */
    LIBXML_TEST_VERSION;
        
    /* Initialise and parse schema */
    sp_ctxt = xmlSchemaNewParserCtxt(schemafile);
    if (sp_ctxt == NULL) {
        fprintf(stderr, "config: XML schema parser initialisation failure (do_configuration())\n");
        ok = -1;
        goto cleanup;
    }
    xmlSchemaSetParserErrors(sp_ctxt,
                             (xmlSchemaValidityErrorFunc)   xml_error,
                             (xmlSchemaValidityWarningFunc) xml_warning,
                             NULL);
    
    schema = xmlSchemaParse(sp_ctxt);
    if (schema == NULL) {
        fprintf(stderr, "config: error in schema %s (do_configuration())\n", schemafile);
        ok = -1;
        goto cleanup;
    }
    xmlSchemaSetValidErrors(sv_ctxt,
                            (xmlSchemaValidityErrorFunc)   xml_error,
                            (xmlSchemaValidityWarningFunc) xml_warning,
                            NULL);
    
    sv_ctxt = xmlSchemaNewValidCtxt(schema);
    if (sv_ctxt == NULL) {
        fprintf(stderr, "config: XML schema validator initialisation failure (do_configuration())\n");
        ok = -1;
        goto cleanup;
    }
    
    /* Initialise and parse document */
    p_ctxt = xmlNewParserCtxt();
    if (p_ctxt == NULL) {
        fprintf(stderr, "config: XML parser initialisation failure (do_configuration())\n");
        ok = -1;
        goto cleanup;
    }
    
    doc = xmlCtxtReadFile(p_ctxt, configfile, NULL, XML_PARSE_NONET | XML_PARSE_NOBLANKS | XML_PARSE_NSCLEAN);
    if (doc == NULL) {
        fprintf(stderr, "config: failed to parse %s (do_configuration())\n", configfile);
        ok = -1;
        goto cleanup;
    }

    /* Validate document */
    if (xmlSchemaValidateDoc(sv_ctxt, doc)) {
        fprintf(stderr, "config: error in configuration file %s (do_configuration())\n", configfile);
        ok = -1;
        goto cleanup;
    }
    
    /* Create xpath context */
    xp_ctx = xmlXPathNewContext(doc);
    if (xp_ctx == NULL) {
        fprintf(stderr, "config: XPath initialisation failure (do_configuration())\n");
        ok = -1;
        goto cleanup;
    }
    xmlXPathRegisterNs(xp_ctx, (xmlChar *) XML_NS_ID, (xmlChar *) XML_NS_URL); 
    
    
    /* Get xpath obj */
    for (i = 0 ; i < (int) (sizeof(xpathobj) / sizeof(xpathobj[0])); i++) {
        *xpathobj[i].ptr = xmlXPathEvalExpression(xpathobj[i].expr, xp_ctx);
        if (*xpathobj[i].ptr == NULL) {
            fprintf(stderr, "config: unable to evaluate xpath \"%s\" (do_configuration())\n", xpathobj[i].expr);
            ok = -1;
            goto cleanup;
            
        }
    }

    /***************/
    /* Counting... */
    /***************/
    nodeset = entity_xobj->nodesetval;
    if ((entities.size = (nodeset) ? nodeset->nodeNr : 0) == 0) {
        fprintf(stderr, "config: no entity defined (do_configuration())\n");
        ok = -1; 
        goto cleanup;
    }
    fprintf(stderr, "\nFound %d entities...\n", entities.size);
    nodeset = environment_xobj->nodesetval;
    if (((nodeset) ? nodeset->nodeNr : 0) == 0) {
        fprintf(stderr, "config: no environment defined (do_configuration())\n");
        ok = -1; 
        goto cleanup;
    }
    fprintf(stderr, "Found 1 environment...\n");
    nodeset = bundle_xobj->nodesetval;
    if ((bundles.size = (nodeset) ? nodeset->nodeNr : 0) == 0) {
        fprintf(stderr, "config: no bundle defined (do_configuration())\n");
        ok = -1; 
        goto cleanup;
    }
    fprintf(stderr, "Found %d bundles...\n", bundles.size);
    

    if ((dflt_params = das_create()) == NULL) {
        ok = -1; 
        goto cleanup;
    }

    /**************/
    /* Simulation */
    /**************/
    if (parse_simulation(simul_xobj->nodesetval)) {
        ok = -1;
        goto cleanup;
    }
                                                          
    /**********/
    /* Entity */
    /**********/
    /* initialize library paths */
    config_set_usr_modulesdir();
    user_path_list = g_strsplit(user_modulesdir, ":", 0); /* TOCLEAN */
    sys_path_list = g_strsplit(sys_modulesdir, ":", 0); /* TOCLEAN */

    /* parse */
    if (parse_entities(entity_xobj->nodesetval)) {
        ok = -1;
        goto cleanup;
    }

    /**************/
    /* Measure    */
    /**************/
    if (parse_measure()) {
        ok = -1;
        goto cleanup;
    }

    /***************/
    /* Environment */
    /***************/
    if (parse_environment(environment_xobj->nodesetval)) {
        ok = -1;
        goto cleanup;
    }
    
    /***************/
    /* Bundle      */
    /***************/
    if (parse_bundles(bundle_xobj->nodesetval)) {
        ok = -1;
        goto cleanup;
    }

    /***************/
    /* Nodes      */
    /***************/
    if (parse_nodes(node_xobj->nodesetval)) {
        ok = -1;
        goto cleanup;
    }
 
    /* edit by Quentin Lampin <*****@*****.**> */
    gchar **path = NULL;
    for (path = user_path_list ; *path ; path++) {
        g_free(*path);
    }
    path = NULL;
    for (path = sys_path_list  ; *path ; path++) {
        g_free(*path);
    }
    /* end of edition */

 cleanup:
    clean_params();
    
    for (i = 0 ; i < (int) (sizeof(xpathobj) / sizeof(xpathobj[0])); i++) {
        xmlXPathFreeObject(*xpathobj[i].ptr);
    }

    if (xp_ctx) {
        xmlXPathFreeContext(xp_ctx);
    }

    if (sp_ctxt) {
        xmlSchemaFreeParserCtxt(sp_ctxt);		
    }

    if (schema) {
        xmlSchemaFree(schema);
    }

    if (sv_ctxt) {
        xmlSchemaFreeValidCtxt(sv_ctxt);
    }

    if (doc) {
        xmlFreeDoc(doc);
    }

    if (p_ctxt) {
        xmlFreeParserCtxt(p_ctxt);
    }

    xmlCleanupParser();
    return ok;
}