summaryrefslogtreecommitdiff
path: root/src/qemu/qemu_qapi.c
blob: 184c0a965ff79b39dae545140e52bbdf237397cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
/*
 * qemu_qapi.c: helper functions for QEMU QAPI schema handling
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
 */

#include <config.h>

#include "qemu_qapi.h"

#include "virerror.h"
#include "virlog.h"

#define VIR_FROM_THIS VIR_FROM_QEMU

VIR_LOG_INIT("qemu.qemu_qapi");


/**
 * virQEMUQAPISchemaObjectGet:
 * @field: name of the object containing the requested type
 * @name: name of the requested type
 * @namefield: name of the object property holding @name
 * @elem: QAPI schema entry JSON object
 *
 * Helper that selects the type of a QMP schema object member or it's variant
 * member. Returns the QMP entry on success or NULL on error.
 */
static virJSONValue *
virQEMUQAPISchemaObjectGet(const char *field,
                           const char *name,
                           const char *namefield,
                           virJSONValue *elem)
{
    virJSONValue *arr;
    virJSONValue *cur;
    const char *curname;
    size_t i;

    if (!(arr = virJSONValueObjectGetArray(elem, field)))
        return NULL;

    for (i = 0; i < virJSONValueArraySize(arr); i++) {
        if (!(cur = virJSONValueArrayGet(arr, i)) ||
            !(curname = virJSONValueObjectGetString(cur, namefield)))
            continue;

        if (STREQ(name, curname))
            return cur;
    }

    return NULL;
}


struct virQEMUQAPISchemaTraverseContext {
    const char *prevquery;
    GHashTable *schema;
    char **queries;
    virJSONValue *returnType;
    size_t depth;
};


static int
virQEMUQAPISchemaTraverseContextValidateDepth(struct virQEMUQAPISchemaTraverseContext *ctxt)
{
    if (ctxt->depth++ > 1000) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("possible loop in QMP schema"));
        return -1;
    }

    return 0;
}


static void
virQEMUQAPISchemaTraverseContextInit(struct virQEMUQAPISchemaTraverseContext *ctxt,
                                     char **queries,
                                     GHashTable *schema)
{
    memset(ctxt, 0, sizeof(*ctxt));
    ctxt->schema = schema;
    ctxt->queries = queries;
}


static const char *
virQEMUQAPISchemaTraverseContextNextQuery(struct virQEMUQAPISchemaTraverseContext *ctxt)
{
    ctxt->prevquery = ctxt->queries[0];
    ctxt->queries++;
    return ctxt->prevquery;
}


static bool
virQEMUQAPISchemaTraverseContextHasNextQuery(struct virQEMUQAPISchemaTraverseContext *ctxt)
{
    return !!ctxt->queries[0];
}


static int
virQEMUQAPISchemaTraverse(const char *baseName,
                          struct virQEMUQAPISchemaTraverseContext *ctxt);


/**
 * @featurename: name of 'feature' field to select
 * @elem: QAPI JSON entry for a type
 *
 * Looks for @featurename in the array of 'features' for given type passed in
 * via @elem. Returns 1 if @featurename is present, 0 if it's not present
 * (or @elem has no 'features') or -2 if the schema is malformed.
 * (see virQEMUQAPISchemaTraverseFunc)
 */
static int
virQEMUQAPISchemaTraverseHasObjectFeature(const char *featurename,
                                          virJSONValue *elem)
{
    virJSONValue *featuresarray;
    virJSONValue *cur;
    const char *curstr;
    size_t i;

    if (!(featuresarray = virJSONValueObjectGetArray(elem, "features")))
        return 0;

    for (i = 0; i < virJSONValueArraySize(featuresarray); i++) {
        if (!(cur = virJSONValueArrayGet(featuresarray, i)) ||
            !(curstr = virJSONValueGetString(cur)))
            return -2;

        if (STREQ(featurename, curstr))
            return 1;
    }

    return 0;
}


static int
virQEMUQAPISchemaTraverseObject(virJSONValue *cur,
                                struct virQEMUQAPISchemaTraverseContext *ctxt)
{
    virJSONValue *obj;
    const char *query = virQEMUQAPISchemaTraverseContextNextQuery(ctxt);
    char modifier = *query;

    if (!g_ascii_isalpha(modifier))
        query++;

    /* exit on modifiers for other types */
    if (modifier == '^' || modifier == '!')
        return 0;

    if (modifier == '$') {
        if (virQEMUQAPISchemaTraverseContextHasNextQuery(ctxt))
            return -3;

        return virQEMUQAPISchemaTraverseHasObjectFeature(query, cur);
    }

    if (modifier == '+') {
        obj = virQEMUQAPISchemaObjectGet("variants", query, "case", cur);
    } else {
        obj = virQEMUQAPISchemaObjectGet("members", query, "name", cur);

        if (modifier == '*' &&
            !virJSONValueObjectHasKey(obj, "default"))
            return 0;
    }

    if (!obj)
        return 0;

    return virQEMUQAPISchemaTraverse(virJSONValueObjectGetString(obj, "type"), ctxt);
}


static int
virQEMUQAPISchemaTraverseArray(virJSONValue *cur,
                               struct virQEMUQAPISchemaTraverseContext *ctxt)
{
    const char *querytype;

    /* arrays are just flattened by default */
    if (!(querytype = virJSONValueObjectGetString(cur, "element-type")))
        return -2;

    return virQEMUQAPISchemaTraverse(querytype, ctxt);
}


static int
virQEMUQAPISchemaTraverseCommand(virJSONValue *cur,
                                 struct virQEMUQAPISchemaTraverseContext *ctxt)
{
    const char *query = virQEMUQAPISchemaTraverseContextNextQuery(ctxt);
    const char *querytype;
    char modifier = *query;

    if (!g_ascii_isalpha(modifier))
        query++;

    /* exit on modifiers for other types */
    if (modifier == '^' || modifier == '!' || modifier == '+' || modifier == '*')
        return 0;

    if (modifier == '$') {
        if (virQEMUQAPISchemaTraverseContextHasNextQuery(ctxt))
            return -3;

        return virQEMUQAPISchemaTraverseHasObjectFeature(query, cur);
    }

    if (!(querytype = virJSONValueObjectGetString(cur, query)))
        return 0;

    return virQEMUQAPISchemaTraverse(querytype, ctxt);
}


static int
virQEMUQAPISchemaTraverseEnum(virJSONValue *cur,
                              struct virQEMUQAPISchemaTraverseContext *ctxt)
{
    const char *query = virQEMUQAPISchemaTraverseContextNextQuery(ctxt);
    const char *featurequery = NULL;
    virJSONValue *values;
    virJSONValue *members;
    size_t i;

    if (query[0] != '^')
        return 0;

    if (virQEMUQAPISchemaTraverseContextHasNextQuery(ctxt)) {
        /* we might have a query for a feature flag of an enum value */
        featurequery = virQEMUQAPISchemaTraverseContextNextQuery(ctxt);

        if (*featurequery != '$' ||
            virQEMUQAPISchemaTraverseContextHasNextQuery(ctxt))
            return -3;

        featurequery++;
    }

    query++;

    /* qemu-6.2 added a "members" array superseding "values" */
    if ((members = virJSONValueObjectGetArray(cur, "members"))) {
        for (i = 0; i < virJSONValueArraySize(members); i++) {
            virJSONValue *member = virJSONValueArrayGet(members, i);
            const char *name;

            if (!member || !(name = virJSONValueObjectGetString(member, "name")))
                return -2;

            if (STREQ(name, query)) {
                if (featurequery)
                    return virQEMUQAPISchemaTraverseHasObjectFeature(featurequery, member);

                return 1;
            }
        }

        return 0;
    }

    /* old-style "values" array doesn't have feature flags so any query is necessarily false */
    if (featurequery)
        return 0;

    if (!(values = virJSONValueObjectGetArray(cur, "values")))
        return -2;

    for (i = 0; i < virJSONValueArraySize(values); i++) {
        virJSONValue *enumval;
        const char *value;

        if (!(enumval = virJSONValueArrayGet(values, i)) ||
            !(value = virJSONValueGetString(enumval)))
            continue;

        if (STREQ(value, query))
            return 1;
    }

    return 0;
}


static int
virQEMUQAPISchemaTraverseBuiltin(virJSONValue *cur,
                                 struct virQEMUQAPISchemaTraverseContext *ctxt)
{
    const char *query = virQEMUQAPISchemaTraverseContextNextQuery(ctxt);
    const char *jsontype;

    if (query[0] != '!')
        return 0;

    if (virQEMUQAPISchemaTraverseContextHasNextQuery(ctxt))
        return -3;

    query++;

    if (!(jsontype = virJSONValueObjectGetString(cur, "json-type")))
        return -1;

    if (STREQ(jsontype, query))
        return 1;

    return 0;
}


static int
virQEMUQAPISchemaTraverseAlternate(virJSONValue *cur,
                                   struct virQEMUQAPISchemaTraverseContext *ctxt)
{
    struct virQEMUQAPISchemaTraverseContext savectxt = *ctxt;
    virJSONValue *members;
    virJSONValue *member;
    const char *membertype;
    int rc;
    size_t i;

    if (!(members = virJSONValueObjectGetArray(cur, "members")))
        return -2;

    for (i = 0; i < virJSONValueArraySize(members); i++) {
        if (!(member = virJSONValueArrayGet(members, i)) ||
            !(membertype = virJSONValueObjectGetString(member, "type")))
            continue;

        *ctxt = savectxt;

        if ((rc = virQEMUQAPISchemaTraverse(membertype, ctxt)) != 0)
            return rc;
    }

    return 0;
}


/* The function must return 1 on successful query, 0 if the query was not found
 * -1 when a libvirt error is reported, -2 if the schema is invalid and -3 if
 *  the query component is malformed. */
typedef int (*virQEMUQAPISchemaTraverseFunc)(virJSONValue *cur,
                                             struct virQEMUQAPISchemaTraverseContext *ctxt);

struct virQEMUQAPISchemaTraverseMetaType {
    const char *metatype;
    virQEMUQAPISchemaTraverseFunc func;
};


static const struct virQEMUQAPISchemaTraverseMetaType traverseMetaType[] = {
    { "object", virQEMUQAPISchemaTraverseObject },
    { "array", virQEMUQAPISchemaTraverseArray },
    { "command", virQEMUQAPISchemaTraverseCommand },
    { "event", virQEMUQAPISchemaTraverseCommand },
    { "enum", virQEMUQAPISchemaTraverseEnum },
    { "builtin", virQEMUQAPISchemaTraverseBuiltin },
    { "alternate", virQEMUQAPISchemaTraverseAlternate },
};


static int
virQEMUQAPISchemaTraverse(const char *baseName,
                          struct virQEMUQAPISchemaTraverseContext *ctxt)
{
    virJSONValue *cur;
    const char *metatype;
    size_t i;

    if (virQEMUQAPISchemaTraverseContextValidateDepth(ctxt) < 0)
        return -2;

    if (!(cur = virHashLookup(ctxt->schema, baseName)))
        return -2;

    if (!virQEMUQAPISchemaTraverseContextHasNextQuery(ctxt)) {
        ctxt->returnType = cur;
        return 1;
    }

    if (!(metatype = virJSONValueObjectGetString(cur, "meta-type")))
        return -2;

    for (i = 0; i < G_N_ELEMENTS(traverseMetaType); i++) {
        if (STREQ(metatype, traverseMetaType[i].metatype))
            return traverseMetaType[i].func(cur, ctxt);
    }

    return 0;
}


/**
 * virQEMUQAPISchemaPathGet:
 * @query: string specifying the required data type (see below)
 * @schema: hash table containing the schema data
 * @entry: filled with the located schema object requested by @query (optional)
 *
 * Retrieves the requested schema entry specified by @query to @entry. The
 * @query parameter has the following syntax which is very closely tied to the
 * qemu schema syntax entries separated by slashes with a few special characters:
 *
 * "command_or_event/attribute/subattribute/subattribute/..."
 *
 * command_or_event: name of the event or attribute to introspect
 * attribute: selects whether arguments or return type should be introspected
 *            ("arg-type" or "ret-type" for commands, "arg-type" for events)
 *
 * 'subattribute' may be one or more of the following depending on the first
 * character.
 *
 * - Type queries - @entry is filled on success with the corresponding schema entry:
 *   'subattribute': selects a plain object member named 'subattribute'
 *   '*subattribute': same as above but the selected member must be optional
 *                    (has a property named 'default' in the schema)
 *   '+variant': In the case of unionized objects, select a specific variant of
 *               the previously selected member
 *
 * - Boolean queries - @entry remains NULL, return value indicates success:
 *   '^enumval': returns true if the previously selected enum contains 'enumval'
 *   '!basictype': returns true if previously selected type is of 'basictype'
 *                 JSON type. Supported are 'null', 'string', 'number', 'value',
 *                 'int' and 'boolean.
 *   '$feature': returns true if the previously selected type supports 'feature'
 *               ('feature' is in the 'features' array of given type)
 *
 * If the name of any (sub)attribute starts with non-alphabetical symbols it
 * needs to be prefixed by a single space.
 *
 * Array types are automatically flattened to the singular type. Alternates are
 * iterated until first success.
 *
 * The above types can be chained arbitrarily using slashes to construct any
 * path into the schema tree, booleans must be always the last component as they
 * don't refer to a type. An exception is querying feature of an enum value
 * (.../^enumval/$featurename) which is allowed.
 *
 * Returns 1 if @query was found in @schema filling @entry if non-NULL, 0 if
 * @query was not found in @schema and -1 on other errors along with an appropriate
 * error message.
 */
int
virQEMUQAPISchemaPathGet(const char *query,
                         GHashTable *schema,
                         virJSONValue **entry)
{
    g_auto(GStrv) elems = NULL;
    struct virQEMUQAPISchemaTraverseContext ctxt;
    const char *cmdname;
    int rc;

    if (entry)
        *entry = NULL;

    if (!(elems = g_strsplit(query, "/", 0)))
        return -1;

    if (!*elems) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("malformed query string"));
        return -1;
    }

    virQEMUQAPISchemaTraverseContextInit(&ctxt, elems, schema);
    cmdname = virQEMUQAPISchemaTraverseContextNextQuery(&ctxt);

    if (!virHashLookup(schema, cmdname))
        return 0;

    rc = virQEMUQAPISchemaTraverse(cmdname, &ctxt);

    if (entry)
        *entry = ctxt.returnType;

    if (rc >= 0)
        return rc;

    if (rc == -2) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("malformed QAPI schema when querying '%1$s' of '%2$s'"),
                       NULLSTR(ctxt.prevquery), query);
    } else if (rc == -3) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("terminal QAPI query component '%1$s' of '%2$s' must not have followers"),
                       NULLSTR(ctxt.prevquery), query);
    }

    return -1;
}


bool
virQEMUQAPISchemaPathExists(const char *query,
                            GHashTable *schema)
{
    return virQEMUQAPISchemaPathGet(query, schema, NULL) == 1;
}

static int
virQEMUQAPISchemaEntryProcess(size_t pos G_GNUC_UNUSED,
                              virJSONValue *item,
                              void *opaque)
{
    const char *name;
    GHashTable *schema = opaque;

    if (!(name = virJSONValueObjectGetString(item, "name"))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("malformed QMP schema"));
        return -1;
    }

    if (virHashAddEntry(schema, name, item) < 0)
        return -1;

    return 0;
}


/**
 * virQEMUQAPISchemaConvert:
 * @schemareply: Schema data as returned by the qemu monitor
 *
 * Converts the schema into the hash-table used by the functions working with
 * the schema. @schemareply is consumed and freed.
 */
GHashTable *
virQEMUQAPISchemaConvert(virJSONValue *schemareply)
{
    g_autoptr(GHashTable) schema = NULL;
    g_autoptr(virJSONValue) schemajson = schemareply;

    if (!(schema = virHashNew(virJSONValueHashFree)))
        return NULL;

    if (virJSONValueArrayForeachSteal(schemajson,
                                      virQEMUQAPISchemaEntryProcess,
                                      schema) < 0)
        return NULL;

    return g_steal_pointer(&schema);
}