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>
30 struct validation_ctx
{
31 xmlSchemaParserCtxtPtr parser_ctx
;
33 xmlSchemaValidCtxtPtr schema_validation_ctx
;
36 enum command_err_code
{
41 static ATTR_FORMAT_PRINTF(2, 3)
42 void xml_error_handler(void *ctx
__attribute__((unused
)),
43 const char *format
, ...)
49 va_start(args
, format
);
50 ret
= vasprintf(&err_msg
, format
, args
);
53 fprintf(stderr
, "ERR: %s\n",
54 "String allocation failed in xml error handle");
58 fprintf(stderr
, "XML Error: %s\n", err_msg
);
63 void fini_validation_ctx(
64 struct validation_ctx
*ctx
)
66 if (ctx
->parser_ctx
) {
67 xmlSchemaFreeParserCtxt(ctx
->parser_ctx
);
71 xmlSchemaFree(ctx
->schema
);
74 if (ctx
->schema_validation_ctx
) {
75 xmlSchemaFreeValidCtxt(ctx
->schema_validation_ctx
);
78 memset(ctx
, 0, sizeof(struct validation_ctx
));
82 int init_validation_ctx(
83 struct validation_ctx
*ctx
, char *xsd_path
)
88 ret
= -LTTNG_ERR_NOMEM
;
92 ctx
->parser_ctx
= xmlSchemaNewParserCtxt(xsd_path
);
93 if (!ctx
->parser_ctx
) {
94 ret
= -LTTNG_ERR_LOAD_INVALID_CONFIG
;
97 xmlSchemaSetParserErrors(ctx
->parser_ctx
, xml_error_handler
,
98 xml_error_handler
, NULL
);
100 ctx
->schema
= xmlSchemaParse(ctx
->parser_ctx
);
102 ret
= -LTTNG_ERR_LOAD_INVALID_CONFIG
;
106 ctx
->schema_validation_ctx
= xmlSchemaNewValidCtxt(ctx
->schema
);
107 if (!ctx
->schema_validation_ctx
) {
108 ret
= -LTTNG_ERR_LOAD_INVALID_CONFIG
;
112 xmlSchemaSetValidErrors(ctx
->schema_validation_ctx
, xml_error_handler
,
113 xml_error_handler
, NULL
);
118 fini_validation_ctx(ctx
);
123 static int validate_xml(const char *xml_file_path
, struct validation_ctx
*ctx
)
126 xmlDocPtr doc
= NULL
;
128 LTTNG_ASSERT(xml_file_path
);
131 /* Open the document */
132 doc
= xmlParseFile(xml_file_path
);
134 ret
= LTTNG_ERR_MI_IO_FAIL
;
138 /* Validate against the validation ctx (xsd) */
139 ret
= xmlSchemaValidateDoc(ctx
->schema_validation_ctx
, doc
);
141 fprintf(stderr
, "ERR: %s\n", "XML is not valid againt provided XSD");
152 int main(int argc
, char **argv
)
155 struct validation_ctx ctx
= {};
157 /* Check if we have all argument */
159 fprintf(stderr
, "ERR: %s\n", "Missing arguments");
164 /* Check if xsd file exist */
165 ret
= access(argv
[1], F_OK
);
167 fprintf(stderr
, "ERR: %s\n", "Xsd path not valid");
171 /* Check if xml to validate exist */
172 ret
= access(argv
[2], F_OK
);
174 fprintf(stderr
, "ERR: %s\n", "XML path not valid");
178 /* initialize the validation ctx */
179 ret
= init_validation_ctx(&ctx
, argv
[1]);
184 ret
= validate_xml(argv
[2], &ctx
);
186 fini_validation_ctx(&ctx
);