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
22 #include <sys/types.h>
25 #include <libxml/xmlschemas.h>
26 #include <libxml/parser.h>
28 #include <lttng/lttng-error.h>
30 struct validation_ctx
{
31 xmlSchemaParserCtxtPtr parser_ctx
;
33 xmlSchemaValidCtxtPtr schema_validation_ctx
;
36 enum command_err_code
{
42 void xml_error_handler(void *ctx
, const char *format
, ...)
48 va_start(args
, format
);
49 ret
= vasprintf(&err_msg
, format
, args
);
52 fprintf(stderr
, "ERR: %s\n",
53 "String allocation failed in xml error handle");
57 fprintf(stderr
, "XML Error: %s\n", err_msg
);
62 void fini_validation_ctx(
63 struct validation_ctx
*ctx
)
65 if (ctx
->parser_ctx
) {
66 xmlSchemaFreeParserCtxt(ctx
->parser_ctx
);
70 xmlSchemaFree(ctx
->schema
);
73 if (ctx
->schema_validation_ctx
) {
74 xmlSchemaFreeValidCtxt(ctx
->schema_validation_ctx
);
77 memset(ctx
, 0, sizeof(struct validation_ctx
));
81 int init_validation_ctx(
82 struct validation_ctx
*ctx
, char *xsd_path
)
87 ret
= -LTTNG_ERR_NOMEM
;
91 ctx
->parser_ctx
= xmlSchemaNewParserCtxt(xsd_path
);
92 if (!ctx
->parser_ctx
) {
93 ret
= -LTTNG_ERR_LOAD_INVALID_CONFIG
;
96 xmlSchemaSetParserErrors(ctx
->parser_ctx
, xml_error_handler
,
97 xml_error_handler
, NULL
);
99 ctx
->schema
= xmlSchemaParse(ctx
->parser_ctx
);
101 ret
= -LTTNG_ERR_LOAD_INVALID_CONFIG
;
105 ctx
->schema_validation_ctx
= xmlSchemaNewValidCtxt(ctx
->schema
);
106 if (!ctx
->schema_validation_ctx
) {
107 ret
= -LTTNG_ERR_LOAD_INVALID_CONFIG
;
111 xmlSchemaSetValidErrors(ctx
->schema_validation_ctx
, xml_error_handler
,
112 xml_error_handler
, NULL
);
117 fini_validation_ctx(ctx
);
122 static int validate_xml(const char *xml_file_path
, struct validation_ctx
*ctx
)
125 xmlDocPtr doc
= NULL
;
127 assert(xml_file_path
);
130 /* Open the document */
131 doc
= xmlParseFile(xml_file_path
);
133 ret
= LTTNG_ERR_MI_IO_FAIL
;
137 /* Validate against the validation ctx (xsd) */
138 ret
= xmlSchemaValidateDoc(ctx
->schema_validation_ctx
, doc
);
140 fprintf(stderr
, "ERR: %s\n", "XML is not valid againt provided XSD");
151 int main(int argc
, char **argv
, char *env
[])
154 struct validation_ctx ctx
= { 0 };
156 /* Check if we have all argument */
158 fprintf(stderr
, "ERR: %s\n", "Missing arguments");
163 /* Check if xsd file exist */
164 ret
= access(argv
[1], F_OK
);
166 fprintf(stderr
, "ERR: %s\n", "Xsd path not valid");
170 /* Check if xml to validate exist */
171 ret
= access(argv
[2], F_OK
);
173 fprintf(stderr
, "ERR: %s\n", "XML path not valid");
177 /* initialize the validation ctx */
178 ret
= init_validation_ctx(&ctx
, argv
[1]);
183 ret
= validate_xml(argv
[2], &ctx
);
185 fini_validation_ctx(&ctx
);