示例#1
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;
	}
}
bool PluginXmlOptions::validateXml(xmlDocPtr doc, const char *schemaFile)
{
	char *pluginDir = ADM_getPluginPath();
	char schemaPath[strlen(pluginDir) + strlen(PLUGIN_SCHEMA_DIR) + 1 + strlen(schemaFile) + 1];
	bool success = false;

	strcpy(schemaPath, pluginDir);
	strcat(schemaPath, PLUGIN_SCHEMA_DIR);
	strcat(schemaPath, "/");
	strcat(schemaPath, schemaFile);
	delete [] pluginDir;

	xmlSchemaParserCtxtPtr xmlSchemaParserCtxt = xmlSchemaNewParserCtxt(schemaPath);
	xmlSchemaPtr xmlSchema = xmlSchemaParse(xmlSchemaParserCtxt);

 	xmlSchemaFreeParserCtxt(xmlSchemaParserCtxt);

 	xmlSchemaValidCtxtPtr xmlSchemaValidCtxt = xmlSchemaNewValidCtxt(xmlSchema);

 	if (xmlSchemaValidCtxt)
	{
 		success = !xmlSchemaValidateDoc(xmlSchemaValidCtxt, doc);
	 	xmlSchemaFree(xmlSchema);
		xmlSchemaFreeValidCtxt(xmlSchemaValidCtxt);
 	}
	else
 		xmlSchemaFree(xmlSchema);

	return success;
}
/**
 * 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;
}
示例#4
0
void MainWindow::on_actionLoadSchema_triggered() {
  FreeXMLSchema();
  ui_->actionCheckSchema->setEnabled(false);
  QString file_name = QFileDialog::getOpenFileName(this,
                                                   tr("Выберите XML-схему"),
                                                   "..",
                                                   tr("XSD-файлы (*.xsd)"));
  //file_name.push_front("file://");
  xmlSchemaParserCtxtPtr schema_parser = xmlSchemaNewParserCtxt(file_name.toUtf8().data());
  if (0 == schema_parser)
    return;

  xmlSchemaPtr schema = xmlSchemaParse(schema_parser);
  if (0 == schema) {
    xmlSchemaFreeParserCtxt(schema_parser);
    schema_parser = 0;
    return;
  }

  schema_valid_ctxt_ = xmlSchemaNewValidCtxt(schema);
  if (0 == schema_valid_ctxt_) {
    xmlSchemaFreeParserCtxt(schema_parser);
    schema_parser = 0;
    xmlSchemaFree(schema);
    schema = 0;
    return;
  }

  ui_->actionCheckSchema->setEnabled(true);
}
示例#5
0
文件: schema.c 项目: r6144/wine
static cache_entry* cache_entry_from_url(char const* url)
{
    cache_entry* entry = heap_alloc(sizeof(cache_entry));
    xmlSchemaParserCtxtPtr spctx = xmlSchemaNewParserCtxt(url);
    entry->type = SCHEMA_TYPE_XSD;
    entry->ref = 0;
    if (spctx)
    {
        if((entry->schema = xmlSchemaParse(spctx)))
        {
            xmldoc_init(entry->schema->doc, &CLSID_DOMDocument40);
            entry->doc = entry->schema->doc;
            xmldoc_add_ref(entry->doc);
        }
        else
        {
            heap_free(entry);
            entry = NULL;
        }
        xmlSchemaFreeParserCtxt(spctx);
    }
    else
    {
        FIXME("schema for nsURI %s not found\n", wine_dbgstr_a(url));
        heap_free(entry);
        entry = NULL;
    }
    return entry;
}
示例#6
0
osync_bool osync_xml_validate_document(xmlDocPtr doc, char *schemafilepath)
{
	int rc = 0;
	xmlSchemaParserCtxtPtr xmlSchemaParserCtxt = NULL;
	xmlSchemaPtr xmlSchema = NULL;
	xmlSchemaValidCtxtPtr xmlSchemaValidCtxt = NULL;

	osync_assert(doc);
	osync_assert(schemafilepath);
	
	xmlSchemaParserCtxt = xmlSchemaNewParserCtxt(schemafilepath);
	xmlSchema = xmlSchemaParse(xmlSchemaParserCtxt);
	xmlSchemaFreeParserCtxt(xmlSchemaParserCtxt);

	xmlSchemaValidCtxt = xmlSchemaNewValidCtxt(xmlSchema);
	if (xmlSchemaValidCtxt == NULL) {
		xmlSchemaFree(xmlSchema);
		rc = 1;
	}else{
		/* Validate the document */
		rc = xmlSchemaValidateDoc(xmlSchemaValidCtxt, doc);
		xmlSchemaFree(xmlSchema);
		xmlSchemaFreeValidCtxt(xmlSchemaValidCtxt);
	}

	if(rc != 0)
		return FALSE;
	return TRUE;
}
示例#7
0
/*
 * Valid an xml string against an XML schema
 * Inpired from: http://xml.developpez.com/sources/?page=validation#validate_XSD_CppCLI_2
 * taken from tinyows.org
 */
int msOWSSchemaValidation(const char* xml_schema, const char* xml)
{
  xmlSchemaPtr schema;
  xmlSchemaParserCtxtPtr ctxt;
  xmlSchemaValidCtxtPtr validctxt;
  int ret;
  xmlDocPtr doc;

  if (!xml_schema || !xml)
    return MS_FAILURE;

  xmlInitParser();
  schema = NULL;
  ret = -1;

  /* Open XML Schema File */
  ctxt = xmlSchemaNewParserCtxt(xml_schema);
  /*
  else ctxt = xmlSchemaNewMemParserCtxt(xml_schema);
  */
  /*
  xmlSchemaSetParserErrors(ctxt,
                           (xmlSchemaValidityErrorFunc) libxml2_callback,
                           (xmlSchemaValidityWarningFunc) libxml2_callback, stderr);
  */

  schema = xmlSchemaParse(ctxt);
  xmlSchemaFreeParserCtxt(ctxt);

  /* If XML Schema hasn't been rightly loaded */
  if (schema == NULL) {
    xmlSchemaCleanupTypes();
    xmlMemoryDump();
    xmlCleanupParser();
    return ret;
  }

  doc = xmlParseDoc((xmlChar *)xml);

  if (doc != NULL) {
    /* Loading XML Schema content */
    validctxt = xmlSchemaNewValidCtxt(schema);
    /*
    xmlSchemaSetValidErrors(validctxt,
                            (xmlSchemaValidityErrorFunc) libxml2_callback,
                            (xmlSchemaValidityWarningFunc) libxml2_callback, stderr);
    */
    /* validation */
    ret = xmlSchemaValidateDoc(validctxt, doc);
    xmlSchemaFreeValidCtxt(validctxt);
  }

  xmlSchemaFree(schema);
  xmlFreeDoc(doc);
  xmlCleanupParser();

  return ret;
}
示例#8
0
 void schema::load_from_file(const std::string& file_name)
 {
     free_();
     xmlSchemaParserCtxt* ctxt = xmlSchemaNewParserCtxt(file_name.c_str());
     if (ctxt != 0)
     {
         raw_ = xmlSchemaParse(ctxt);
         xmlSchemaFreeParserCtxt(ctxt);
     }
     if (raw_ == 0)
     {
         std::string what = "failed to load schema from file " + file_name;
         throw dom_error(what);
     }
 }
示例#9
0
文件: CMRXmlDoc.cpp 项目: svalat/CMR
/*******************  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.");
}
示例#10
0
文件: xml.cpp 项目: treiche/db_agg
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");
        }
    }
}
示例#11
0
/* validate manifest file */
int ermXmlValidateManifest(erManifest *pCtx)
{
    int  retVal = RET_ERR;

    xmlSchemaParserCtxtPtr  parserCtxtPtr = NULL;
    xmlSchemaValidCtxtPtr   validCtxPtr   = NULL;  
    xmlSchemaPtr            schema        = NULL;

    int result;

    if (NULL == pCtx->pDoc)
    {
        TRACE("pCtx->pDoc pointer is empty!\n");        
        return retVal;
    }

    // get XML schema
    parserCtxtPtr = xmlSchemaNewParserCtxt(MANIFEST_SCHEMA_FILE);
    if (parserCtxtPtr)
    {
        schema = xmlSchemaParse(parserCtxtPtr);
        if (schema)
        {
            validCtxPtr = xmlSchemaNewValidCtxt(schema);
            if (validCtxPtr)
            {
                if (xmlSchemaIsValid(validCtxPtr))
                {
                    // validate XML document
                    result = xmlSchemaValidateDoc(validCtxPtr, pCtx->pDoc);
                    TRACE("ValidateDoc returns [%d] (0 == OK)\n", result);        
                    if (result == 0)
                    {
                        retVal = RET_OK;
                    }
                }
                xmlSchemaFreeValidCtxt(validCtxPtr);
            }
            xmlSchemaFree(schema);
        }
    }
    xmlSchemaFreeParserCtxt(parserCtxtPtr);

    return retVal;
}
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);
}
示例#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);
	}
}
示例#14
0
/**
 * Parse data returned from HTTP metaserver and add it to the list of servers.
 *
 * @param body
 * The data to parse.
 * @param body_size
 * Length of the body.
 */
static void
parse_metaserver_data (const char *body, size_t body_size)
{
    HARD_ASSERT(body != NULL);

    xmlSchemaParserCtxtPtr parser_ctx = NULL;
    xmlSchemaPtr schema = NULL;
    xmlSchemaValidCtxtPtr valid_ctx = NULL;

    xmlDocPtr doc = xmlReadMemory(body, body_size, "noname.xml", NULL, 0);
    if (doc == NULL) {
        LOG(ERROR, "Failed to parse data from metaserver");
        goto out;
    }

    parser_ctx = xmlSchemaNewParserCtxt("schemas/Atrinik-ADS-7.xsd");
    if (parser_ctx == NULL) {
        LOG(ERROR, "Failed to create a schema parser context");
        goto out;
    }

    schema = xmlSchemaParse(parser_ctx);
    if (schema == NULL) {
        LOG(ERROR, "Failed to parse schema file");
        goto out;
    }

    valid_ctx = xmlSchemaNewValidCtxt(schema);
    if (valid_ctx == NULL) {
        LOG(ERROR, "Failed to create a validation context");
        goto out;
    }

    xmlSetStructuredErrorFunc(NULL, NULL);
    xmlSetGenericErrorFunc(NULL, parse_metaserver_data_error);
    xmlThrDefSetStructuredErrorFunc(NULL, NULL);
    xmlThrDefSetGenericErrorFunc(NULL, parse_metaserver_data_error);

    if (xmlSchemaValidateDoc(valid_ctx, doc) != 0) {
        LOG(ERROR, "XML verification failed.");
        goto out;
    }

    xmlNodePtr root = xmlDocGetRootElement(doc);
    if (root == NULL || !XML_STR_EQUAL(root->name, "Servers")) {
        LOG(ERROR, "No servers element found in metaserver XML");
        goto out;
    }

    xmlNodePtr last = NULL;
    for (xmlNodePtr node = root->children; node != NULL; node = node->next) {
        last = node;
    }

    for (xmlNodePtr node = last; node != NULL; node = node->prev) {
        if (!XML_STR_EQUAL(node->name, "Server")) {
            continue;
        }

        parse_metaserver_node(node);
    }

out:
    if (doc != NULL) {
            xmlFreeDoc(doc);
    }

    if (parser_ctx != NULL) {
        xmlSchemaFreeParserCtxt(parser_ctx);
    }

    if (schema != NULL) {
        xmlSchemaFree(schema);
    }

    if (valid_ctx != NULL) {
        xmlSchemaFreeValidCtxt(valid_ctx);
    }
}
示例#15
0
文件: main.c 项目: dprevost/newpso
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;   
}
/* ************************************************** */
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;
}
示例#17
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;
}
示例#18
0
/**
 *  This is the main function for 'validate' option
 */
int
valMain(int argc, char **argv)
{
    int start;
    static valOptions ops;
    static ErrorInfo errorInfo;
    int invalidFound = 0;
    int options = XML_PARSE_DTDLOAD | XML_PARSE_DTDATTR;

    if (argc <= 2) valUsage(argc, argv, EXIT_BAD_ARGS);
    valInitOptions(&ops);
    start = valParseOptions(&ops, argc, argv);
    if (ops.nonet) options |= XML_PARSE_NONET;

    errorInfo.verbose = ops.err;
    xmlSetStructuredErrorFunc(&errorInfo, reportError);
    xmlLineNumbersDefault(1);

    if (ops.dtd)
    {
        /* xmlReader doesn't work with external dtd, have to use SAX
         * interface */
        int i;

        for (i=start; i<argc; i++)
        {
            xmlDocPtr doc;
            int ret;

            ret = 0;
            doc = NULL;

            errorInfo.filename = argv[i];
            doc = xmlReadFile(argv[i], NULL, options);
            if (doc)
            {
                /* TODO: precompile DTD once */                
                ret = valAgainstDtd(&ops, ops.dtd, doc, argv[i]);
                xmlFreeDoc(doc);
            }
            else
            {
                ret = 1; /* Malformed XML or could not open file */
                if ((ops.listGood < 0) && !ops.show_val_res)
                {
                    fprintf(stdout, "%s\n", argv[i]);
                }
            }
            if (ret) invalidFound = 1;     

            if (ops.show_val_res)
            {
                if (ret == 0)
                    fprintf(stdout, "%s - valid\n", argv[i]);
                else
                    fprintf(stdout, "%s - invalid\n", argv[i]);
            }
        }
    }
    else if (ops.schema || ops.relaxng || ops.embed || ops.wellFormed)
    {
        int i;
        xmlTextReaderPtr reader = NULL;

#ifdef LIBXML_SCHEMAS_ENABLED
        xmlSchemaPtr schema = NULL;
        xmlSchemaParserCtxtPtr schemaParserCtxt = NULL;
        xmlSchemaValidCtxtPtr schemaCtxt = NULL;

        xmlRelaxNGPtr relaxng = NULL;
        xmlRelaxNGParserCtxtPtr relaxngParserCtxt = NULL;
        /* there is no xmlTextReaderRelaxNGValidateCtxt() !?  */

        /* TODO: Do not print debug stuff */
        if (ops.schema)
        {
            schemaParserCtxt = xmlSchemaNewParserCtxt(ops.schema);
            if (!schemaParserCtxt)
            {
                invalidFound = 2;
                goto schemaCleanup;
            }
            errorInfo.filename = ops.schema;
            schema = xmlSchemaParse(schemaParserCtxt);
            if (!schema)
            {
                invalidFound = 2;
                goto schemaCleanup;
            }

            xmlSchemaFreeParserCtxt(schemaParserCtxt);
            schemaCtxt = xmlSchemaNewValidCtxt(schema);
            if (!schemaCtxt)
            {
                invalidFound = 2;
                goto schemaCleanup;
            }

        }
        else if (ops.relaxng)
        {
            relaxngParserCtxt = xmlRelaxNGNewParserCtxt(ops.relaxng);
            if (!relaxngParserCtxt)
            {
                invalidFound = 2;
                goto schemaCleanup;
            }

            errorInfo.filename = ops.relaxng;
            relaxng = xmlRelaxNGParse(relaxngParserCtxt);
            if (!relaxng)
            {
                invalidFound = 2;
                goto schemaCleanup;
            }

        }
#endif  /* LIBXML_SCHEMAS_ENABLED */

        for (i=start; i<argc; i++)
        {
            int ret = 0;
            if (ops.embed) options |= XML_PARSE_DTDVALID;

            if (!reader)
            {
                reader = xmlReaderForFile(argv[i], NULL, options);
            }
            else
            {
                ret = xmlReaderNewFile(reader, argv[i], NULL, options);
            }

            errorInfo.xmlReader = reader;
            errorInfo.filename = argv[i];

            if (reader && ret == 0)
            {
#ifdef LIBXML_SCHEMAS_ENABLED
                if (schemaCtxt)
                {
                    ret = xmlTextReaderSchemaValidateCtxt(reader,
                        schemaCtxt, 0);
                }
                else if (relaxng)
                {
                    ret = xmlTextReaderRelaxNGSetSchema(reader,
                        relaxng);
                }
#endif  /* LIBXML_SCHEMAS_ENABLED */

                if (ret == 0)
                {
                    do
                    {
                        ret = xmlTextReaderRead(reader);
                    } while (ret == 1);
                    if (ret != -1 && (schema || relaxng || ops.embed))
                        ret = !xmlTextReaderIsValid(reader);
                }
            }
            else
            {
                if (ops.err)
                    fprintf(stderr, "couldn't read file '%s'\n", errorInfo.filename);
                ret = 1; /* could not open file */
            }
            if (ret) invalidFound = 1;

            if (!ops.show_val_res)
            {
                if ((ops.listGood > 0) && (ret == 0))
                    fprintf(stdout, "%s\n", argv[i]);
                if ((ops.listGood < 0) && (ret != 0))
                    fprintf(stdout, "%s\n", argv[i]);
            }
            else
            {
                if (ret == 0)
                    fprintf(stdout, "%s - valid\n", argv[i]);
                else
                    fprintf(stdout, "%s - invalid\n", argv[i]);
            }
        }
        errorInfo.xmlReader = NULL;
        xmlFreeTextReader(reader);

#ifdef LIBXML_SCHEMAS_ENABLED
    schemaCleanup:
        xmlSchemaFreeValidCtxt(schemaCtxt);
        xmlRelaxNGFree(relaxng);
        xmlSchemaFree(schema);
        xmlRelaxNGCleanupTypes();
        xmlSchemaCleanupTypes();
#endif  /* LIBXML_SCHEMAS_ENABLED */
    }

    xmlCleanupParser();
    return invalidFound;
}
示例#19
0
static inline int oscap_validate_xml(struct oscap_source *source, const char *schemafile, xml_reporter reporter, void *arg)
{
	int result = -1;
	xmlSchemaParserCtxtPtr parser_ctxt = NULL;
	xmlSchemaPtr schema = NULL;
	xmlSchemaValidCtxtPtr ctxt = NULL;
	xmlDocPtr doc = NULL;

	struct ctxt context = { reporter, arg, (void*) oscap_source_readable_origin(source)};

	if (schemafile == NULL) {
		oscap_seterr(OSCAP_EFAMILY_OSCAP, "'schemafile' == NULL");
		return -1;
	}

	char * schemapath = oscap_sprintf("%s%s%s", oscap_path_to_schemas(), "/", schemafile);
	if (access(schemapath, R_OK)) {
		oscap_seterr(OSCAP_EFAMILY_OSCAP, "Schema file '%s' not found in path '%s' when trying to validate '%s'",
				schemafile, oscap_path_to_schemas(), oscap_source_readable_origin(source));
		goto cleanup;
	}

	parser_ctxt = xmlSchemaNewParserCtxt(schemapath);
	if (parser_ctxt == NULL) {
		oscap_seterr(OSCAP_EFAMILY_XML, "Could not create parser context for validation");
		goto cleanup;
	}

	xmlSchemaSetParserStructuredErrors(parser_ctxt, oscap_xml_validity_handler, &context);

	schema = xmlSchemaParse(parser_ctxt);
	if (schema == NULL) {
		oscap_seterr(OSCAP_EFAMILY_XML, "Could not parse XML schema");
		goto cleanup;
	}

	ctxt = xmlSchemaNewValidCtxt(schema);
	if (ctxt == NULL) {
		oscap_seterr(OSCAP_EFAMILY_XML, "Could not create validation context");
		goto cleanup;
	}

	xmlSchemaSetValidStructuredErrors(ctxt, oscap_xml_validity_handler, &context);

	doc = oscap_source_get_xmlDoc(source);
	if (!doc)
		goto cleanup;

	result = xmlSchemaValidateDoc(ctxt, doc);

	/*
	 * xmlSchemaValidateFile() returns "-1" if document is not well formed
	 * thefore we ignore libxml internal errors here and map return code to
	 * either pass or fail.
	 */
	if (result != 0)
		result = 1;
	/* This would be nicer
	 * if (result ==  -1)
	 *	oscap_setxmlerr(xmlGetLastError());
	*/

cleanup:
	if (ctxt)
		xmlSchemaFreeValidCtxt(ctxt);
	if (schema)
		xmlSchemaFree(schema);
	if (parser_ctxt)
		xmlSchemaFreeParserCtxt(parser_ctxt);
	oscap_free(schemapath);

	return result;
}
示例#20
0

/*
 * call-seq:
 *    XML::Schema.initialize(schema_uri) -> schema
 *
 * Create a new schema from the specified URI.
 */
static VALUE rxml_schema_init_from_uri(VALUE class, VALUE uri)
{
  xmlSchemaParserCtxtPtr xparser;
  xmlSchemaPtr xschema;

  Check_Type(uri, T_STRING);

  xparser = xmlSchemaNewParserCtxt(StringValuePtr(uri));
  xschema = xmlSchemaParse(xparser);
  xmlSchemaFreeParserCtxt(xparser);

  return Data_Wrap_Struct(cXMLSchema, NULL, rxml_schema_free, xschema);
}

/*
 * call-seq:
 *    XML::Schema.document(document) -> schema
 *
 * Create a new schema from the specified document.
 */
static VALUE rxml_schema_init_from_document(VALUE class, VALUE document)
{
  xmlDocPtr xdoc;
示例#21
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);

}