2 * Copyright (C) 2014 Jonathan Rajotte <jonathan.r.julien@gmail.com>
4 * SPDX-License-Identifier: LGPL-2.1-only
9 * This script validate and xml from an xsd.
10 * argv[1] Path of the xsd
11 * argv[2] Path to the XML to be validated
21 #include <sys/types.h>
24 #include <libxml/xmlschemas.h>
25 #include <libxml/parser.h>
27 #include <lttng/lttng-error.h>
28 #include <common/macros.h>
30 #include <common/macros.h>
32 struct validation_ctx
{
33 xmlSchemaParserCtxtPtr parser_ctx
;
35 xmlSchemaValidCtxtPtr schema_validation_ctx
;
38 enum command_err_code
{
43 static ATTR_FORMAT_PRINTF(2, 3)
44 void xml_error_handler(void *ctx
, const char *format
, ...)
50 va_start(args
, format
);
51 ret
= vasprintf(&err_msg
, format
, args
);
54 fprintf(stderr
, "ERR: %s\n",
55 "String allocation failed in xml error handle");
59 fprintf(stderr
, "XML Error: %s\n", err_msg
);
64 void fini_validation_ctx(
65 struct validation_ctx
*ctx
)
67 if (ctx
->parser_ctx
) {
68 xmlSchemaFreeParserCtxt(ctx
->parser_ctx
);
72 xmlSchemaFree(ctx
->schema
);
75 if (ctx
->schema_validation_ctx
) {
76 xmlSchemaFreeValidCtxt(ctx
->schema_validation_ctx
);
79 memset(ctx
, 0, sizeof(struct validation_ctx
));
83 int init_validation_ctx(
84 struct validation_ctx
*ctx
, char *xsd_path
)
89 ret
= -LTTNG_ERR_NOMEM
;
93 ctx
->parser_ctx
= xmlSchemaNewParserCtxt(xsd_path
);
94 if (!ctx
->parser_ctx
) {
95 ret
= -LTTNG_ERR_LOAD_INVALID_CONFIG
;
98 xmlSchemaSetParserErrors(ctx
->parser_ctx
, xml_error_handler
,
99 xml_error_handler
, NULL
);
101 ctx
->schema
= xmlSchemaParse(ctx
->parser_ctx
);
103 ret
= -LTTNG_ERR_LOAD_INVALID_CONFIG
;
107 ctx
->schema_validation_ctx
= xmlSchemaNewValidCtxt(ctx
->schema
);
108 if (!ctx
->schema_validation_ctx
) {
109 ret
= -LTTNG_ERR_LOAD_INVALID_CONFIG
;
113 xmlSchemaSetValidErrors(ctx
->schema_validation_ctx
, xml_error_handler
,
114 xml_error_handler
, NULL
);
119 fini_validation_ctx(ctx
);
124 static int validate_xml(const char *xml_file_path
, struct validation_ctx
*ctx
)
127 xmlDocPtr doc
= NULL
;
129 LTTNG_ASSERT(xml_file_path
);
132 /* Open the document */
133 doc
= xmlParseFile(xml_file_path
);
135 ret
= LTTNG_ERR_MI_IO_FAIL
;
139 /* Validate against the validation ctx (xsd) */
140 ret
= xmlSchemaValidateDoc(ctx
->schema_validation_ctx
, doc
);
142 fprintf(stderr
, "ERR: %s\n", "XML is not valid againt provided XSD");
153 int main(int argc
, char **argv
, char *env
[])
156 struct validation_ctx ctx
= { 0 };
158 /* Check if we have all argument */
160 fprintf(stderr
, "ERR: %s\n", "Missing arguments");
165 /* Check if xsd file exist */
166 ret
= access(argv
[1], F_OK
);
168 fprintf(stderr
, "ERR: %s\n", "Xsd path not valid");
172 /* Check if xml to validate exist */
173 ret
= access(argv
[2], F_OK
);
175 fprintf(stderr
, "ERR: %s\n", "XML path not valid");
179 /* initialize the validation ctx */
180 ret
= init_validation_ctx(&ctx
, argv
[1]);
185 ret
= validate_xml(argv
[2], &ctx
);
187 fini_validation_ctx(&ctx
);