virjson.c 50.2 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 "virerror.h"
28
#include "virlog.h"
29
#include "virstring.h"
30
#include "virutil.h"
31
#include "virbuffer.h"
32

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

#endif

39 40 41
/* XXX fixme */
#define VIR_FROM_THIS VIR_FROM_NONE

42
VIR_LOG_INIT("util.json");
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
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;
};


82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
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;
};


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


106
/**
107 108 109
 * virJSONValueObjectAddVArgs:
 * @obj: JSON object to add the values to
 * @args: a key-value argument pairs, terminated by NULL
110
 *
111
 * Adds the key-value pairs supplied as variable argument list to @obj.
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
 *
 * 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
136 137
 * T: boolean value specified by a virTristate(Bool|Switch) value, omitted on
 * the _ABSENT value
138 139 140
 *
 * d: double precision floating point number
 * n: json null value
141
 *
142 143
 * 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.
144
 * a: json object, must be non-NULL
145
 * A: json object, omitted if NULL
146
 *
147 148
 * m: a bitmap represented as a JSON array, must be non-NULL
 * M: a bitmap represented as a JSON array, omitted if NULL
149 150 151 152
 *
 * The value corresponds to the selected type.
 *
 * Returns -1 on error. 1 on success, if at least one key:pair was valid 0
153
 * in case of no error but nothing was filled.
154 155
 */
int
156 157
virJSONValueObjectAddVArgs(virJSONValuePtr obj,
                           va_list args)
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
{
    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;
            }
190
            rc = virJSONValueObjectAppendString(obj, key, val);
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
        }   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;

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

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

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

219
            rc = virJSONValueObjectAppendNumberUint(obj, key, val);
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
        }   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;

238
            rc = virJSONValueObjectAppendNumberLong(obj, key, val);
239 240 241 242 243 244 245 246 247 248 249 250 251 252
        }   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;

253
            rc = virJSONValueObjectAppendNumberLong(obj, key, val);
254 255 256 257
        }   break;

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

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

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

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

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

279
            rc = virJSONValueObjectAppendBoolean(obj, key, val);
280 281 282
        }   break;

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

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

290
            if (!(*val)) {
291 292 293
                if (type == 'A')
                    continue;

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

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

304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
        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;

326 327 328 329 330 331 332 333 334 335 336
        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 */
337
    if (virJSONValueObjectKeysNumber(obj) == 0) {
338 339 340 341 342 343 344
        ret = 0;
        goto cleanup;
    }

    ret = 1;

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

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


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

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

    return ret;
}


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

E
Eric Blake 已提交
403
    switch ((virJSONType) value->type) {
404
    case VIR_JSON_TYPE_OBJECT:
405
        for (i = 0; i < value->data.object.npairs; i++) {
406 407 408 409 410 411
            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:
412
        for (i = 0; i < value->data.array.nvalues; i++)
413 414 415 416 417 418 419 420 421
            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 已提交
422 423 424
    case VIR_JSON_TYPE_BOOLEAN:
    case VIR_JSON_TYPE_NULL:
        break;
425
    }
426 427

    VIR_FREE(value);
428 429 430
}


431 432 433 434 435 436 437 438
void
virJSONValueHashFree(void *opaque,
                     const void *name ATTRIBUTE_UNUSED)
{
    virJSONValueFree(opaque);
}


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

    if (!data)
        return virJSONValueNewNull();

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

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

    return val;
}

459

460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
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;
}


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

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

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

    return val;
}

499 500 501

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


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


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


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


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


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

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

    val->type = VIR_JSON_TYPE_BOOLEAN;
559
    val->data.boolean = boolean_;
560 561 562 563

    return val;
}

564 565 566

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

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

    val->type = VIR_JSON_TYPE_NULL;

    return val;
}

578 579 580

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

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

    val->type = VIR_JSON_TYPE_ARRAY;

    return val;
}

592 593 594

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

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

    val->type = VIR_JSON_TYPE_OBJECT;

    return val;
}

606 607 608 609 610

int
virJSONValueObjectAppend(virJSONValuePtr object,
                         const char *key,
                         virJSONValuePtr value)
611 612 613
{
    char *newkey;

614 615 616
    if (object->type != VIR_JSON_TYPE_OBJECT) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("expecting JSON object"));
617
        return -1;
618
    }
619

620 621
    if (virJSONValueObjectHasKey(object, key)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, _("duplicate key '%s'"), key);
622
        return -1;
623
    }
624

625
    if (VIR_STRDUP(newkey, key) < 0)
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
        return -1;

    if (VIR_REALLOC_N(object->data.object.pairs,
                      object->data.object.npairs + 1) < 0) {
        VIR_FREE(newkey);
        return -1;
    }

    object->data.object.pairs[object->data.object.npairs].key = newkey;
    object->data.object.pairs[object->data.object.npairs].value = value;
    object->data.object.npairs++;

    return 0;
}


642 643 644 645
int
virJSONValueObjectAppendString(virJSONValuePtr object,
                               const char *key,
                               const char *value)
646 647 648 649 650 651 652 653 654 655 656
{
    virJSONValuePtr jvalue = virJSONValueNewString(value);
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}

657 658 659 660 661

int
virJSONValueObjectAppendNumberInt(virJSONValuePtr object,
                                  const char *key,
                                  int number)
662 663 664 665 666 667 668 669 670 671 672 673
{
    virJSONValuePtr jvalue = virJSONValueNewNumberInt(number);
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}


674 675 676 677
int
virJSONValueObjectAppendNumberUint(virJSONValuePtr object,
                                   const char *key,
                                   unsigned int number)
678 679 680 681 682 683 684 685 686 687 688
{
    virJSONValuePtr jvalue = virJSONValueNewNumberUint(number);
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}

689 690 691 692 693

int
virJSONValueObjectAppendNumberLong(virJSONValuePtr object,
                                   const char *key,
                                   long long number)
694 695 696 697 698 699 700 701 702 703 704
{
    virJSONValuePtr jvalue = virJSONValueNewNumberLong(number);
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}

705 706 707 708 709

int
virJSONValueObjectAppendNumberUlong(virJSONValuePtr object,
                                    const char *key,
                                    unsigned long long number)
710 711 712 713 714 715 716 717 718 719 720
{
    virJSONValuePtr jvalue = virJSONValueNewNumberUlong(number);
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}

721 722 723 724 725

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

737 738 739 740 741

int
virJSONValueObjectAppendBoolean(virJSONValuePtr object,
                                const char *key,
                                int boolean_)
742
{
743
    virJSONValuePtr jvalue = virJSONValueNewBoolean(boolean_);
744 745 746 747 748 749 750 751 752
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}

753 754 755 756

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


769 770 771
int
virJSONValueArrayAppend(virJSONValuePtr array,
                        virJSONValuePtr value)
772
{
773 774
    if (array->type != VIR_JSON_TYPE_ARRAY) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("expecting JSON array"));
775
        return -1;
776
    }
777 778 779 780 781 782 783 784 785 786 787

    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;
}

788

789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
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;
}


804 805 806
int
virJSONValueObjectHasKey(virJSONValuePtr object,
                         const char *key)
807
{
808
    size_t i;
809 810 811 812

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

813
    for (i = 0; i < object->data.object.npairs; i++) {
814 815 816 817 818 819 820
        if (STREQ(object->data.object.pairs[i].key, key))
            return 1;
    }

    return 0;
}

821 822 823 824

virJSONValuePtr
virJSONValueObjectGet(virJSONValuePtr object,
                      const char *key)
825
{
826
    size_t i;
827 828 829 830

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

831
    for (i = 0; i < object->data.object.npairs; i++) {
832 833 834 835 836 837 838
        if (STREQ(object->data.object.pairs[i].key, key))
            return object->data.object.pairs[i].value;
    }

    return NULL;
}

839

840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
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)) {
            VIR_STEAL_PTR(obj, object->data.object.pairs[i].value);
            VIR_FREE(object->data.object.pairs[i].key);
            VIR_DELETE_ELEMENT(object->data.object.pairs, i,
                               object->data.object.npairs);
            break;
        }
    }

    return obj;
}


864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
/* 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;
}


879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
/* 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;
}


894 895
int
virJSONValueObjectKeysNumber(virJSONValuePtr object)
896 897 898 899 900 901 902
{
    if (object->type != VIR_JSON_TYPE_OBJECT)
        return -1;

    return object->data.object.npairs;
}

903 904 905 906

const char *
virJSONValueObjectGetKey(virJSONValuePtr object,
                         unsigned int n)
907 908 909 910 911 912 913 914 915 916
{
    if (object->type != VIR_JSON_TYPE_OBJECT)
        return NULL;

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

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

917

918 919 920 921
/* 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
922 923
virJSONValueObjectRemoveKey(virJSONValuePtr object,
                            const char *key,
924 925
                            virJSONValuePtr *value)
{
926
    size_t i;
927 928 929 930 931 932 933

    if (value)
        *value = NULL;

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

934
    for (i = 0; i < object->data.object.npairs; i++) {
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
        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;
}

951 952 953 954

virJSONValuePtr
virJSONValueObjectGetValue(virJSONValuePtr object,
                           unsigned int n)
955 956 957 958 959 960 961 962 963 964
{
    if (object->type != VIR_JSON_TYPE_OBJECT)
        return NULL;

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

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

965

966 967 968 969 970 971 972 973 974 975
bool
virJSONValueIsObject(virJSONValuePtr object)
{
    if (object)
        return object->type == VIR_JSON_TYPE_OBJECT;
    else
        return false;
}


976 977 978 979 980 981 982
bool
virJSONValueIsArray(virJSONValuePtr array)
{
    return array->type == VIR_JSON_TYPE_ARRAY;
}


983
size_t
984
virJSONValueArraySize(const virJSONValue *array)
985 986 987 988 989
{
    return array->data.array.nvalues;
}


990 991 992
virJSONValuePtr
virJSONValueArrayGet(virJSONValuePtr array,
                     unsigned int element)
993 994 995 996 997 998 999 1000 1001 1002
{
    if (array->type != VIR_JSON_TYPE_ARRAY)
        return NULL;

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

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

1003

1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
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;
}


1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
/**
 * 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;
}


1081 1082
const char *
virJSONValueGetString(virJSONValuePtr string)
1083 1084 1085 1086 1087 1088 1089 1090
{
    if (string->type != VIR_JSON_TYPE_STRING)
        return NULL;

    return string->data.string;
}


1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
const char *
virJSONValueGetNumberString(virJSONValuePtr number)
{
    if (number->type != VIR_JSON_TYPE_NUMBER)
        return NULL;

    return number->data.number;
}


1101 1102 1103
int
virJSONValueGetNumberInt(virJSONValuePtr number,
                         int *value)
1104 1105 1106 1107 1108 1109 1110
{
    if (number->type != VIR_JSON_TYPE_NUMBER)
        return -1;

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

1111 1112 1113 1114

int
virJSONValueGetNumberUint(virJSONValuePtr number,
                          unsigned int *value)
1115 1116 1117 1118 1119 1120 1121
{
    if (number->type != VIR_JSON_TYPE_NUMBER)
        return -1;

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

1122 1123 1124 1125

int
virJSONValueGetNumberLong(virJSONValuePtr number,
                          long long *value)
1126 1127 1128 1129 1130 1131 1132
{
    if (number->type != VIR_JSON_TYPE_NUMBER)
        return -1;

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

1133 1134 1135 1136

int
virJSONValueGetNumberUlong(virJSONValuePtr number,
                           unsigned long long *value)
1137 1138 1139 1140 1141 1142 1143
{
    if (number->type != VIR_JSON_TYPE_NUMBER)
        return -1;

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

1144 1145 1146 1147

int
virJSONValueGetNumberDouble(virJSONValuePtr number,
                            double *value)
1148 1149 1150 1151 1152 1153 1154 1155
{
    if (number->type != VIR_JSON_TYPE_NUMBER)
        return -1;

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


1156 1157 1158
int
virJSONValueGetBoolean(virJSONValuePtr val,
                       bool *value)
1159
{
J
Jiri Denemark 已提交
1160
    if (val->type != VIR_JSON_TYPE_BOOLEAN)
1161 1162
        return -1;

J
Jiri Denemark 已提交
1163 1164
    *value = val->data.boolean;
    return 0;
1165 1166 1167
}


1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
/**
 * 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;
1187
    VIR_AUTOFREE(unsigned long long *) elems = NULL;
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
    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)
1204
            return -1;
1205 1206 1207 1208 1209 1210

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

    if (!(*bitmap = virBitmapNewQuiet(maxelem + 1)))
1211
        return -1;
1212 1213 1214 1215 1216

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

1217
    return 0;
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
}


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;
}


1251
bool
1252
virJSONValueIsNull(virJSONValuePtr val)
1253
{
1254
    return val->type == VIR_JSON_TYPE_NULL;
1255 1256 1257
}


1258 1259 1260
const char *
virJSONValueObjectGetString(virJSONValuePtr object,
                            const char *key)
1261
{
1262
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1263 1264 1265 1266 1267 1268 1269 1270

    if (!val)
        return NULL;

    return virJSONValueGetString(val);
}


1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
/**
 * 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;
}


1298 1299 1300 1301
int
virJSONValueObjectGetNumberInt(virJSONValuePtr object,
                               const char *key,
                               int *value)
1302
{
1303
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1304 1305 1306 1307 1308 1309 1310 1311

    if (!val)
        return -1;

    return virJSONValueGetNumberInt(val, value);
}


1312 1313 1314 1315
int
virJSONValueObjectGetNumberUint(virJSONValuePtr object,
                                const char *key,
                                unsigned int *value)
1316
{
1317
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1318 1319 1320 1321 1322 1323 1324 1325

    if (!val)
        return -1;

    return virJSONValueGetNumberUint(val, value);
}


1326 1327 1328 1329
int
virJSONValueObjectGetNumberLong(virJSONValuePtr object,
                                const char *key,
                                long long *value)
1330
{
1331
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1332 1333 1334 1335 1336 1337 1338 1339

    if (!val)
        return -1;

    return virJSONValueGetNumberLong(val, value);
}


1340 1341 1342 1343
int
virJSONValueObjectGetNumberUlong(virJSONValuePtr object,
                                 const char *key,
                                 unsigned long long *value)
1344
{
1345
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1346 1347 1348 1349 1350 1351 1352 1353

    if (!val)
        return -1;

    return virJSONValueGetNumberUlong(val, value);
}


1354 1355 1356 1357
int
virJSONValueObjectGetNumberDouble(virJSONValuePtr object,
                                  const char *key,
                                  double *value)
1358
{
1359
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1360 1361 1362 1363 1364 1365 1366 1367

    if (!val)
        return -1;

    return virJSONValueGetNumberDouble(val, value);
}


1368 1369 1370 1371
int
virJSONValueObjectGetBoolean(virJSONValuePtr object,
                             const char *key,
                             bool *value)
1372
{
1373
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1374 1375 1376 1377

    if (!val)
        return -1;

J
Jiri Denemark 已提交
1378
    return virJSONValueGetBoolean(val, value);
1379 1380 1381
}


1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
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);
}


1396 1397 1398 1399 1400 1401 1402
virJSONValuePtr
virJSONValueObjectStealArray(virJSONValuePtr object, const char *key)
{
    return virJSONValueObjectStealByType(object, key, VIR_JSON_TYPE_ARRAY);
}


1403 1404 1405 1406 1407 1408 1409 1410
virJSONValuePtr
virJSONValueObjectStealObject(virJSONValuePtr object,
                              const char *key)
{
    return virJSONValueObjectStealByType(object, key, VIR_JSON_TYPE_OBJECT);
}


1411 1412 1413
int
virJSONValueObjectIsNull(virJSONValuePtr object,
                         const char *key)
1414
{
1415
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1416 1417 1418 1419 1420 1421 1422 1423

    if (!val)
        return -1;

    return virJSONValueIsNull(val);
}


1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
/**
 * 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
1437
virJSONValueObjectForeachKeyValue(virJSONValuePtr object,
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
                                  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 已提交
1457
virJSONValuePtr
1458
virJSONValueCopy(const virJSONValue *in)
M
Martin Kletzander 已提交
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 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
{
    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;
}


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 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
#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 已提交
1616
                          size_t l)
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
{
    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 已提交
1644
                          size_t stringLen)
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
{
    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 已提交
1667
                          size_t stringLen)
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 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
{
    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 已提交
1823
    /* Yajl 2 is nice enough to default to rejecting trailing garbage. */
1824
    rc = yajl_parse(hand, (const unsigned char *)jsonstring, len);
J
Ján Tomko 已提交
1825
    if (rc != yajl_status_ok ||
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 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879
        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))
1880
                != yajl_gen_status_ok)
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 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928
                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;
}


1929
int
1930 1931
virJSONValueToBuffer(virJSONValuePtr object,
                     virBufferPtr buf,
1932 1933 1934 1935
                     bool pretty)
{
    yajl_gen g;
    const unsigned char *str;
J
Ján Tomko 已提交
1936
    size_t len;
1937
    int ret = -1;
1938 1939 1940 1941 1942 1943 1944 1945 1946

    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;
    }
1947 1948 1949
    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);
1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960

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

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

1961 1962
    virBufferAdd(buf, (const char *) str, len);
    ret = 0;
1963 1964 1965 1966 1967 1968 1969 1970

 cleanup:
    yajl_gen_free(g);

    return ret;
}


1971
#else
1972 1973
virJSONValuePtr
virJSONValueFromString(const char *jsonstring ATTRIBUTE_UNUSED)
1974
{
1975 1976
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("No JSON parser implementation is available"));
1977 1978
    return NULL;
}
1979 1980


1981
int
1982 1983
virJSONValueToBuffer(virJSONValuePtr object ATTRIBUTE_UNUSED,
                     virBufferPtr buf ATTRIBUTE_UNUSED,
1984
                     bool pretty ATTRIBUTE_UNUSED)
1985
{
1986 1987
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("No JSON parser implementation is available"));
1988
    return -1;
1989 1990
}
#endif
1991 1992


1993 1994 1995 1996 1997 1998 1999 2000 2001
char *
virJSONValueToString(virJSONValuePtr object,
                     bool pretty)
{
    VIR_AUTOCLEAN(virBuffer) buf = VIR_BUFFER_INITIALIZER;

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

2002
    return virBufferContentAndReset(&buf);
2003 2004 2005
}


2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021
/**
 * 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)
{
2022
    VIR_AUTOPTR(virJSONValue) json = NULL;
2023 2024 2025 2026

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

2027
    return virJSONValueToString(json, pretty);
2028
}
2029 2030 2031 2032 2033 2034 2035 2036 2037


static int
virJSONValueObjectDeflattenWorker(const char *key,
                                  virJSONValuePtr value,
                                  void *opaque)
{
    virJSONValuePtr retobj = opaque;
    virJSONValuePtr newval = NULL;
2038 2039 2040 2041
    virJSONValuePtr existobj;
    char **tokens = NULL;
    size_t ntokens = 0;
    int ret = -1;
2042

2043 2044
    /* non-nested keys only need to be copied */
    if (!strchr(key, '.')) {
2045 2046 2047 2048 2049 2050 2051

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

        if (!newval)
2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063
            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;
2064 2065
    }

2066 2067
    if (!(tokens = virStringSplitCount(key, ".", 2, &ntokens)))
        goto cleanup;
2068

2069 2070 2071 2072
    if (ntokens != 2) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid nested value key '%s'"), key);
        goto cleanup;
2073 2074
    }

2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097
    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;
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115
}


/**
 * 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)
{
2116
    VIR_AUTOPTR(virJSONValue) deflattened = NULL;
2117
    virJSONValuePtr ret = NULL;
2118

2119
    if (!(deflattened = virJSONValueNewObject()))
2120 2121 2122 2123
        return NULL;

    if (virJSONValueObjectForeachKeyValue(json,
                                          virJSONValueObjectDeflattenWorker,
2124
                                          deflattened) < 0)
2125
        return NULL;
2126

2127
    VIR_STEAL_PTR(ret, deflattened);
2128

2129 2130
    return ret;
}