LCOV - code coverage report
Current view: top level - source/ps/XML - RelaxNG.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 75 79 94.9 %
Date: 2026-12-03 01:19:39 Functions: 11 11 100.0 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "RelaxNG.h"
      21             : 
      22             : #include "ps/CLogger.h"
      23             : #include "ps/CStr.h"
      24             : #include "ps/Errors.h"
      25             : #include "ps/Filesystem.h"
      26             : 
      27             : #include <cstddef>
      28             : #include <libxml/parser.h>
      29             : #include <libxml/relaxng.h>
      30             : #include <libxml/xmlerror.h>
      31             : #include <libxml/xmlversion.h>
      32             : #include <map>
      33             : #include <memory>
      34             : #include <mutex>
      35             : #include <type_traits>
      36             : #include <utility>
      37             : 
      38             : /*
      39             :  * libxml2 leaks memory when parsing schemas: https://bugzilla.gnome.org/show_bug.cgi?id=615767
      40             :  * To minimise that problem, keep a global cache of parsed schemas, so we don't
      41             :  * leak an indefinitely large amount of memory when repeatedly restarting the simulation.
      42             :  */
      43             : class RelaxNGSchema;
      44             : static std::map<std::string, std::shared_ptr<RelaxNGSchema>> g_SchemaCache;
      45             : static std::mutex g_SchemaCacheLock;
      46             : 
      47         114 : void ClearSchemaCache()
      48             : {
      49         114 :     std::lock_guard<std::mutex> lock(g_SchemaCacheLock);
      50         114 :     g_SchemaCache.clear();
      51         114 : }
      52             : 
      53          15 : static void relaxNGErrorHandler(void* /*userData*/,
      54             :     std::conditional_t<LIBXML_VERSION >= 21200, const xmlError, xmlError>* error)
      55             : {
      56             :     // Strip a trailing newline
      57          15 :     std::string message = error->message;
      58          15 :     if (message.length() > 0 && message[message.length()-1] == '\n')
      59          15 :         message.erase(message.length()-1);
      60             : 
      61          60 :     LOGERROR("RelaxNGValidator: Validation {}: {}:{}: {}",
      62             :         error->level == XML_ERR_WARNING ? "warning" : "error",
      63             :         error->file, error->line, message.c_str());
      64          15 : }
      65             : 
      66             : class RelaxNGSchema
      67             : {
      68             : public:
      69             :     xmlRelaxNGPtr m_Schema;
      70             : 
      71          49 :     RelaxNGSchema(const std::string& grammar)
      72          49 :     {
      73          49 :         xmlRelaxNGParserCtxtPtr ctxt = xmlRelaxNGNewMemParserCtxt(grammar.c_str(), (int)grammar.size());
      74          49 :         m_Schema = xmlRelaxNGParse(ctxt);
      75          49 :         xmlRelaxNGFreeParserCtxt(ctxt);
      76             : 
      77          49 :         if (m_Schema == NULL)
      78           2 :             LOGERROR("RelaxNGValidator: Failed to compile schema");
      79          49 :     }
      80             : 
      81          49 :     ~RelaxNGSchema()
      82             :     {
      83          49 :         if (m_Schema)
      84          48 :             xmlRelaxNGFree(m_Schema);
      85          49 :     }
      86             : };
      87             : 
      88         181 : RelaxNGValidator::RelaxNGValidator() :
      89         181 :     m_Schema(NULL)
      90             : {
      91         181 : }
      92             : 
      93         479 : RelaxNGValidator::~RelaxNGValidator()
      94             : {
      95         479 : }
      96             : 
      97          56 : bool RelaxNGValidator::LoadGrammar(const std::string& grammar)
      98             : {
      99          56 :     std::shared_ptr<RelaxNGSchema> schema;
     100             : 
     101          56 :     {
     102          56 :         std::lock_guard<std::mutex> lock(g_SchemaCacheLock);
     103          56 :         std::map<std::string, std::shared_ptr<RelaxNGSchema>>::iterator it = g_SchemaCache.find(grammar);
     104          56 :         if (it == g_SchemaCache.end())
     105             :         {
     106          49 :             schema = std::make_shared<RelaxNGSchema>(grammar);
     107          49 :             g_SchemaCache[grammar] = schema;
     108             :         }
     109             :         else
     110             :         {
     111          63 :             schema = it->second;
     112             :         }
     113           0 :     }
     114             : 
     115          56 :     m_Schema = schema->m_Schema;
     116          56 :     if (!m_Schema)
     117             :         return false;
     118             : 
     119          55 :     MD5 hash;
     120          55 :     hash.Update(reinterpret_cast<const std::uint8_t*>(grammar.c_str()), grammar.length());
     121          55 :     m_Hash = hash;
     122             : 
     123          55 :     return true;
     124          56 : }
     125             : 
     126          46 : bool RelaxNGValidator::LoadGrammarFile(const PIVFS& vfs, const VfsPath& grammarPath)
     127             : {
     128          46 :     CVFSFile file;
     129          46 :     if (file.Load(vfs, grammarPath) != PSRETURN_OK)
     130             :         return false;
     131             : 
     132          70 :     return LoadGrammar(file.DecodeUTF8());
     133          46 : }
     134             : 
     135        7506 : bool RelaxNGValidator::Validate(const std::string& filename, const std::string& document) const
     136             : {
     137        7506 :     std::string docutf8 = "<?xml version='1.0' encoding='utf-8'?>" + document;
     138             : 
     139        7506 :     return ValidateEncoded(filename, docutf8);
     140        7506 : }
     141             : 
     142        7506 : bool RelaxNGValidator::ValidateEncoded(const std::string& filename, const std::string& document) const
     143             : {
     144        7506 :     if (!m_Schema)
     145             :     {
     146           1 :         LOGERROR("RelaxNGValidator: No grammar loaded");
     147           1 :         return false;
     148             :     }
     149             : 
     150        7505 :     xmlDocPtr doc = xmlReadMemory(document.c_str(), (int)document.size(), filename.c_str(), NULL, XML_PARSE_NONET);
     151        7505 :     if (doc == NULL)
     152             :     {
     153           2 :         LOGERROR("RelaxNGValidator: Failed to parse document '{}'", filename);
     154           1 :         return false;
     155             :     }
     156             : 
     157        7504 :     bool ret = ValidateEncoded(doc);
     158        7504 :     xmlFreeDoc(doc);
     159        7504 :     return ret;
     160             : }
     161             : 
     162        7547 : bool RelaxNGValidator::ValidateEncoded(xmlDocPtr doc) const
     163             : {
     164        7547 :     xmlRelaxNGValidCtxtPtr ctxt = xmlRelaxNGNewValidCtxt(m_Schema);
     165        7547 :     xmlRelaxNGSetValidStructuredErrors(ctxt, &relaxNGErrorHandler, NULL);
     166        7547 :     int ret = xmlRelaxNGValidateDoc(ctxt, doc);
     167        7547 :     xmlRelaxNGFreeValidCtxt(ctxt);
     168             : 
     169        7547 :     if (ret == 0)
     170             :     {
     171             :         return true;
     172             :     }
     173           7 :     else if (ret > 0)
     174             :     {
     175           7 :         if (doc->name)
     176           0 :             LOGERROR("RelaxNGValidator: Validation failed for '{}'", doc->name);
     177             :         else
     178          14 :             LOGERROR("RelaxNGValidator: Validation failed");
     179           7 :         return false;
     180             :     }
     181             :     else
     182             :     {
     183           0 :         LOGERROR("RelaxNGValidator: Internal error {}", ret);
     184           0 :         return false;
     185             :     }
     186             : }
     187             : 
     188        7797 : bool RelaxNGValidator::CanValidate() const
     189             : {
     190        7797 :     return m_Schema != NULL;
     191             : }

Generated by: LCOV version 1.16