2 * Copyright (C) 2014 EfficiOS Inc.
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.hpp>
31 struct validation_ctx
{
32 xmlSchemaParserCtxtPtr parser_ctx
;
34 xmlSchemaValidCtxtPtr schema_validation_ctx
;
38 enum command_err_code
{
43 static ATTR_FORMAT_PRINTF(2, 3)
44 void xml_error_handler(void *ctx
__attribute__((unused
)),
45 const char *format
, ...)
51 va_start(args
, format
);
52 ret
= vasprintf(&err_msg
, format
, args
);
55 fprintf(stderr
, "ERR: %s\n",
56 "String allocation failed in xml error handle");
60 fprintf(stderr
, "XML Error: %s\n", err_msg
);
65 void fini_validation_ctx(
66 struct validation_ctx
*ctx
)
68 if (ctx
->parser_ctx
) {
69 xmlSchemaFreeParserCtxt(ctx
->parser_ctx
);
73 xmlSchemaFree(ctx
->schema
);
76 if (ctx
->schema_validation_ctx
) {
77 xmlSchemaFreeValidCtxt(ctx
->schema_validation_ctx
);
80 memset(ctx
, 0, sizeof(struct validation_ctx
));
84 int init_validation_ctx(
85 struct validation_ctx
*ctx
, char *xsd_path
)
90 ret
= -LTTNG_ERR_NOMEM
;
94 ctx
->parser_ctx
= xmlSchemaNewParserCtxt(xsd_path
);
95 if (!ctx
->parser_ctx
) {
96 ret
= -LTTNG_ERR_LOAD_INVALID_CONFIG
;
99 xmlSchemaSetParserErrors(ctx
->parser_ctx
, xml_error_handler
,
100 xml_error_handler
, NULL
);
102 ctx
->schema
= xmlSchemaParse(ctx
->parser_ctx
);
104 ret
= -LTTNG_ERR_LOAD_INVALID_CONFIG
;
108 ctx
->schema_validation_ctx
= xmlSchemaNewValidCtxt(ctx
->schema
);
109 if (!ctx
->schema_validation_ctx
) {
110 ret
= -LTTNG_ERR_LOAD_INVALID_CONFIG
;
114 xmlSchemaSetValidErrors(ctx
->schema_validation_ctx
, xml_error_handler
,
115 xml_error_handler
, NULL
);
120 fini_validation_ctx(ctx
);
125 static int validate_xml(const char *xml_file_path
, struct validation_ctx
*ctx
)
128 xmlDocPtr doc
= NULL
;
130 LTTNG_ASSERT(xml_file_path
);
133 /* Open the document */
134 doc
= xmlParseFile(xml_file_path
);
136 ret
= LTTNG_ERR_MI_IO_FAIL
;
140 /* Validate against the validation ctx (xsd) */
141 ret
= xmlSchemaValidateDoc(ctx
->schema_validation_ctx
, doc
);
143 fprintf(stderr
, "ERR: %s\n", "XML is not valid againt provided XSD");
156 int main(int argc
, char **argv
)
159 struct validation_ctx ctx
= {};
161 /* Check if we have all argument */
163 fprintf(stderr
, "ERR: %s\n", "Missing arguments");
168 /* Check if xsd file exist */
169 ret
= access(argv
[1], F_OK
);
171 fprintf(stderr
, "ERR: %s\n", "Xsd path not valid");
175 /* Check if xml to validate exist */
176 ret
= access(argv
[2], F_OK
);
178 fprintf(stderr
, "ERR: %s\n", "XML path not valid");
182 /* initialize the validation ctx */
183 ret
= init_validation_ctx(&ctx
, argv
[1]);
188 ret
= validate_xml(argv
[2], &ctx
);
190 fini_validation_ctx(&ctx
);