virjson.c 51.0 KB
Newer Older
1
/*
2
 * virjson.c: JSON object parsing/formatting
3
 *
M
Martin Kletzander 已提交
4
 * Copyright (C) 2009-2010, 2012-2015 Red Hat, Inc.
5
 * Copyright (C) 2009 Daniel P. Berrange
6 7 8 9 10 11 12 13 14 15 16 17
 *
 * 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
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
20 21 22 23 24 25
 *
 */


#include <config.h>

26
#include "virjson.h"
27
#include "viralloc.h"
28
#include "virerror.h"
29
#include "virlog.h"
30
#include "virstring.h"
31
#include "virutil.h"
32
#include "virbuffer.h"
33
#include "virenum.h"
34

35 36 37 38 39 40
#if WITH_YAJL
# include <yajl/yajl_gen.h>
# include <yajl/yajl_parse.h>

#endif

41 42 43
/* XXX fixme */
#define VIR_FROM_THIS VIR_FROM_NONE

44
VIR_LOG_INIT("util.json");
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
typedef struct _virJSONObject virJSONObject;
typedef virJSONObject *virJSONObjectPtr;

typedef struct _virJSONObjectPair virJSONObjectPair;
typedef virJSONObjectPair *virJSONObjectPairPtr;

typedef struct _virJSONArray virJSONArray;
typedef virJSONArray *virJSONArrayPtr;


struct _virJSONObjectPair {
    char *key;
    virJSONValuePtr value;
};

struct _virJSONObject {
    size_t npairs;
    virJSONObjectPairPtr pairs;
};

struct _virJSONArray {
    size_t nvalues;
    virJSONValuePtr *values;
};

struct _virJSONValue {
    int type; /* enum virJSONType */

    union {
        virJSONObject object;
        virJSONArray array;
        char *string;
        char *number; /* int/float/etc format is context defined so we can't parse it here :-( */
        int boolean;
    } data;
};


84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
typedef struct _virJSONParserState virJSONParserState;
typedef virJSONParserState *virJSONParserStatePtr;
struct _virJSONParserState {
    virJSONValuePtr value;
    char *key;
};

typedef struct _virJSONParser virJSONParser;
typedef virJSONParser *virJSONParserPtr;
struct _virJSONParser {
    virJSONValuePtr head;
    virJSONParserStatePtr state;
    size_t nstate;
    int wrap;
};


101 102 103 104 105 106 107
virJSONType
virJSONValueGetType(const virJSONValue *value)
{
    return value->type;
}


108
/**
109 110 111
 * virJSONValueObjectAddVArgs:
 * @obj: JSON object to add the values to
 * @args: a key-value argument pairs, terminated by NULL
112
 *
113
 * Adds the key-value pairs supplied as variable argument list to @obj.
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
 *
 * Keys look like   s:name  the first letter is a type code:
 * Explanation of type codes:
 * s: string value, must be non-null
 * S: string value, omitted if null
 *
 * i: signed integer value
 * j: signed integer value, error if negative
 * z: signed integer value, omitted if zero
 * y: signed integer value, omitted if zero, error if negative
 *
 * I: signed long integer value
 * J: signed long integer value, error if negative
 * Z: signed long integer value, omitted if zero
 * Y: signed long integer value, omitted if zero, error if negative
 *
 * u: unsigned integer value
 * p: unsigned integer value, omitted if zero
 *
 * U: unsigned long integer value (see below for quirks)
 * P: unsigned long integer value, omitted if zero
 *
 * b: boolean value
 * B: boolean value, omitted if false
138 139
 * T: boolean value specified by a virTristate(Bool|Switch) value, omitted on
 * the _ABSENT value
140 141 142
 *
 * d: double precision floating point number
 * n: json null value
143
 *
144 145
 * The following two cases take a pointer to a pointer to a virJSONValuePtr. The
 * pointer is cleared when the virJSONValuePtr is stolen into the object.
146
 * a: json object, must be non-NULL
147
 * A: json object, omitted if NULL
148
 *
149 150
 * m: a bitmap represented as a JSON array, must be non-NULL
 * M: a bitmap represented as a JSON array, omitted if NULL
151 152 153 154
 *
 * The value corresponds to the selected type.
 *
 * Returns -1 on error. 1 on success, if at least one key:pair was valid 0
155
 * in case of no error but nothing was filled.
156 157
 */
int
158 159
virJSONValueObjectAddVArgs(virJSONValuePtr obj,
                           va_list args)
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
{
    char type;
    char *key;
    int ret = -1;
    int rc;

    while ((key = va_arg(args, char *)) != NULL) {

        if (strlen(key) < 3) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("argument key '%s' is too short, missing type prefix"),
                           key);
            goto cleanup;
        }

        type = key[0];
        key += 2;

        /* This doesn't support maps, but no command uses those.  */
        switch (type) {
        case 'S':
        case 's': {
            char *val = va_arg(args, char *);
            if (!val) {
                if (type == 'S')
                    continue;

                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("argument key '%s' must not have null value"),
                               key);
                goto cleanup;
            }
192
            rc = virJSONValueObjectAppendString(obj, key, val);
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
        }   break;

        case 'z':
        case 'y':
        case 'j':
        case 'i': {
            int val = va_arg(args, int);

            if (val < 0 && (type == 'j' || type == 'y')) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("argument key '%s' must not be negative"),
                               key);
                goto cleanup;
            }

            if (!val && (type == 'z' || type == 'y'))
                continue;

211
            rc = virJSONValueObjectAppendNumberInt(obj, key, val);
212 213 214 215 216 217 218 219 220
        }   break;

        case 'p':
        case 'u': {
            unsigned int val = va_arg(args, unsigned int);

            if (!val && type == 'p')
                continue;

221
            rc = virJSONValueObjectAppendNumberUint(obj, key, val);
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
        }   break;

        case 'Z':
        case 'Y':
        case 'J':
        case 'I': {
            long long val = va_arg(args, long long);

            if (val < 0 && (type == 'J' || type == 'Y')) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("argument key '%s' must not be negative"),
                               key);
                goto cleanup;
            }

            if (!val && (type == 'Z' || type == 'Y'))
                continue;

240
            rc = virJSONValueObjectAppendNumberLong(obj, key, val);
241 242 243 244 245 246 247 248 249 250 251 252 253 254
        }   break;

        case 'P':
        case 'U': {
            /* qemu silently truncates numbers larger than LLONG_MAX,
             * so passing the full range of unsigned 64 bit integers
             * is not safe here.  Pass them as signed 64 bit integers
             * instead.
             */
            long long val = va_arg(args, long long);

            if (!val && type == 'P')
                continue;

255
            rc = virJSONValueObjectAppendNumberLong(obj, key, val);
256 257 258 259
        }   break;

        case 'd': {
            double val = va_arg(args, double);
260
            rc = virJSONValueObjectAppendNumberDouble(obj, key, val);
261 262
        }   break;

263
        case 'T':
264 265 266 267 268 269 270
        case 'B':
        case 'b': {
            int val = va_arg(args, int);

            if (!val && type == 'B')
                continue;

271 272 273 274 275 276 277 278 279 280
            if (type == 'T') {
                if (val == VIR_TRISTATE_BOOL_ABSENT)
                    continue;

                if (val == VIR_TRISTATE_BOOL_NO)
                    val = 0;
                else
                    val = 1;
            }

281
            rc = virJSONValueObjectAppendBoolean(obj, key, val);
282 283 284
        }   break;

        case 'n': {
285
            rc = virJSONValueObjectAppendNull(obj, key);
286 287
        }   break;

288
        case 'A':
289
        case 'a': {
290
            virJSONValuePtr *val = va_arg(args, virJSONValuePtr *);
291

292
            if (!(*val)) {
293 294 295
                if (type == 'A')
                    continue;

296 297 298 299 300 301
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("argument key '%s' must not have null value"),
                               key);
                goto cleanup;
            }

302 303
            if ((rc = virJSONValueObjectAppend(obj, key, *val)) == 0)
                *val = NULL;
304 305
        }   break;

306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
        case 'M':
        case 'm': {
            virBitmapPtr map = va_arg(args, virBitmapPtr);
            virJSONValuePtr jsonMap;

            if (!map) {
                if (type == 'M')
                    continue;

                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("argument key '%s' must not have null value"),
                               key);
                goto cleanup;
            }

            if (!(jsonMap = virJSONValueNewArrayFromBitmap(map)))
                goto cleanup;

            if ((rc = virJSONValueObjectAppend(obj, key, jsonMap)) < 0)
                virJSONValueFree(jsonMap);
        } break;

328 329 330 331 332 333 334 335 336 337 338
        default:
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unsupported data type '%c' for arg '%s'"), type, key - 2);
            goto cleanup;
        }

        if (rc < 0)
            goto cleanup;
    }

    /* verify that we added at least one key-value pair */
339
    if (virJSONValueObjectKeysNumber(obj) == 0) {
340 341 342 343 344 345 346
        ret = 0;
        goto cleanup;
    }

    ret = 1;

 cleanup:
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
    return ret;
}


int
virJSONValueObjectAdd(virJSONValuePtr obj, ...)
{
    va_list args;
    int ret;

    va_start(args, obj);
    ret = virJSONValueObjectAddVArgs(obj, args);
    va_end(args);

    return ret;
}


int
virJSONValueObjectCreateVArgs(virJSONValuePtr *obj,
                              va_list args)
{
    int ret;

    if (!(*obj = virJSONValueNewObject()))
        return -1;

    /* free the object on error, or if no value objects were added */
    if ((ret = virJSONValueObjectAddVArgs(*obj, args)) <= 0) {
        virJSONValueFree(*obj);
        *obj = NULL;
    }

380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
    return ret;
}


int
virJSONValueObjectCreate(virJSONValuePtr *obj, ...)
{
    va_list args;
    int ret;

    va_start(args, obj);
    ret = virJSONValueObjectCreateVArgs(obj, args);
    va_end(args);

    return ret;
}


398 399
void
virJSONValueFree(virJSONValuePtr value)
400
{
401
    size_t i;
402
    if (!value)
403 404
        return;

E
Eric Blake 已提交
405
    switch ((virJSONType) value->type) {
406
    case VIR_JSON_TYPE_OBJECT:
407
        for (i = 0; i < value->data.object.npairs; i++) {
408 409 410 411 412 413
            VIR_FREE(value->data.object.pairs[i].key);
            virJSONValueFree(value->data.object.pairs[i].value);
        }
        VIR_FREE(value->data.object.pairs);
        break;
    case VIR_JSON_TYPE_ARRAY:
414
        for (i = 0; i < value->data.array.nvalues; i++)
415 416 417 418 419 420 421 422 423
            virJSONValueFree(value->data.array.values[i]);
        VIR_FREE(value->data.array.values);
        break;
    case VIR_JSON_TYPE_STRING:
        VIR_FREE(value->data.string);
        break;
    case VIR_JSON_TYPE_NUMBER:
        VIR_FREE(value->data.number);
        break;
E
Eric Blake 已提交
424 425 426
    case VIR_JSON_TYPE_BOOLEAN:
    case VIR_JSON_TYPE_NULL:
        break;
427
    }
428 429

    VIR_FREE(value);
430 431 432
}


433 434
void
virJSONValueHashFree(void *opaque,
J
Ján Tomko 已提交
435
                     const void *name G_GNUC_UNUSED)
436 437 438 439 440
{
    virJSONValueFree(opaque);
}


441 442
virJSONValuePtr
virJSONValueNewString(const char *data)
443 444 445 446 447 448 449 450 451 452
{
    virJSONValuePtr val;

    if (!data)
        return virJSONValueNewNull();

    if (VIR_ALLOC(val) < 0)
        return NULL;

    val->type = VIR_JSON_TYPE_STRING;
453
    if (VIR_STRDUP(val->data.string, data) < 0) {
454 455 456 457 458 459 460
        VIR_FREE(val);
        return NULL;
    }

    return val;
}

461

462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
virJSONValuePtr
virJSONValueNewStringLen(const char *data,
                         size_t length)
{
    virJSONValuePtr val;

    if (!data)
        return virJSONValueNewNull();

    if (VIR_ALLOC(val) < 0)
        return NULL;

    val->type = VIR_JSON_TYPE_STRING;
    if (VIR_STRNDUP(val->data.string, data, length) < 0) {
        VIR_FREE(val);
        return NULL;
    }

    return val;
}


484 485
static virJSONValuePtr
virJSONValueNewNumber(const char *data)
486 487 488 489 490 491 492
{
    virJSONValuePtr val;

    if (VIR_ALLOC(val) < 0)
        return NULL;

    val->type = VIR_JSON_TYPE_NUMBER;
493
    if (VIR_STRDUP(val->data.number, data) < 0) {
494 495 496 497 498 499 500
        VIR_FREE(val);
        return NULL;
    }

    return val;
}

501 502 503

virJSONValuePtr
virJSONValueNewNumberInt(int data)
504
{
505
    g_autofree char *str = NULL;
506 507
    if (virAsprintf(&str, "%i", data) < 0)
        return NULL;
508
    return virJSONValueNewNumber(str);
509 510 511
}


512 513
virJSONValuePtr
virJSONValueNewNumberUint(unsigned int data)
514
{
515
    g_autofree char *str = NULL;
516 517
    if (virAsprintf(&str, "%u", data) < 0)
        return NULL;
518
    return virJSONValueNewNumber(str);
519 520 521
}


522 523
virJSONValuePtr
virJSONValueNewNumberLong(long long data)
524
{
525
    g_autofree char *str = NULL;
526 527
    if (virAsprintf(&str, "%lld", data) < 0)
        return NULL;
528
    return virJSONValueNewNumber(str);
529 530 531
}


532 533
virJSONValuePtr
virJSONValueNewNumberUlong(unsigned long long data)
534
{
535
    g_autofree char *str = NULL;
536 537
    if (virAsprintf(&str, "%llu", data) < 0)
        return NULL;
538
    return virJSONValueNewNumber(str);
539 540 541
}


542 543
virJSONValuePtr
virJSONValueNewNumberDouble(double data)
544
{
545
    g_autofree char *str = NULL;
546
    if (virDoubleToStr(&str, data) < 0)
547
        return NULL;
548
    return virJSONValueNewNumber(str);
549 550 551
}


552 553
virJSONValuePtr
virJSONValueNewBoolean(int boolean_)
554 555 556 557 558 559 560
{
    virJSONValuePtr val;

    if (VIR_ALLOC(val) < 0)
        return NULL;

    val->type = VIR_JSON_TYPE_BOOLEAN;
561
    val->data.boolean = boolean_;
562 563 564 565

    return val;
}

566 567 568

virJSONValuePtr
virJSONValueNewNull(void)
569 570 571 572 573 574 575 576 577 578 579
{
    virJSONValuePtr val;

    if (VIR_ALLOC(val) < 0)
        return NULL;

    val->type = VIR_JSON_TYPE_NULL;

    return val;
}

580 581 582

virJSONValuePtr
virJSONValueNewArray(void)
583 584 585 586 587 588 589 590 591 592 593
{
    virJSONValuePtr val;

    if (VIR_ALLOC(val) < 0)
        return NULL;

    val->type = VIR_JSON_TYPE_ARRAY;

    return val;
}

594 595 596

virJSONValuePtr
virJSONValueNewObject(void)
597 598 599 600 601 602 603 604 605 606 607
{
    virJSONValuePtr val;

    if (VIR_ALLOC(val) < 0)
        return NULL;

    val->type = VIR_JSON_TYPE_OBJECT;

    return val;
}

608

609 610
static int
virJSONValueObjectInsert(virJSONValuePtr object,
611
                         const char *key,
612 613
                         virJSONValuePtr value,
                         bool prepend)
614
{
615 616
    virJSONObjectPair pair = { NULL, value };
    int ret = -1;
617

618 619 620
    if (object->type != VIR_JSON_TYPE_OBJECT) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("expecting JSON object"));
621
        return -1;
622
    }
623

624 625
    if (virJSONValueObjectHasKey(object, key)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, _("duplicate key '%s'"), key);
626
        return -1;
627
    }
628

629
    if (VIR_STRDUP(pair.key, key) < 0)
630 631
        return -1;

632 633 634 635 636 637 638
    if (prepend) {
        ret = VIR_INSERT_ELEMENT(object->data.object.pairs, 0,
                                 object->data.object.npairs, pair);
    } else {
        ret = VIR_APPEND_ELEMENT(object->data.object.pairs,
                                 object->data.object.npairs, pair);
    }
639

640 641
    VIR_FREE(pair.key);
    return ret;
642 643 644
}


645
int
646 647 648 649 650 651 652 653 654 655
virJSONValueObjectAppend(virJSONValuePtr object,
                         const char *key,
                         virJSONValuePtr value)
{
    return virJSONValueObjectInsert(object, key, value, false);
}


static int
virJSONValueObjectInsertString(virJSONValuePtr object,
656
                               const char *key,
657 658
                               const char *value,
                               bool prepend)
659 660 661 662
{
    virJSONValuePtr jvalue = virJSONValueNewString(value);
    if (!jvalue)
        return -1;
663
    if (virJSONValueObjectInsert(object, key, jvalue, prepend) < 0) {
664 665 666 667 668 669
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}

670

671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
int
virJSONValueObjectAppendString(virJSONValuePtr object,
                               const char *key,
                               const char *value)
{
    return virJSONValueObjectInsertString(object, key, value, false);
}


int
virJSONValueObjectPrependString(virJSONValuePtr object,
                                const char *key,
                                const char *value)
{
    return virJSONValueObjectInsertString(object, key, value, true);
}


689 690 691 692
int
virJSONValueObjectAppendNumberInt(virJSONValuePtr object,
                                  const char *key,
                                  int number)
693 694 695 696 697 698 699 700 701 702 703 704
{
    virJSONValuePtr jvalue = virJSONValueNewNumberInt(number);
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}


705 706 707 708
int
virJSONValueObjectAppendNumberUint(virJSONValuePtr object,
                                   const char *key,
                                   unsigned int number)
709 710 711 712 713 714 715 716 717 718 719
{
    virJSONValuePtr jvalue = virJSONValueNewNumberUint(number);
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}

720 721 722 723 724

int
virJSONValueObjectAppendNumberLong(virJSONValuePtr object,
                                   const char *key,
                                   long long number)
725 726 727 728 729 730 731 732 733 734 735
{
    virJSONValuePtr jvalue = virJSONValueNewNumberLong(number);
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}

736 737 738 739 740

int
virJSONValueObjectAppendNumberUlong(virJSONValuePtr object,
                                    const char *key,
                                    unsigned long long number)
741 742 743 744 745 746 747 748 749 750 751
{
    virJSONValuePtr jvalue = virJSONValueNewNumberUlong(number);
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}

752 753 754 755 756

int
virJSONValueObjectAppendNumberDouble(virJSONValuePtr object,
                                     const char *key,
                                     double number)
757 758 759 760 761 762 763 764 765 766 767
{
    virJSONValuePtr jvalue = virJSONValueNewNumberDouble(number);
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}

768 769 770 771 772

int
virJSONValueObjectAppendBoolean(virJSONValuePtr object,
                                const char *key,
                                int boolean_)
773
{
774
    virJSONValuePtr jvalue = virJSONValueNewBoolean(boolean_);
775 776 777 778 779 780 781 782 783
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}

784 785 786 787

int
virJSONValueObjectAppendNull(virJSONValuePtr object,
                             const char *key)
788 789 790 791 792 793 794 795 796 797 798 799
{
    virJSONValuePtr jvalue = virJSONValueNewNull();
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}


800 801 802
int
virJSONValueArrayAppend(virJSONValuePtr array,
                        virJSONValuePtr value)
803
{
804 805
    if (array->type != VIR_JSON_TYPE_ARRAY) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("expecting JSON array"));
806
        return -1;
807
    }
808 809 810 811 812 813 814 815 816 817 818

    if (VIR_REALLOC_N(array->data.array.values,
                      array->data.array.nvalues + 1) < 0)
        return -1;

    array->data.array.values[array->data.array.nvalues] = value;
    array->data.array.nvalues++;

    return 0;
}

819

820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
int
virJSONValueArrayAppendString(virJSONValuePtr object,
                              const char *value)
{
    virJSONValuePtr jvalue = virJSONValueNewString(value);
    if (!jvalue)
        return -1;
    if (virJSONValueArrayAppend(object, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}


835 836 837
int
virJSONValueObjectHasKey(virJSONValuePtr object,
                         const char *key)
838
{
839
    size_t i;
840 841 842 843

    if (object->type != VIR_JSON_TYPE_OBJECT)
        return -1;

844
    for (i = 0; i < object->data.object.npairs; i++) {
845 846 847 848 849 850 851
        if (STREQ(object->data.object.pairs[i].key, key))
            return 1;
    }

    return 0;
}

852 853 854 855

virJSONValuePtr
virJSONValueObjectGet(virJSONValuePtr object,
                      const char *key)
856
{
857
    size_t i;
858 859 860 861

    if (object->type != VIR_JSON_TYPE_OBJECT)
        return NULL;

862
    for (i = 0; i < object->data.object.npairs; i++) {
863 864 865 866 867 868 869
        if (STREQ(object->data.object.pairs[i].key, key))
            return object->data.object.pairs[i].value;
    }

    return NULL;
}

870

871 872 873 874 875 876 877 878 879 880 881 882
static virJSONValuePtr
virJSONValueObjectSteal(virJSONValuePtr object,
                        const char *key)
{
    size_t i;
    virJSONValuePtr obj = NULL;

    if (object->type != VIR_JSON_TYPE_OBJECT)
        return NULL;

    for (i = 0; i < object->data.object.npairs; i++) {
        if (STREQ(object->data.object.pairs[i].key, key)) {
883
            obj = g_steal_pointer(&object->data.object.pairs[i].value);
884 885 886 887 888 889 890 891 892 893 894
            VIR_FREE(object->data.object.pairs[i].key);
            VIR_DELETE_ELEMENT(object->data.object.pairs, i,
                               object->data.object.npairs);
            break;
        }
    }

    return obj;
}


895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
/* Return the value associated with KEY within OBJECT, but return NULL
 * if the key is missing or if value is not the correct TYPE.  */
virJSONValuePtr
virJSONValueObjectGetByType(virJSONValuePtr object,
                            const char *key,
                            virJSONType type)
{
    virJSONValuePtr value = virJSONValueObjectGet(object, key);

    if (value && value->type == type)
        return value;
    return NULL;
}


910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
/* Steal the value associated with KEY within OBJECT, but return NULL
 * if the key is missing or if value is not the correct TYPE.  */
static virJSONValuePtr
virJSONValueObjectStealByType(virJSONValuePtr object,
                              const char *key,
                              virJSONType type)
{
    virJSONValuePtr value = virJSONValueObjectSteal(object, key);

    if (value && value->type == type)
        return value;
    return NULL;
}


925 926
int
virJSONValueObjectKeysNumber(virJSONValuePtr object)
927 928 929 930 931 932 933
{
    if (object->type != VIR_JSON_TYPE_OBJECT)
        return -1;

    return object->data.object.npairs;
}

934 935 936 937

const char *
virJSONValueObjectGetKey(virJSONValuePtr object,
                         unsigned int n)
938 939 940 941 942 943 944 945 946 947
{
    if (object->type != VIR_JSON_TYPE_OBJECT)
        return NULL;

    if (n >= object->data.object.npairs)
        return NULL;

    return object->data.object.pairs[n].key;
}

948

949 950 951 952
/* Remove the key-value pair tied to @key out of @object.  If @value is
 * not NULL, the dropped value object is returned instead of freed.
 * Returns 1 on success, 0 if no key was found, and -1 on error.  */
int
953 954
virJSONValueObjectRemoveKey(virJSONValuePtr object,
                            const char *key,
955 956
                            virJSONValuePtr *value)
{
957
    size_t i;
958 959 960 961 962 963 964

    if (value)
        *value = NULL;

    if (object->type != VIR_JSON_TYPE_OBJECT)
        return -1;

965
    for (i = 0; i < object->data.object.npairs; i++) {
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
        if (STREQ(object->data.object.pairs[i].key, key)) {
            if (value) {
                *value = object->data.object.pairs[i].value;
                object->data.object.pairs[i].value = NULL;
            }
            VIR_FREE(object->data.object.pairs[i].key);
            virJSONValueFree(object->data.object.pairs[i].value);
            VIR_DELETE_ELEMENT(object->data.object.pairs, i,
                               object->data.object.npairs);
            return 1;
        }
    }

    return 0;
}

982 983 984 985

virJSONValuePtr
virJSONValueObjectGetValue(virJSONValuePtr object,
                           unsigned int n)
986 987 988 989 990 991 992 993 994 995
{
    if (object->type != VIR_JSON_TYPE_OBJECT)
        return NULL;

    if (n >= object->data.object.npairs)
        return NULL;

    return object->data.object.pairs[n].value;
}

996

997 998 999 1000 1001 1002 1003 1004 1005 1006
bool
virJSONValueIsObject(virJSONValuePtr object)
{
    if (object)
        return object->type == VIR_JSON_TYPE_OBJECT;
    else
        return false;
}


1007 1008 1009 1010 1011 1012 1013
bool
virJSONValueIsArray(virJSONValuePtr array)
{
    return array->type == VIR_JSON_TYPE_ARRAY;
}


1014
size_t
1015
virJSONValueArraySize(const virJSONValue *array)
1016 1017 1018 1019 1020
{
    return array->data.array.nvalues;
}


1021 1022 1023
virJSONValuePtr
virJSONValueArrayGet(virJSONValuePtr array,
                     unsigned int element)
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
{
    if (array->type != VIR_JSON_TYPE_ARRAY)
        return NULL;

    if (element >= array->data.array.nvalues)
        return NULL;

    return array->data.array.values[element];
}

1034

1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
virJSONValuePtr
virJSONValueArraySteal(virJSONValuePtr array,
                       unsigned int element)
{
    virJSONValuePtr ret = NULL;

    if (array->type != VIR_JSON_TYPE_ARRAY)
        return NULL;

    if (element >= array->data.array.nvalues)
        return NULL;

    ret = array->data.array.values[element];

    VIR_DELETE_ELEMENT(array->data.array.values,
                       element,
                       array->data.array.nvalues);

    return ret;
}


1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
/**
 * virJSONValueArrayForeachSteal:
 * @array: array to iterate
 * @cb: callback called on every member of the array
 * @opaque: custom data for the callback
 *
 * Iterates members of the array and calls the callback on every single member.
 * The return codes of the callback are interpreted as follows:
 *  0: callback claims ownership of the array element and is responsible for
 *     freeing it
 *  1: callback doesn't claim ownership of the element
 * -1: callback doesn't claim ownership of the element and iteration does not
 *     continue
 *
 * Returns 0 if all members were iterated and/or stolen by the callback; -1
 * on callback failure or if the JSON value object is not an array.
 * The rest of the members stay in possession of the array and it's condensed.
 */
int
virJSONValueArrayForeachSteal(virJSONValuePtr array,
                              virJSONArrayIteratorFunc cb,
                              void *opaque)
{
    size_t i;
    size_t j = 0;
    int ret = 0;
    int rc;

    if (array->type != VIR_JSON_TYPE_ARRAY)
        return -1;

    for (i = 0; i < array->data.array.nvalues; i++) {
        if ((rc = cb(i, array->data.array.values[i], opaque)) < 0) {
            ret = -1;
            break;
        }

        if (rc == 0)
            array->data.array.values[i] = NULL;
    }

    /* condense the remaining entries at the beginning */
    for (i = 0; i < array->data.array.nvalues; i++) {
        if (!array->data.array.values[i])
            continue;

        array->data.array.values[j++] = array->data.array.values[i];
    }

    array->data.array.nvalues = j;

    return ret;
}


1112 1113
const char *
virJSONValueGetString(virJSONValuePtr string)
1114 1115 1116 1117 1118 1119 1120 1121
{
    if (string->type != VIR_JSON_TYPE_STRING)
        return NULL;

    return string->data.string;
}


1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
const char *
virJSONValueGetNumberString(virJSONValuePtr number)
{
    if (number->type != VIR_JSON_TYPE_NUMBER)
        return NULL;

    return number->data.number;
}


1132 1133 1134
int
virJSONValueGetNumberInt(virJSONValuePtr number,
                         int *value)
1135 1136 1137 1138 1139 1140 1141
{
    if (number->type != VIR_JSON_TYPE_NUMBER)
        return -1;

    return virStrToLong_i(number->data.number, NULL, 10, value);
}

1142 1143 1144 1145

int
virJSONValueGetNumberUint(virJSONValuePtr number,
                          unsigned int *value)
1146 1147 1148 1149 1150 1151 1152
{
    if (number->type != VIR_JSON_TYPE_NUMBER)
        return -1;

    return virStrToLong_ui(number->data.number, NULL, 10, value);
}

1153 1154 1155 1156

int
virJSONValueGetNumberLong(virJSONValuePtr number,
                          long long *value)
1157 1158 1159 1160 1161 1162 1163
{
    if (number->type != VIR_JSON_TYPE_NUMBER)
        return -1;

    return virStrToLong_ll(number->data.number, NULL, 10, value);
}

1164 1165 1166 1167

int
virJSONValueGetNumberUlong(virJSONValuePtr number,
                           unsigned long long *value)
1168 1169 1170 1171 1172 1173 1174
{
    if (number->type != VIR_JSON_TYPE_NUMBER)
        return -1;

    return virStrToLong_ull(number->data.number, NULL, 10, value);
}

1175 1176 1177 1178

int
virJSONValueGetNumberDouble(virJSONValuePtr number,
                            double *value)
1179 1180 1181 1182 1183 1184 1185 1186
{
    if (number->type != VIR_JSON_TYPE_NUMBER)
        return -1;

    return virStrToDouble(number->data.number, NULL, value);
}


1187 1188 1189
int
virJSONValueGetBoolean(virJSONValuePtr val,
                       bool *value)
1190
{
J
Jiri Denemark 已提交
1191
    if (val->type != VIR_JSON_TYPE_BOOLEAN)
1192 1193
        return -1;

J
Jiri Denemark 已提交
1194 1195
    *value = val->data.boolean;
    return 0;
1196 1197 1198
}


1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
/**
 * virJSONValueGetArrayAsBitmap:
 * @val: JSON array to convert to bitmap
 * @bitmap: New bitmap is allocated filled and returned via this argument
 *
 * Attempts a conversion of a JSON array to a bitmap. The members of the array
 * must be non-negative integers for the conversion to succeed. This function
 * does not report libvirt errors so that it can be used to probe that the
 * array can be represented as a bitmap.
 *
 * Returns 0 on success and fills @bitmap; -1 on error and  @bitmap is set to
 * NULL.
 */
int
virJSONValueGetArrayAsBitmap(const virJSONValue *val,
                             virBitmapPtr *bitmap)
{
    virJSONValuePtr elem;
    size_t i;
1218
    g_autofree unsigned long long *elems = NULL;
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
    unsigned long long maxelem = 0;

    *bitmap = NULL;

    if (val->type != VIR_JSON_TYPE_ARRAY)
        return -1;

    if (VIR_ALLOC_N_QUIET(elems, val->data.array.nvalues) < 0)
        return -1;

    /* first pass converts array members to numbers and finds the maximum */
    for (i = 0; i < val->data.array.nvalues; i++) {
        elem = val->data.array.values[i];

        if (elem->type != VIR_JSON_TYPE_NUMBER ||
            virStrToLong_ullp(elem->data.number, NULL, 10, &elems[i]) < 0)
1235
            return -1;
1236 1237 1238 1239 1240 1241

        if (elems[i] > maxelem)
            maxelem = elems[i];
    }

    if (!(*bitmap = virBitmapNewQuiet(maxelem + 1)))
1242
        return -1;
1243 1244 1245 1246 1247

    /* second pass sets the correct bits in the map */
    for (i = 0; i < val->data.array.nvalues; i++)
        ignore_value(virBitmapSetBit(*bitmap, elems[i]));

1248
    return 0;
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
}


virJSONValuePtr
virJSONValueNewArrayFromBitmap(virBitmapPtr bitmap)
{
    virJSONValuePtr ret;
    ssize_t pos = -1;

    if (!(ret = virJSONValueNewArray()))
        return NULL;

    if (!bitmap)
        return ret;

    while ((pos = virBitmapNextSetBit(bitmap, pos)) > -1) {
        virJSONValuePtr newelem;

        if (!(newelem = virJSONValueNewNumberLong(pos)) ||
            virJSONValueArrayAppend(ret, newelem) < 0) {
            virJSONValueFree(newelem);
            goto error;
        }
    }

    return ret;

 error:
    virJSONValueFree(ret);
    return NULL;
}


1282
bool
1283
virJSONValueIsNull(virJSONValuePtr val)
1284
{
1285
    return val->type == VIR_JSON_TYPE_NULL;
1286 1287 1288
}


1289 1290 1291
const char *
virJSONValueObjectGetString(virJSONValuePtr object,
                            const char *key)
1292
{
1293
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1294 1295 1296 1297 1298 1299 1300 1301

    if (!val)
        return NULL;

    return virJSONValueGetString(val);
}


1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
/**
 * virJSONValueObjectGetStringOrNumber:
 * @object: JSON value object
 * @key: name of the property in @object to get
 *
 * Gets a property named @key from the JSON object @object. The value may be
 * a number or a string and is returned as a string. In cases when the property
 * is not present or is not a string or number NULL is returned.
 */
const char *
virJSONValueObjectGetStringOrNumber(virJSONValuePtr object,
                                    const char *key)
{
    virJSONValuePtr val = virJSONValueObjectGet(object, key);

    if (!val)
        return NULL;

    if (val->type == VIR_JSON_TYPE_STRING)
        return val->data.string;
    else if (val->type == VIR_JSON_TYPE_NUMBER)
        return val->data.number;

    return NULL;
}


1329 1330 1331 1332
int
virJSONValueObjectGetNumberInt(virJSONValuePtr object,
                               const char *key,
                               int *value)
1333
{
1334
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1335 1336 1337 1338 1339 1340 1341 1342

    if (!val)
        return -1;

    return virJSONValueGetNumberInt(val, value);
}


1343 1344 1345 1346
int
virJSONValueObjectGetNumberUint(virJSONValuePtr object,
                                const char *key,
                                unsigned int *value)
1347
{
1348
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1349 1350 1351 1352 1353 1354 1355 1356

    if (!val)
        return -1;

    return virJSONValueGetNumberUint(val, value);
}


1357 1358 1359 1360
int
virJSONValueObjectGetNumberLong(virJSONValuePtr object,
                                const char *key,
                                long long *value)
1361
{
1362
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1363 1364 1365 1366 1367 1368 1369 1370

    if (!val)
        return -1;

    return virJSONValueGetNumberLong(val, value);
}


1371 1372 1373 1374
int
virJSONValueObjectGetNumberUlong(virJSONValuePtr object,
                                 const char *key,
                                 unsigned long long *value)
1375
{
1376
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1377 1378 1379 1380 1381 1382 1383 1384

    if (!val)
        return -1;

    return virJSONValueGetNumberUlong(val, value);
}


1385 1386 1387 1388
int
virJSONValueObjectGetNumberDouble(virJSONValuePtr object,
                                  const char *key,
                                  double *value)
1389
{
1390
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1391 1392 1393 1394 1395 1396 1397 1398

    if (!val)
        return -1;

    return virJSONValueGetNumberDouble(val, value);
}


1399 1400 1401 1402
int
virJSONValueObjectGetBoolean(virJSONValuePtr object,
                             const char *key,
                             bool *value)
1403
{
1404
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1405 1406 1407 1408

    if (!val)
        return -1;

J
Jiri Denemark 已提交
1409
    return virJSONValueGetBoolean(val, value);
1410 1411 1412
}


1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
virJSONValuePtr
virJSONValueObjectGetObject(virJSONValuePtr object, const char *key)
{
    return virJSONValueObjectGetByType(object, key, VIR_JSON_TYPE_OBJECT);
}


virJSONValuePtr
virJSONValueObjectGetArray(virJSONValuePtr object, const char *key)
{
    return virJSONValueObjectGetByType(object, key, VIR_JSON_TYPE_ARRAY);
}


1427 1428 1429 1430 1431 1432 1433
virJSONValuePtr
virJSONValueObjectStealArray(virJSONValuePtr object, const char *key)
{
    return virJSONValueObjectStealByType(object, key, VIR_JSON_TYPE_ARRAY);
}


1434 1435 1436 1437 1438 1439 1440 1441
virJSONValuePtr
virJSONValueObjectStealObject(virJSONValuePtr object,
                              const char *key)
{
    return virJSONValueObjectStealByType(object, key, VIR_JSON_TYPE_OBJECT);
}


1442 1443 1444
int
virJSONValueObjectIsNull(virJSONValuePtr object,
                         const char *key)
1445
{
1446
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1447 1448 1449 1450 1451 1452 1453 1454

    if (!val)
        return -1;

    return virJSONValueIsNull(val);
}


1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
/**
 * virJSONValueObjectForeachKeyValue:
 * @object: JSON object to iterate
 * @cb: callback to call on key-value pairs contained in the object
 * @opaque: generic data for the callback
 *
 * Iterates all key=value pairs in @object. Iteration breaks if @cb returns
 * negative value.
 *
 * Returns 0 if all elements were iterated, -2 if @cb returned negative value
 * during iteration and -1 on generic errors.
 */
int
1468
virJSONValueObjectForeachKeyValue(virJSONValuePtr object,
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
                                  virJSONValueObjectIteratorFunc cb,
                                  void *opaque)
{
    size_t i;

    if (object->type != VIR_JSON_TYPE_OBJECT)
        return -1;

    for (i = 0; i < object->data.object.npairs; i++) {
        virJSONObjectPairPtr elem = object->data.object.pairs + i;

        if (cb(elem->key, elem->value, opaque) < 0)
            return -2;
    }

    return 0;
}


M
Martin Kletzander 已提交
1488
virJSONValuePtr
1489
virJSONValueCopy(const virJSONValue *in)
M
Martin Kletzander 已提交
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
{
    size_t i;
    virJSONValuePtr out = NULL;

    if (!in)
        return NULL;

    switch ((virJSONType) in->type) {
    case VIR_JSON_TYPE_OBJECT:
        out = virJSONValueNewObject();
        if (!out)
            return NULL;
        for (i = 0; i < in->data.object.npairs; i++) {
            virJSONValuePtr val = NULL;
            if (!(val = virJSONValueCopy(in->data.object.pairs[i].value)))
                goto error;
            if (virJSONValueObjectAppend(out, in->data.object.pairs[i].key,
                                         val) < 0) {
                virJSONValueFree(val);
                goto error;
            }
        }
        break;
    case VIR_JSON_TYPE_ARRAY:
        out = virJSONValueNewArray();
        if (!out)
            return NULL;
        for (i = 0; i < in->data.array.nvalues; i++) {
            virJSONValuePtr val = NULL;
            if (!(val = virJSONValueCopy(in->data.array.values[i])))
                goto error;
            if (virJSONValueArrayAppend(out, val) < 0) {
                virJSONValueFree(val);
                goto error;
            }
        }
        break;

    /* No need to error out in the following cases */
    case VIR_JSON_TYPE_STRING:
        out = virJSONValueNewString(in->data.string);
        break;
    case VIR_JSON_TYPE_NUMBER:
        out = virJSONValueNewNumber(in->data.number);
        break;
    case VIR_JSON_TYPE_BOOLEAN:
        out = virJSONValueNewBoolean(in->data.boolean);
        break;
    case VIR_JSON_TYPE_NULL:
        out = virJSONValueNewNull();
        break;
    }

    return out;

 error:
    virJSONValueFree(out);
    return NULL;
}


1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646
#if WITH_YAJL
static int
virJSONParserInsertValue(virJSONParserPtr parser,
                         virJSONValuePtr value)
{
    if (!parser->head) {
        parser->head = value;
    } else {
        virJSONParserStatePtr state;
        if (!parser->nstate) {
            VIR_DEBUG("got a value to insert without a container");
            return -1;
        }

        state = &parser->state[parser->nstate-1];

        switch (state->value->type) {
        case VIR_JSON_TYPE_OBJECT: {
            if (!state->key) {
                VIR_DEBUG("missing key when inserting object value");
                return -1;
            }

            if (virJSONValueObjectAppend(state->value,
                                         state->key,
                                         value) < 0)
                return -1;

            VIR_FREE(state->key);
        }   break;

        case VIR_JSON_TYPE_ARRAY: {
            if (state->key) {
                VIR_DEBUG("unexpected key when inserting array value");
                return -1;
            }

            if (virJSONValueArrayAppend(state->value,
                                        value) < 0)
                return -1;
        }   break;

        default:
            VIR_DEBUG("unexpected value type, not a container");
            return -1;
        }
    }

    return 0;
}


static int
virJSONParserHandleNull(void *ctx)
{
    virJSONParserPtr parser = ctx;
    virJSONValuePtr value = virJSONValueNewNull();

    VIR_DEBUG("parser=%p", parser);

    if (!value)
        return 0;

    if (virJSONParserInsertValue(parser, value) < 0) {
        virJSONValueFree(value);
        return 0;
    }

    return 1;
}


static int
virJSONParserHandleBoolean(void *ctx,
                           int boolean_)
{
    virJSONParserPtr parser = ctx;
    virJSONValuePtr value = virJSONValueNewBoolean(boolean_);

    VIR_DEBUG("parser=%p boolean=%d", parser, boolean_);

    if (!value)
        return 0;

    if (virJSONParserInsertValue(parser, value) < 0) {
        virJSONValueFree(value);
        return 0;
    }

    return 1;
}


static int
virJSONParserHandleNumber(void *ctx,
                          const char *s,
J
Ján Tomko 已提交
1647
                          size_t l)
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674
{
    virJSONParserPtr parser = ctx;
    char *str;
    virJSONValuePtr value;

    if (VIR_STRNDUP(str, s, l) < 0)
        return -1;
    value = virJSONValueNewNumber(str);
    VIR_FREE(str);

    VIR_DEBUG("parser=%p str=%s", parser, str);

    if (!value)
        return 0;

    if (virJSONParserInsertValue(parser, value) < 0) {
        virJSONValueFree(value);
        return 0;
    }

    return 1;
}


static int
virJSONParserHandleString(void *ctx,
                          const unsigned char *stringVal,
J
Ján Tomko 已提交
1675
                          size_t stringLen)
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
{
    virJSONParserPtr parser = ctx;
    virJSONValuePtr value = virJSONValueNewStringLen((const char *)stringVal,
                                                     stringLen);

    VIR_DEBUG("parser=%p str=%p", parser, (const char *)stringVal);

    if (!value)
        return 0;

    if (virJSONParserInsertValue(parser, value) < 0) {
        virJSONValueFree(value);
        return 0;
    }

    return 1;
}


static int
virJSONParserHandleMapKey(void *ctx,
                          const unsigned char *stringVal,
J
Ján Tomko 已提交
1698
                          size_t stringLen)
1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
{
    virJSONParserPtr parser = ctx;
    virJSONParserStatePtr state;

    VIR_DEBUG("parser=%p key=%p", parser, (const char *)stringVal);

    if (!parser->nstate)
        return 0;

    state = &parser->state[parser->nstate-1];
    if (state->key)
        return 0;
    if (VIR_STRNDUP(state->key, (const char *)stringVal, stringLen) < 0)
        return 0;
    return 1;
}


static int
virJSONParserHandleStartMap(void *ctx)
{
    virJSONParserPtr parser = ctx;
    virJSONValuePtr value = virJSONValueNewObject();

    VIR_DEBUG("parser=%p", parser);

    if (!value)
        return 0;

    if (virJSONParserInsertValue(parser, value) < 0) {
        virJSONValueFree(value);
        return 0;
    }

    if (VIR_REALLOC_N(parser->state,
                      parser->nstate + 1) < 0) {
        return 0;
    }

    parser->state[parser->nstate].value = value;
    parser->state[parser->nstate].key = NULL;
    parser->nstate++;

    return 1;
}


static int
virJSONParserHandleEndMap(void *ctx)
{
    virJSONParserPtr parser = ctx;
    virJSONParserStatePtr state;

    VIR_DEBUG("parser=%p", parser);

    if (!parser->nstate)
        return 0;

    state = &(parser->state[parser->nstate-1]);
    if (state->key) {
        VIR_FREE(state->key);
        return 0;
    }

    VIR_DELETE_ELEMENT(parser->state, parser->nstate - 1, parser->nstate);

    return 1;
}


static int
virJSONParserHandleStartArray(void *ctx)
{
    virJSONParserPtr parser = ctx;
    virJSONValuePtr value = virJSONValueNewArray();

    VIR_DEBUG("parser=%p", parser);

    if (!value)
        return 0;

    if (virJSONParserInsertValue(parser, value) < 0) {
        virJSONValueFree(value);
        return 0;
    }

    if (VIR_REALLOC_N(parser->state,
                      parser->nstate + 1) < 0)
        return 0;

    parser->state[parser->nstate].value = value;
    parser->state[parser->nstate].key = NULL;
    parser->nstate++;

    return 1;
}


static int
virJSONParserHandleEndArray(void *ctx)
{
    virJSONParserPtr parser = ctx;
    virJSONParserStatePtr state;

    VIR_DEBUG("parser=%p", parser);

    if (!(parser->nstate - parser->wrap))
        return 0;

    state = &(parser->state[parser->nstate-1]);
    if (state->key) {
        VIR_FREE(state->key);
        return 0;
    }

    VIR_DELETE_ELEMENT(parser->state, parser->nstate - 1, parser->nstate);

    return 1;
}


static const yajl_callbacks parserCallbacks = {
    virJSONParserHandleNull,
    virJSONParserHandleBoolean,
    NULL,
    NULL,
    virJSONParserHandleNumber,
    virJSONParserHandleString,
    virJSONParserHandleStartMap,
    virJSONParserHandleMapKey,
    virJSONParserHandleEndMap,
    virJSONParserHandleStartArray,
    virJSONParserHandleEndArray
};


/* XXX add an incremental streaming parser - yajl trivially supports it */
virJSONValuePtr
virJSONValueFromString(const char *jsonstring)
{
    yajl_handle hand;
    virJSONParser parser = { NULL, NULL, 0, 0 };
    virJSONValuePtr ret = NULL;
    int rc;
    size_t len = strlen(jsonstring);

    VIR_DEBUG("string=%s", jsonstring);

    hand = yajl_alloc(&parserCallbacks, NULL, &parser);
    if (!hand) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to create JSON parser"));
        goto cleanup;
    }

J
Ján Tomko 已提交
1854
    /* Yajl 2 is nice enough to default to rejecting trailing garbage. */
1855
    rc = yajl_parse(hand, (const unsigned char *)jsonstring, len);
J
Ján Tomko 已提交
1856
    if (rc != yajl_status_ok ||
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
        yajl_complete_parse(hand) != yajl_status_ok) {
        unsigned char *errstr = yajl_get_error(hand, 1,
                                               (const unsigned char*)jsonstring,
                                               strlen(jsonstring));

        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot parse json %s: %s"),
                       jsonstring, (const char*) errstr);
        yajl_free_error(hand, errstr);
        virJSONValueFree(parser.head);
        goto cleanup;
    }

    if (parser.nstate != 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot parse json %s: unterminated string/map/array"),
                       jsonstring);
        virJSONValueFree(parser.head);
    } else {
        ret = parser.head;
    }

 cleanup:
    yajl_free(hand);

    if (parser.nstate) {
        size_t i;
        for (i = 0; i < parser.nstate; i++)
            VIR_FREE(parser.state[i].key);
        VIR_FREE(parser.state);
    }

    VIR_DEBUG("result=%p", ret);

    return ret;
}


static int
virJSONValueToStringOne(virJSONValuePtr object,
                        yajl_gen g)
{
    size_t i;

    VIR_DEBUG("object=%p type=%d gen=%p", object, object->type, g);

    switch (object->type) {
    case VIR_JSON_TYPE_OBJECT:
        if (yajl_gen_map_open(g) != yajl_gen_status_ok)
            return -1;
        for (i = 0; i < object->data.object.npairs; i++) {
            if (yajl_gen_string(g,
                                (unsigned char *)object->data.object.pairs[i].key,
                                strlen(object->data.object.pairs[i].key))
1911
                != yajl_gen_status_ok)
1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959
                return -1;
            if (virJSONValueToStringOne(object->data.object.pairs[i].value, g) < 0)
                return -1;
        }
        if (yajl_gen_map_close(g) != yajl_gen_status_ok)
            return -1;
        break;
    case VIR_JSON_TYPE_ARRAY:
        if (yajl_gen_array_open(g) != yajl_gen_status_ok)
            return -1;
        for (i = 0; i < object->data.array.nvalues; i++) {
            if (virJSONValueToStringOne(object->data.array.values[i], g) < 0)
                return -1;
        }
        if (yajl_gen_array_close(g) != yajl_gen_status_ok)
            return -1;
        break;

    case VIR_JSON_TYPE_STRING:
        if (yajl_gen_string(g, (unsigned char *)object->data.string,
                            strlen(object->data.string)) != yajl_gen_status_ok)
            return -1;
        break;

    case VIR_JSON_TYPE_NUMBER:
        if (yajl_gen_number(g, object->data.number,
                            strlen(object->data.number)) != yajl_gen_status_ok)
            return -1;
        break;

    case VIR_JSON_TYPE_BOOLEAN:
        if (yajl_gen_bool(g, object->data.boolean) != yajl_gen_status_ok)
            return -1;
        break;

    case VIR_JSON_TYPE_NULL:
        if (yajl_gen_null(g) != yajl_gen_status_ok)
            return -1;
        break;

    default:
        return -1;
    }

    return 0;
}


1960
int
1961 1962
virJSONValueToBuffer(virJSONValuePtr object,
                     virBufferPtr buf,
1963 1964 1965 1966
                     bool pretty)
{
    yajl_gen g;
    const unsigned char *str;
J
Ján Tomko 已提交
1967
    size_t len;
1968
    int ret = -1;
1969 1970 1971 1972 1973 1974 1975 1976 1977

    VIR_DEBUG("object=%p", object);

    g = yajl_gen_alloc(NULL);
    if (!g) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to create JSON formatter"));
        goto cleanup;
    }
1978 1979 1980
    yajl_gen_config(g, yajl_gen_beautify, pretty ? 1 : 0);
    yajl_gen_config(g, yajl_gen_indent_string, pretty ? "  " : " ");
    yajl_gen_config(g, yajl_gen_validate_utf8, 1);
1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991

    if (virJSONValueToStringOne(object, g) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    if (yajl_gen_get_buf(g, &str, &len) != yajl_gen_status_ok) {
        virReportOOMError();
        goto cleanup;
    }

1992 1993
    virBufferAdd(buf, (const char *) str, len);
    ret = 0;
1994 1995 1996 1997 1998 1999 2000 2001

 cleanup:
    yajl_gen_free(g);

    return ret;
}


2002
#else
2003
virJSONValuePtr
J
Ján Tomko 已提交
2004
virJSONValueFromString(const char *jsonstring G_GNUC_UNUSED)
2005
{
2006 2007
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("No JSON parser implementation is available"));
2008 2009
    return NULL;
}
2010 2011


2012
int
J
Ján Tomko 已提交
2013 2014 2015
virJSONValueToBuffer(virJSONValuePtr object G_GNUC_UNUSED,
                     virBufferPtr buf G_GNUC_UNUSED,
                     bool pretty G_GNUC_UNUSED)
2016
{
2017 2018
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("No JSON parser implementation is available"));
2019
    return -1;
2020 2021
}
#endif
2022 2023


2024 2025 2026 2027
char *
virJSONValueToString(virJSONValuePtr object,
                     bool pretty)
{
2028
    g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
2029 2030 2031 2032

    if (virJSONValueToBuffer(object, &buf, pretty) < 0)
        return NULL;

2033
    return virBufferContentAndReset(&buf);
2034 2035 2036
}


2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052
/**
 * virJSONStringReformat:
 * @jsonstr: string to reformat
 * @pretty: use the pretty formatter
 *
 * Reformats a JSON string by passing it to the parser and then to the
 * formatter. If @pretty is true the JSON is formatted for human eye
 * compatibility.
 *
 * Returns the reformatted JSON string on success; NULL and a libvirt error on
 * failure.
 */
char *
virJSONStringReformat(const char *jsonstr,
                      bool pretty)
{
J
Ján Tomko 已提交
2053
    g_autoptr(virJSONValue) json = NULL;
2054 2055 2056 2057

    if (!(json = virJSONValueFromString(jsonstr)))
        return NULL;

2058
    return virJSONValueToString(json, pretty);
2059
}
2060 2061 2062 2063 2064 2065 2066 2067 2068


static int
virJSONValueObjectDeflattenWorker(const char *key,
                                  virJSONValuePtr value,
                                  void *opaque)
{
    virJSONValuePtr retobj = opaque;
    virJSONValuePtr newval = NULL;
2069 2070 2071 2072
    virJSONValuePtr existobj;
    char **tokens = NULL;
    size_t ntokens = 0;
    int ret = -1;
2073

2074 2075
    /* non-nested keys only need to be copied */
    if (!strchr(key, '.')) {
2076 2077 2078 2079 2080 2081 2082

        if (virJSONValueIsObject(value))
            newval = virJSONValueObjectDeflatten(value);
        else
            newval = virJSONValueCopy(value);

        if (!newval)
2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094
            return -1;

        if (virJSONValueObjectHasKey(retobj, key)) {
            virReportError(VIR_ERR_INVALID_ARG,
                           _("can't deflatten colliding key '%s'"), key);
            goto cleanup;
        }

        if (virJSONValueObjectAppend(retobj, key, newval) < 0)
            goto cleanup;

        return 0;
2095 2096
    }

2097 2098
    if (!(tokens = virStringSplitCount(key, ".", 2, &ntokens)))
        goto cleanup;
2099

2100 2101 2102 2103
    if (ntokens != 2) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid nested value key '%s'"), key);
        goto cleanup;
2104 2105
    }

2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128
    if (!(existobj = virJSONValueObjectGet(retobj, tokens[0]))) {
        if (!(existobj = virJSONValueNewObject()))
            goto cleanup;

        if (virJSONValueObjectAppend(retobj, tokens[0], existobj) < 0)
            goto cleanup;

    } else {
        if (!virJSONValueIsObject(existobj)) {
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("mixing nested objects and values is forbidden in "
                             "JSON deflattening"));
            goto cleanup;
        }
    }

    ret = virJSONValueObjectDeflattenWorker(tokens[1], value, existobj);

 cleanup:
    virStringListFreeCount(tokens, ntokens);
    virJSONValueFree(newval);

    return ret;
2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146
}


/**
 * virJSONValueObjectDeflatten:
 *
 * In some cases it's possible to nest JSON objects by prefixing object members
 * with the parent object name followed by the dot and then the attribute name
 * rather than directly using a nested value object (e.g qemu's JSON
 * pseudo-protocol in backing file definition).
 *
 * This function will attempt to reverse the process and provide a nested json
 * hierarchy so that the parsers can be kept simple and we still can use the
 * weird syntax some users might use.
 */
virJSONValuePtr
virJSONValueObjectDeflatten(virJSONValuePtr json)
{
J
Ján Tomko 已提交
2147
    g_autoptr(virJSONValue) deflattened = NULL;
2148
    virJSONValuePtr ret = NULL;
2149

2150
    if (!(deflattened = virJSONValueNewObject()))
2151 2152 2153 2154
        return NULL;

    if (virJSONValueObjectForeachKeyValue(json,
                                          virJSONValueObjectDeflattenWorker,
2155
                                          deflattened) < 0)
2156
        return NULL;
2157

2158
    ret = g_steal_pointer(&deflattened);
2159

2160 2161
    return ret;
}