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
14 #include <common/macros.hpp>
16 #include <lttng/lttng-error.h>
21 #include <libxml/parser.h>
22 #include <libxml/xmlschemas.h>
27 #include <sys/types.h>
31 struct validation_ctx
{
32 xmlSchemaParserCtxtPtr parser_ctx
;
34 xmlSchemaValidCtxtPtr schema_validation_ctx
;
38 enum command_err_code
{ CMD_SUCCESS
= 0, CMD_ERROR
};
40 static ATTR_FORMAT_PRINTF(2, 3) void xml_error_handler(void *ctx
__attribute__((unused
)),
48 va_start(args
, format
);
49 ret
= vasprintf(&err_msg
, format
, args
);
52 fprintf(stderr
, "ERR: %s\n", "String allocation failed in xml error handle");
56 fprintf(stderr
, "XML Error: %s\n", err_msg
);
60 static void fini_validation_ctx(struct validation_ctx
*ctx
)
62 if (ctx
->parser_ctx
) {
63 xmlSchemaFreeParserCtxt(ctx
->parser_ctx
);
67 xmlSchemaFree(ctx
->schema
);
70 if (ctx
->schema_validation_ctx
) {
71 xmlSchemaFreeValidCtxt(ctx
->schema_validation_ctx
);
74 memset(ctx
, 0, sizeof(struct validation_ctx
));
77 static int init_validation_ctx(struct validation_ctx
*ctx
, char *xsd_path
)
82 ret
= -LTTNG_ERR_NOMEM
;
86 ctx
->parser_ctx
= xmlSchemaNewParserCtxt(xsd_path
);
87 if (!ctx
->parser_ctx
) {
88 ret
= -LTTNG_ERR_LOAD_INVALID_CONFIG
;
91 xmlSchemaSetParserErrors(ctx
->parser_ctx
, xml_error_handler
, xml_error_handler
, nullptr);
93 ctx
->schema
= xmlSchemaParse(ctx
->parser_ctx
);
95 ret
= -LTTNG_ERR_LOAD_INVALID_CONFIG
;
99 ctx
->schema_validation_ctx
= xmlSchemaNewValidCtxt(ctx
->schema
);
100 if (!ctx
->schema_validation_ctx
) {
101 ret
= -LTTNG_ERR_LOAD_INVALID_CONFIG
;
105 xmlSchemaSetValidErrors(
106 ctx
->schema_validation_ctx
, xml_error_handler
, xml_error_handler
, nullptr);
111 fini_validation_ctx(ctx
);
116 static int validate_xml(const char *xml_file_path
, struct validation_ctx
*ctx
)
119 xmlDocPtr doc
= nullptr;
121 LTTNG_ASSERT(xml_file_path
);
124 /* Open the document */
125 doc
= xmlParseFile(xml_file_path
);
127 ret
= LTTNG_ERR_MI_IO_FAIL
;
131 /* Validate against the validation ctx (xsd) */
132 ret
= xmlSchemaValidateDoc(ctx
->schema_validation_ctx
, doc
);
134 fprintf(stderr
, "ERR: %s\n", "XML is not valid againt provided XSD");
147 int main(int argc
, char **argv
)
150 struct validation_ctx ctx
= {};
152 /* Check if we have all argument */
154 fprintf(stderr
, "ERR: %s\n", "Missing arguments");
159 /* Check if xsd file exist */
160 ret
= access(argv
[1], F_OK
);
162 fprintf(stderr
, "ERR: %s\n", "Xsd path not valid");
166 /* Check if xml to validate exist */
167 ret
= access(argv
[2], F_OK
);
169 fprintf(stderr
, "ERR: %s\n", "XML path not valid");
173 /* initialize the validation ctx */
174 ret
= init_validation_ctx(&ctx
, argv
[1]);
179 ret
= validate_xml(argv
[2], &ctx
);
181 fini_validation_ctx(&ctx
);