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

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

    return ret;
}
Esempio n. 2
0
/**
 * oseacomm_xml_validate_message:
 * @message: 
 * 
 * Validates the message against the main dtd of LibOseaComm.
 * 
 * Return value: TRUE if the validation was succesful, FALSE if not.
 **/
gboolean oseacomm_xml_validate_message (OseaCommXmlMessage * message)
{

	xmlDtdPtr dtd;
	gchar *dtd_file_name = NULL;
	xmlValidCtxtPtr context;
	xmlDocPtr doc;

	g_return_val_if_fail (message, FALSE);

	dtd_file_name = g_build_filename (PACKAGE_DTD_DIR, "liboseacomm", "oseacomm.dtd", NULL );
	g_log (LOG_DOMAIN, G_LOG_LEVEL_DEBUG, "Using dtd file: %s", dtd_file_name);
	if (!dtd_file_name) {
		g_log (LOG_DOMAIN, G_LOG_LEVEL_CRITICAL, "Cannot find the dtd file to validate messages");
		g_free (dtd_file_name);
		return FALSE;
	}

	dtd = xmlParseDTD (NULL, dtd_file_name);

	g_free (dtd_file_name);

	if (!dtd) {
		g_log (LOG_DOMAIN, G_LOG_LEVEL_CRITICAL, "Cannot parse the dtd file");
		return FALSE;
	}

	// dtd correct

	doc = xmlParseMemory ((xmlChar *) message->content, (message->len * sizeof (char)));
	if (!doc) {
		g_log (LOG_DOMAIN, G_LOG_LEVEL_CRITICAL, "Cannot parse xml message to validate it");
		xmlFreeDtd (dtd);
		return FALSE;
	}

	// doc correct

	context = g_new0 (xmlValidCtxt, 1);

	if (xmlValidateDtd (context, doc, dtd)) {
		// Validation succesful
		xmlFreeDtd (dtd);
		xmlFreeDoc (doc);
		g_free (context);
		return TRUE;
	} 
	
	// Validation failed
	xmlFreeDtd (dtd);
	xmlFreeDoc (doc);
	g_free (context);
	return FALSE;
	

}
Esempio n. 3
0
gboolean
empathy_xml_validate (xmlDoc      *doc,
    const gchar *dtd_filename)
{
  gchar *path;
  xmlChar *escaped;
  xmlValidCtxt  cvp;
  xmlDtd *dtd;
  gboolean ret;

  path = g_build_filename (g_getenv ("EMPATHY_SRCDIR"), "libempathy",
         dtd_filename, NULL);
  if (!g_file_test (path, G_FILE_TEST_EXISTS))
    {
      g_free (path);
      path = g_build_filename (DATADIR, "empathy", dtd_filename, NULL);
    }

  DEBUG ("Loading dtd file %s", path);

  /* The list of valid chars is taken from libxml. */
  escaped = xmlURIEscapeStr ((const xmlChar *) path,
    (const xmlChar *)":@&=+$,/?;");
  g_free (path);

  memset (&cvp, 0, sizeof (cvp));
  dtd = xmlParseDTD (NULL, escaped);
  ret = xmlValidateDtd (&cvp, doc, dtd);

  xmlFree (escaped);
  xmlFreeDtd (dtd);

  return ret;
}
gboolean
tpaw_xml_validate_from_resource (xmlDoc *doc,
    const gchar *dtd_resourcename)
{
  GBytes *resourcecontents;
  gconstpointer resourcedata;
  gsize resourcesize;
  xmlParserInputBufferPtr buffer;
  xmlValidCtxt  cvp;
  xmlDtd *dtd;
  GError *error = NULL;
  gboolean ret;

  DEBUG ("Loading dtd resource %s", dtd_resourcename);

  resourcecontents = g_resources_lookup_data (dtd_resourcename, G_RESOURCE_LOOKUP_FLAGS_NONE, &error);
  if (error != NULL)
    {
      g_warning ("Unable to load dtd resource '%s': %s", dtd_resourcename, error->message);
      g_error_free (error);
      return FALSE;
    }
  resourcedata = g_bytes_get_data (resourcecontents, &resourcesize);
  buffer = xmlParserInputBufferCreateStatic (resourcedata, resourcesize, XML_CHAR_ENCODING_UTF8);

  memset (&cvp, 0, sizeof (cvp));
  dtd = xmlIOParseDTD (NULL, buffer, XML_CHAR_ENCODING_UTF8);
  ret = xmlValidateDtd (&cvp, doc, dtd);

  xmlFreeDtd (dtd);
  g_bytes_unref (resourcecontents);

  return ret;
}
void
ruby_xml_dtd_free(ruby_xml_dtd *rxdtd) {
  if (rxdtd->dtd != NULL) {
    xmlFreeDtd(rxdtd->dtd);
    rxdtd->dtd = NULL;
  }

  free(rxdtd);
}
Esempio n. 6
0
void rxml_dtd_free(xmlDtdPtr xdtd)
{
  /* Set _private to NULL so that we won't reuse the
   same, freed, Ruby wrapper object later.*/
  xdtd->_private = NULL;

  if (xdtd->doc == NULL && xdtd->parent == NULL)
    xmlFreeDtd(xdtd);
}
Esempio n. 7
0
void rxml_dtd_free(xmlDtdPtr xdtd)
{
  /* Clear our private pointer so that we won't reuse the
   same, freed, Ruby wrapper object later.*/
  rxml_unregister_dtd(xdtd);

  if (xdtd->doc == NULL && xdtd->parent == NULL)
    xmlFreeDtd(xdtd);
}
Esempio n. 8
0
bool DTDParser::parse()
{
  QString fileName = QString::null;
  if (!KIO::NetAccess::download(m_dtdURL, fileName))
  {
    KMessageBox::error(0, i18n("<qt>Cannot download the DTD from <b>%1</b>.</qt>").arg( m_dtdURL.prettyURL(0, KURL::StripFileProtocol)));
    return false;
  }
  DTD::dtd_ptr = xmlParseDTD(NULL, xmlCharStrndup(fileName.utf8(), fileName.utf8().length()));
  if( DTD::dtd_ptr == NULL )
  {
     KMessageBox::error(0, i18n("Error while parsing the DTD.\nThe error message is:\n%1").arg("x"));
     return false;
//          xmlGenericError(xmlGenericErrorContext,                          "Could not parse %s\n", argv[1]);
  }
  KDialogBase dlg(0L, 0L, true, i18n("DTD - > DTEP Conversion"), KDialogBase::Ok | KDialogBase::Cancel);
  DTEPCreationDlg w(&dlg);
  dlg.setMainWidget(&w);
  QString name = QString((const char*)DTD::dtd_ptr->name);
  if (name == "none")
    name = QFileInfo(m_dtdURL.fileName()).baseName();
  w.dtdName->setText(name);
  w.nickName->setText(name);
  w.directory->setText(QFileInfo(m_dtdURL.fileName()).baseName());
  w.doctype->setText(QString((const char*)DTD::dtd_ptr->ExternalID));
  w.dtdURL->setText(QString((const char*)DTD::dtd_ptr->SystemID));
  if (!dlg.exec())
      return false;
  m_name = w.dtdName->text();
  m_nickName = w.nickName->text();
  m_doctype = w.doctype->text();
  m_doctype.replace(QRegExp("<!doctype", false), "");
  m_doctype = m_doctype.left(m_doctype.findRev(">"));
  m_dtdURLLine = w.dtdURL->text();
  m_defaultExtension = w.defaultExtension->text();
  m_caseSensitive = w.caseSensitive->isChecked();
  DTD::dirName = m_dtepDir + "/" + w.directory->text();
  KURL u;
  u.setPath(DTD::dirName);
  if (!QExtFileInfo::createDir(DTD::dirName)) {
    QuantaCommon::dirCreationError(0, u);
    return false;
  }
  DTD::dirName.append("/");
  if (DTD::dtd_ptr->elements)
  {
    xmlHashScan((xmlElementTablePtr)DTD::dtd_ptr->elements, (xmlHashScanner)saveElement, 0);
  } else
  {
     KMessageBox::error(0, i18n("No elements were found in the DTD."));
     return false;
  }
  xmlFreeDtd(DTD::dtd_ptr);
  writeDescriptionRC();

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

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

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

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

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

    ret = 0;

exit:

    if (doc) {
    	xmlFreeDoc(doc);
    }
    if (dtd) {
    	xmlFreeDtd(dtd);
    }
    if (cvp) {
    	xmlFreeValidCtxt(cvp);
    }
    return ret;
}
Esempio n. 10
0
static bool
is_dtd_valid(FILE *input, const char *filename)
{
	bool rc = true;
#if HAVE_LIBXML
	xmlParserCtxtPtr ctx = NULL;
	xmlDocPtr doc = NULL;
	xmlDtdPtr dtd = NULL;
	xmlValidCtxtPtr	dtdctx;
	xmlParserInputBufferPtr	buffer;
	int fd = fileno(input);

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

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

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

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

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

	if (lseek(fd, 0, SEEK_SET) != 0) {
		fprintf(stderr, "Failed to reset fd, output would be garbage.\n");
		abort();
	}
#endif
	return rc;
}
Esempio n. 11
0
/* frees the node if nessecary. this method is aware, that libxml2
 * has several diffrent nodetypes.
 */
void
PmmFreeNode( xmlNodePtr node )
{
    switch( node->type ) {
    case XML_DOCUMENT_NODE:
    case XML_HTML_DOCUMENT_NODE:
        xs_warn("PmmFreeNode: XML_DOCUMENT_NODE\n");
        xmlFreeDoc( (xmlDocPtr) node );
        break;
    case XML_ATTRIBUTE_NODE:
        xs_warn("PmmFreeNode: XML_ATTRIBUTE_NODE\n");
        if ( node->parent == NULL ) {
            xs_warn( "PmmFreeNode:   free node!\n");
            node->ns = NULL;
            xmlFreeProp( (xmlAttrPtr) node );
        }
        break;
    case XML_DTD_NODE:
        if ( node->doc != NULL ) {
            if ( node->doc->extSubset != (xmlDtdPtr)node
                    && node->doc->intSubset != (xmlDtdPtr)node ) {
                xs_warn( "PmmFreeNode: XML_DTD_NODE\n");
                node->doc = NULL;
                xmlFreeDtd( (xmlDtdPtr)node );
            }
        } else {
            xs_warn( "PmmFreeNode: XML_DTD_NODE (no doc)\n");
            xmlFreeDtd( (xmlDtdPtr)node );
        }
        break;
    case XML_DOCUMENT_FRAG_NODE:
        xs_warn("PmmFreeNode: XML_DOCUMENT_FRAG_NODE\n");
    default:
        xs_warn( "PmmFreeNode: normal node\n" );
        xmlFreeNode( node);
        break;
    }
}
Esempio n. 12
0
static gboolean
xml_validate (xmlDoc *doc, const gchar *dtd_path)
{
    xmlValidCtxt  cvp;
    xmlDtd       *dtd;
    gboolean      ret_val;

    memset (&cvp, 0, sizeof (cvp));
    dtd = xmlParseDTD (NULL, dtd_path);
    ret_val = xmlValidateDtd (&cvp, doc, dtd);
    xmlFreeDtd (dtd);

    return ret_val;
}
Esempio n. 13
0
int xml_validate_dtd(struct xml_node_ctx *ctx, xml_node_t *node,
		     const char *dtd_fname, char **ret_err)
{
	xmlDocPtr doc;
	xmlNodePtr n;
	xmlValidCtxt vctx;
	xmlDtdPtr dtd;
	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));

	dtd = xmlParseDTD(NULL, (const xmlChar *) dtd_fname);
	if (dtd == NULL) {
		xmlFreeDoc(doc);
		return -1;
	}

	os_memset(&vctx, 0, sizeof(vctx));
	vctx.userData = &errors;
	vctx.error = add_str;
	vctx.warning = add_str;
	ret = xmlValidateDtd(&vctx, doc, dtd);
	xmlFreeDoc(doc);
	xmlFreeDtd(dtd);

	if (ret == 1) {
		os_free(errors.buf);
		return 0;
	} else {
		if (ret_err)
			*ret_err = errors.buf;
		else
			os_free(errors.buf);
		return -1;
	}
}
int oph_hier_validate(oph_hier_document * document)
{
	int result;
	if ((result = oph_hier_basic_control(document)) != OPH_HIER_OK)
		return result;
	xmlDtdPtr dtd = xmlParseDTD(NULL, (xmlChar *) OPH_FRAMEWORK_HIERARCHY_DTD_PATH);
	if (!dtd) {
		pmesg(LOG_ERROR, __FILE__, __LINE__, "DTD file '%s' not found\n", OPH_FRAMEWORK_HIERARCHY_DTD_PATH);
		return OPH_HIER_IO_ERR;
	}
	xmlValidCtxtPtr cvp = xmlNewValidCtxt();
	if (!cvp) {
		xmlFreeDtd(dtd);
		pmesg(LOG_ERROR, __FILE__, __LINE__, "Context is not gettable\n");
		return OPH_HIER_SYSTEM_ERR;
	}
	if (!xmlValidateDtd(cvp, document->document, dtd)) {
		pmesg(LOG_WARNING, __FILE__, __LINE__, "File is not valid\n");
		result = OPH_HIER_XML_ERR;
	}
	xmlFreeValidCtxt(cvp);
	xmlFreeDtd(dtd);
	return result;
}
Esempio n. 15
0
Bool CXMLDocument::ValidateDTD(char *data, unsigned long tlength)
{
	if (!isinited()) return False;
	xmlParserInputBufferPtr dtdInputBufferPtr; 
	xmlDtdPtr dtd; 
	dtdInputBufferPtr = xmlParserInputBufferCreateMem(data, tlength, XML_CHAR_ENCODING_UTF8); 
	dtd = xmlIOParseDTD(NULL, dtdInputBufferPtr, XML_CHAR_ENCODING_UTF8); 
	if (!dtd) return False;
	xmlValidCtxt ctxt;
	ctxt.doc = doc;
	ctxt.userData = NULL;
	//point to dtd error handling function
	ctxt.error = errorCallback; 
	ctxt.warning = warningCallback;
	Bool isvalid = xmlValidateDtd(&ctxt,doc,dtd);
	xmlFreeDtd(dtd);
	return isvalid;
}
Esempio n. 16
0
/*******************  FUNCTION  *********************/
void CMRXmlDoc::validateWithDTD ( const string& dtdFile )
{
	/* vars */
	bool status = true;
	xmlDtdPtr dtd;
	xmlValidCtxtPtr vctxt;

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

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


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

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

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

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

	if (!status)
		throw LatexException("XML file is invalid.");
}
Esempio n. 17
0
int main(int argc, const char *argv[]) {
  int status = 0;
  xmlParserCtxtPtr parser_context = 0;
  xmlDocPtr doc = 0;
  xmlDtdPtr dtd = 0;
  xmlValidCtxtPtr valid_context = 0;

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

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

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

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

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

  return status;
}
Esempio n. 18
0
XMLParser::~XMLParser()
{
    if (m_Schema) {
        xmlSchemaFree(m_Schema);
    }
    if (m_SchemaParserCtxt) {
        xmlSchemaFreeParserCtxt(m_SchemaParserCtxt);
    }
    if (m_SchemaValidCtxt) {
        xmlSchemaFreeValidCtxt(m_SchemaValidCtxt);
    }
    if (m_DTD) {
        xmlFreeDtd(m_DTD);
    }
    if (m_DTDValidCtxt) {
        xmlFreeValidCtxt(m_DTDValidCtxt);
    }
    if (m_Doc) {
        xmlFreeDoc(m_Doc);
    }
    xmlSetGenericErrorFunc(0, 0);
}
Esempio n. 19
0
void TrackerConfig::loadConfigFile(const string& sFilename)
{
    // TODO: There is duplicated code here and in Player::loadFile which belongs
    // in a lower-level xml handling class.
    registerDTDEntityLoader("trackerconfig.dtd", g_pTrackerConfigDTD);
    xmlDtdPtr dtd;
    string sDTDFName = "trackerconfig.dtd";
    dtd = xmlParseDTD(NULL, (const xmlChar*) sDTDFName.c_str());
    if (!dtd) {
        AVG_LOG_WARNING("DTD not found at " << sDTDFName 
                << ". Not validating trackerconfig files.");
    }

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

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

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

    AVG_TRACE(Logger::category::CONFIG, Logger::severity::INFO,
            "Reading Tracker config file from " << sFilename);
}
Esempio n. 20
0
/* Parse the configuration file. */
int sechk_lib_parse_xml_file(const char *filename, sechk_lib_t * lib)
{
	xmlTextReaderPtr reader = NULL;
	xmlDtdPtr dtd = NULL;
	xmlDocPtr xml = NULL;
	xmlValidCtxtPtr ctxt = NULL;
	int tmp, ret = 0;
	char *dtd_path = NULL;

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

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

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

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

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

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

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

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

      exit_err:
	xmlCleanupParser();
	if (reader)
		xmlFreeTextReader(reader);
	if (ret)
		errno = ret;
	return -1;
}
Esempio n. 21
0
int LireDictionnaireCMC(char *fichierXML)
{
int i, j, k;
 
 char buf[BUFSIZ];
 char *home;
 char dtdfile[256];
 int done;
 int inlen, outlen;
 unsigned char *inbuffer,*outbuffer;
 
 extern int xmlDoValidityCheckingDefaultValue;


xmlDocPtr    doc;
xmlNsPtr     ns;
xmlNodePtr   cur;
MetvarPtr    Metvar;
xmlDtdPtr    dtd ;
xmlValidCtxt ctxt;
FILE *fh;

LIBXML_TEST_VERSION xmlKeepBlanksDefault(0);

/*
 * build an XML tree from the file;
 */
doc = xmlParseFile(fichierXML);
if (doc == NULL) return(1);

/* -----------------------------------------  */
/*  Check the document is of the right kind   */
/* ------------------------------------------ */

 inbuffer=(unsigned char *) malloc(256*sizeof(unsigned char)); 
 outbuffer=(unsigned char *) malloc(256*sizeof(unsigned char)); 

cur = xmlDocGetRootElement(doc);
if (cur == NULL ) 
{
 fprintf(stderr,"empty document\n");
 xmlFreeDoc(doc);
 return(1);
}
 
 printf("root:%s\n",cur->name);
 
 /* ---------------------- */
 /*  Parse the DTD!   */
 /* ---------------------- */
 
 home = (char *) getenv ("AFSISIO");
 strcpy(dtdfile, home);
 strcat(dtdfile, "/datafiles/constants/dict.dtd");
 dtd = xmlParseDTD(NULL,dtdfile); 
 if (! dtd ) 
   { 
   printf("Error Parsing DTD\n");
   return (1);
   }
 else
   {
   printf ("dtd->name:%s\n",dtd->name);  
   }

 /* ----------------------------------------------------------- */
 /*   Set up xmlValidCtxt for error reporting when validating   */
 /* ----------------------------------------------------------- */
 
 ctxt.userData = stderr; 
 ctxt.error    = (xmlValidityErrorFunc) fprintf;   /* register error function */ 
 ctxt.warning  = (xmlValidityWarningFunc) fprintf; /* register warning function */ 
 
 
 if ( xmlValidateDtd(&ctxt,doc,dtd) )
   {
   printf("=========Validation Ok!============\n");
   }
 else 
   {
   printf("========Validation error!===========\n");
   return (1);
   }
 
 
 /*
  * Now, walk the tree.
  */
 
 
 cur = cur->children; 
 while (cur != NULL) 
   {
   Metvar = parseMetvar(doc, ns, cur);  	   
   cur = cur->next;
   }

 for (i=0; i < nbChampsDict; i++)
   {
   printf("*--------------------------------------------------------------\n");
   strcpy(inbuffer, infoChamps[i].identifVar[FRANCAIS]);
   inlen = xmlUTF8Strsize(inbuffer, 256);
   outlen=256;
   UTF8Toisolat1(outbuffer,&outlen,inbuffer ,&inlen);
   outbuffer[outlen]='\0';
   strcpy(infoChamps[i].identifVar[FRANCAIS], outbuffer);
   printf("Champ %03d de %03d\n", i, nbChampsDict);
   printf("nomvar: %s\n", infoChamps[i].nomVar);
   printf("\tdesc fr:%s\n", infoChamps[i].identifVar[FRANCAIS]);
   printf("\tdesc en:%s\n", infoChamps[i].identifVar[ENGLISH]);
   printf("\tunites:%s\n",  infoChamps[i].unitesVar);
   
   }
 
 xmlFreeDtd(dtd);
 xmlFreeDoc(doc);
 return(0);
 
}
Esempio n. 22
0
/**
 *  Validate XML document against DTD
 */
int
valAgainstDtd(valOptionsPtr ops, char* dtdvalid, xmlDocPtr doc, char* filename)
{
    int result = 0;

    if (dtdvalid != NULL)
    {
        xmlDtdPtr dtd;

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

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

    return result;
}
Esempio n. 23
0
int 
DAPI_close () {
	xmlFreeDtd (cannedDocDtd);

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

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

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

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

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

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

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

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

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

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

	xmlFreeDtd(dtd);
	xmlFreeValidCtxt(validctxt);

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