]> git.ipfire.org Git - thirdparty/libvirt.git/commitdiff
util: add xml validation against schema in virXMLParseHelper()
authorKristina Hanicova <khanicov@redhat.com>
Wed, 11 Aug 2021 12:36:45 +0000 (14:36 +0200)
committerJán Tomko <jtomko@redhat.com>
Thu, 12 Aug 2021 11:12:29 +0000 (13:12 +0200)
We need this in order to validate XML against schema at one
place, rather than have the same code for validation in different
functions.
I will add '--validate' option to more virsh commands soon and
this makes it easier as virXMLParse() is called in every one I
plan to change.

Signed-off-by: Kristina Hanicova <khanicov@redhat.com>
Reviewed-by: Ján Tomko <jtomko@redhat.com>
Signed-off-by: Ján Tomko <jtomko@redhat.com>
src/util/virxml.c

index 0220c5906fac25531d943eaeede600c821332ea7..b896a804600cbb4e1d71fdb2b46b6d2f315cfd0e 100644 (file)
@@ -33,6 +33,7 @@
 #include "virfile.h"
 #include "virstring.h"
 #include "virutil.h"
+#include "configmake.h"
 
 #define VIR_FROM_THIS VIR_FROM_XML
 
@@ -1096,8 +1097,8 @@ catchXMLError(void *ctx, const char *msg G_GNUC_UNUSED, ...)
  * @url: URL of XML document for string parser
  * @rootelement: Optional name of the expected root element
  * @ctxt: optional pointer to populate with new context pointer
- * @schemafile: unused
- * @validate: unused
+ * @schemafile: optional name of the file the parsed XML will be validated against
+ * @validate: if true, the XML will be validated against schema in @schemafile
  *
  * Parse XML document provided either as a file or a string. The function
  * guarantees that the XML document contains a root element.
@@ -1114,8 +1115,8 @@ virXMLParseHelper(int domcode,
                   const char *url,
                   const char *rootelement,
                   xmlXPathContextPtr *ctxt,
-                  const char *schemafile G_GNUC_UNUSED,
-                  bool validate G_GNUC_UNUSED)
+                  const char *schemafile,
+                  bool validate)
 {
     struct virParserData private;
     g_autoptr(xmlParserCtxt) pctxt = NULL;
@@ -1181,6 +1182,15 @@ virXMLParseHelper(int domcode,
         (*ctxt)->node = rootnode;
     }
 
+    if (validate && schemafile != NULL) {
+        g_autofree char *schema = virFileFindResource(schemafile,
+                                                      abs_top_srcdir "/docs/schemas",
+                                                      PKGDATADIR "/schemas");
+        if (!schema ||
+            (virXMLValidateAgainstSchema(schema, xml) < 0))
+            return NULL;
+    }
+
     return g_steal_pointer(&xml);
 }