QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
JsonSchemaValidator.cc
Go to the documentation of this file.
2
3#include <memory>
4#include <valijson/adapters/qtjson_adapter.hpp>
5#include <valijson/schema.hpp>
6#include <valijson/schema_parser.hpp>
7#include <valijson/validation_results.hpp>
8#include <valijson/validator.hpp>
9
10#include <QtCore/QCborValue>
11#include <QtCore/QCryptographicHash>
12#include <QtCore/QFile>
13#include <QtCore/QHash>
14#include <QtCore/QJsonDocument>
15#include <QtCore/QJsonObject>
16#include <QtCore/QJsonParseError>
17#include <QtCore/QSet>
18#include <QtCore/QStringList>
19
20#include "QGCLoggingCategory.h"
21
22QGC_LOGGING_CATEGORY(JsonSchemaValidatorLog, "Utilities.Parsing.Json.Schema")
23
25
26namespace {
27
28std::shared_ptr<const valijson::Schema> loadSchema(const QString& schemaResourcePath, QString& errorString)
29{
30 // Unguarded static: component-metadata validation runs on the main thread only.
31 static QHash<QString, std::shared_ptr<const valijson::Schema>> schemaCache;
32
33 if (const auto cached = schemaCache.value(schemaResourcePath)) {
34 return cached;
35 }
36
37 QFile schemaFile(schemaResourcePath);
38 if (!schemaFile.open(QIODevice::ReadOnly)) {
39 errorString = QStringLiteral("Failed to open schema resource: %1").arg(schemaResourcePath);
40 return nullptr;
41 }
42
43 QJsonParseError parseError;
44 const QJsonDocument schemaDoc = QJsonDocument::fromJson(schemaFile.readAll(), &parseError);
45 if (parseError.error != QJsonParseError::NoError) {
46 errorString = QStringLiteral("Failed to parse schema %1: %2").arg(schemaResourcePath, parseError.errorString());
47 return nullptr;
48 }
49
50 // QGC parsers pin the supported metadata version per component (CompInfoParam: version==1) while
51 // the upstream schemas require newer ones, so drop the version range and validate structure only.
52 QJsonObject schemaObj = schemaDoc.object();
53 QJsonObject schemaProps = schemaObj.value(QStringLiteral("properties")).toObject();
54 if (schemaProps.contains(QStringLiteral("version"))) {
55 QJsonObject versionSchema = schemaProps.value(QStringLiteral("version")).toObject();
56 versionSchema.remove(QStringLiteral("minimum"));
57 versionSchema.remove(QStringLiteral("maximum"));
58 schemaProps[QStringLiteral("version")] = versionSchema;
59 schemaObj[QStringLiteral("properties")] = schemaProps;
60 }
61
62 auto schema = std::make_shared<valijson::Schema>();
63 try {
64 valijson::SchemaParser parser;
65 const valijson::adapters::QtJsonAdapter schemaAdapter(schemaObj);
66 parser.populateSchema(schemaAdapter, *schema);
67 } catch (const std::exception& e) {
68 errorString =
69 QStringLiteral("Failed to load schema %1: %2").arg(schemaResourcePath, QString::fromUtf8(e.what()));
70 return nullptr;
71 }
72
73 schemaCache.insert(schemaResourcePath, schema);
74 return schema;
75}
76
77} // namespace
78
79bool validate(const QJsonDocument& doc, const QString& schemaResourcePath, QString& errorString)
80{
81 errorString.clear();
82
83 const QJsonValue root = doc.isArray() ? QJsonValue(doc.array()) : QJsonValue(doc.object());
84
85 // Vehicles send the same component metadata on every connection, so remember documents that
86 // already passed. Unguarded static: component-metadata validation runs on the main thread only.
87 static QSet<QByteArray> validatedDocuments;
88 QCryptographicHash digest(QCryptographicHash::Sha256);
89 digest.addData(schemaResourcePath.toUtf8());
90 digest.addData(QByteArrayView("\0", 1));
91 digest.addData(QCborValue::fromJsonValue(root).toCbor());
92 const QByteArray documentKey = digest.result();
93 if (validatedDocuments.contains(documentKey)) {
94 return true;
95 }
96
97 const auto schema = loadSchema(schemaResourcePath, errorString);
98 if (!schema) {
99 return false;
100 }
101
102 valijson::Validator validator;
103 valijson::ValidationResults results;
104 const valijson::adapters::QtJsonAdapter docAdapter(root);
105
106 if (validator.validate(*schema, docAdapter, &results)) {
107 validatedDocuments.insert(documentKey);
108 return true;
109 }
110
111 QStringList failures;
112 valijson::ValidationResults::Error error;
113 while (results.popError(error)) {
114 failures.append(QStringLiteral("%1: %2").arg(QString::fromStdString(error.jsonPointer),
115 QString::fromStdString(error.description)));
116 }
117 errorString = failures.join(QStringLiteral("; "));
118 return false;
119}
120
121} // namespace JsonSchemaValidator
#define QGC_LOGGING_CATEGORY(name, categoryStr)
bool validate(const QJsonDocument &doc, const QString &schemaResourcePath, QString &errorString)