virjson.c 35.3 KB
Newer Older
1
/*
2
 * virjson.c: JSON object parsing/formatting
3
 *
4
 * Copyright (C) 2009-2010, 2012-2013 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

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

37
# ifdef WITH_YAJL2
38 39 40 41 42
#  define yajl_size_t size_t
# else
#  define yajl_size_t unsigned int
# endif

43
#endif
44 45 46 47

/* XXX fixme */
#define VIR_FROM_THIS VIR_FROM_NONE

48
VIR_LOG_INIT("util.json");
49 50 51 52 53 54 55 56 57 58 59 60 61

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;
62
    size_t nstate;
63 64 65
};


66
/**
67 68 69
 * virJSONValueObjectAddVArgs:
 * @obj: JSON object to add the values to
 * @args: a key-value argument pairs, terminated by NULL
70
 *
71
 * Adds the key-value pairs supplied as variable argument list to @obj.
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
 *
 * 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
 *
 * d: double precision floating point number
 * n: json null value
99 100
 *
 * a: json object, must be non-NULL
101
 * A: json object, omitted if NULL
102 103 104 105
 *
 * The value corresponds to the selected type.
 *
 * Returns -1 on error. 1 on success, if at least one key:pair was valid 0
106
 * in case of no error but nothing was filled.
107 108
 */
int
109 110
virJSONValueObjectAddVArgs(virJSONValuePtr obj,
                           va_list args)
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
{
    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;
            }
143
            rc = virJSONValueObjectAppendString(obj, key, val);
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
        }   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;

162
            rc = virJSONValueObjectAppendNumberInt(obj, key, val);
163 164 165 166 167 168 169 170 171
        }   break;

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

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

172
            rc = virJSONValueObjectAppendNumberUint(obj, key, val);
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
        }   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;

191
            rc = virJSONValueObjectAppendNumberLong(obj, key, val);
192 193 194 195 196 197 198 199 200 201 202 203 204 205
        }   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;

206
            rc = virJSONValueObjectAppendNumberLong(obj, key, val);
207 208 209 210
        }   break;

        case 'd': {
            double val = va_arg(args, double);
211
            rc = virJSONValueObjectAppendNumberDouble(obj, key, val);
212 213 214 215 216 217 218 219 220
        }   break;

        case 'B':
        case 'b': {
            int val = va_arg(args, int);

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

221
            rc = virJSONValueObjectAppendBoolean(obj, key, val);
222 223 224
        }   break;

        case 'n': {
225
            rc = virJSONValueObjectAppendNull(obj, key);
226 227
        }   break;

228
        case 'A':
229 230
        case 'a': {
            virJSONValuePtr val = va_arg(args, virJSONValuePtr);
231 232

            if (!val) {
233 234 235
                if (type == 'A')
                    continue;

236 237 238 239 240 241
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("argument key '%s' must not have null value"),
                               key);
                goto cleanup;
            }

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

        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 */
256
    if (virJSONValueObjectKeysNumber(obj) == 0) {
257 258 259 260 261 262 263
        ret = 0;
        goto cleanup;
    }

    ret = 1;

 cleanup:
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
    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;
    }

297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
    return ret;
}


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

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

    return ret;
}


315 316
void
virJSONValueFree(virJSONValuePtr value)
317
{
318
    size_t i;
E
Eric Blake 已提交
319
    if (!value || value->protect)
320 321
        return;

E
Eric Blake 已提交
322
    switch ((virJSONType) value->type) {
323
    case VIR_JSON_TYPE_OBJECT:
324
        for (i = 0; i < value->data.object.npairs; i++) {
325 326 327 328 329 330
            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:
331
        for (i = 0; i < value->data.array.nvalues; i++)
332 333 334 335 336 337 338 339 340
            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 已提交
341 342 343
    case VIR_JSON_TYPE_BOOLEAN:
    case VIR_JSON_TYPE_NULL:
        break;
344
    }
345 346

    VIR_FREE(value);
347 348 349
}


350 351
virJSONValuePtr
virJSONValueNewString(const char *data)
352 353 354 355 356 357 358 359 360 361
{
    virJSONValuePtr val;

    if (!data)
        return virJSONValueNewNull();

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

    val->type = VIR_JSON_TYPE_STRING;
362
    if (VIR_STRDUP(val->data.string, data) < 0) {
363 364 365 366 367 368 369
        VIR_FREE(val);
        return NULL;
    }

    return val;
}

370 371 372 373

virJSONValuePtr
virJSONValueNewStringLen(const char *data,
                         size_t length)
374 375 376 377 378 379 380 381 382 383
{
    virJSONValuePtr val;

    if (!data)
        return virJSONValueNewNull();

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

    val->type = VIR_JSON_TYPE_STRING;
384
    if (VIR_STRNDUP(val->data.string, data, length) < 0) {
385 386 387 388 389 390 391
        VIR_FREE(val);
        return NULL;
    }

    return val;
}

392 393 394

static virJSONValuePtr
virJSONValueNewNumber(const char *data)
395 396 397 398 399 400 401
{
    virJSONValuePtr val;

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

    val->type = VIR_JSON_TYPE_NUMBER;
402
    if (VIR_STRDUP(val->data.number, data) < 0) {
403 404 405 406 407 408 409
        VIR_FREE(val);
        return NULL;
    }

    return val;
}

410 411 412

virJSONValuePtr
virJSONValueNewNumberInt(int data)
413 414 415 416 417 418 419 420 421 422 423
{
    virJSONValuePtr val = NULL;
    char *str;
    if (virAsprintf(&str, "%i", data) < 0)
        return NULL;
    val = virJSONValueNewNumber(str);
    VIR_FREE(str);
    return val;
}


424 425
virJSONValuePtr
virJSONValueNewNumberUint(unsigned int data)
426 427 428 429 430 431 432 433 434 435 436
{
    virJSONValuePtr val = NULL;
    char *str;
    if (virAsprintf(&str, "%u", data) < 0)
        return NULL;
    val = virJSONValueNewNumber(str);
    VIR_FREE(str);
    return val;
}


437 438
virJSONValuePtr
virJSONValueNewNumberLong(long long data)
439 440 441 442 443 444 445 446 447 448 449
{
    virJSONValuePtr val = NULL;
    char *str;
    if (virAsprintf(&str, "%lld", data) < 0)
        return NULL;
    val = virJSONValueNewNumber(str);
    VIR_FREE(str);
    return val;
}


450 451
virJSONValuePtr
virJSONValueNewNumberUlong(unsigned long long data)
452 453 454 455 456 457 458 459 460 461 462
{
    virJSONValuePtr val = NULL;
    char *str;
    if (virAsprintf(&str, "%llu", data) < 0)
        return NULL;
    val = virJSONValueNewNumber(str);
    VIR_FREE(str);
    return val;
}


463 464
virJSONValuePtr
virJSONValueNewNumberDouble(double data)
465 466 467
{
    virJSONValuePtr val = NULL;
    char *str;
468
    if (virDoubleToStr(&str, data) < 0)
469 470 471 472 473 474 475
        return NULL;
    val = virJSONValueNewNumber(str);
    VIR_FREE(str);
    return val;
}


476 477
virJSONValuePtr
virJSONValueNewBoolean(int boolean_)
478 479 480 481 482 483 484
{
    virJSONValuePtr val;

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

    val->type = VIR_JSON_TYPE_BOOLEAN;
485
    val->data.boolean = boolean_;
486 487 488 489

    return val;
}

490 491 492

virJSONValuePtr
virJSONValueNewNull(void)
493 494 495 496 497 498 499 500 501 502 503
{
    virJSONValuePtr val;

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

    val->type = VIR_JSON_TYPE_NULL;

    return val;
}

504 505 506

virJSONValuePtr
virJSONValueNewArray(void)
507 508 509 510 511 512 513 514 515 516 517
{
    virJSONValuePtr val;

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

    val->type = VIR_JSON_TYPE_ARRAY;

    return val;
}

518 519 520

virJSONValuePtr
virJSONValueNewObject(void)
521 522 523 524 525 526 527 528 529 530 531
{
    virJSONValuePtr val;

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

    val->type = VIR_JSON_TYPE_OBJECT;

    return val;
}

532 533 534 535 536

int
virJSONValueObjectAppend(virJSONValuePtr object,
                         const char *key,
                         virJSONValuePtr value)
537 538 539 540 541 542 543 544 545
{
    char *newkey;

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

    if (virJSONValueObjectHasKey(object, key))
        return -1;

546
    if (VIR_STRDUP(newkey, key) < 0)
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
        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;
}


563 564 565 566
int
virJSONValueObjectAppendString(virJSONValuePtr object,
                               const char *key,
                               const char *value)
567 568 569 570 571 572 573 574 575 576 577
{
    virJSONValuePtr jvalue = virJSONValueNewString(value);
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}

578 579 580 581 582

int
virJSONValueObjectAppendNumberInt(virJSONValuePtr object,
                                  const char *key,
                                  int number)
583 584 585 586 587 588 589 590 591 592 593 594
{
    virJSONValuePtr jvalue = virJSONValueNewNumberInt(number);
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}


595 596 597 598
int
virJSONValueObjectAppendNumberUint(virJSONValuePtr object,
                                   const char *key,
                                   unsigned int number)
599 600 601 602 603 604 605 606 607 608 609
{
    virJSONValuePtr jvalue = virJSONValueNewNumberUint(number);
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}

610 611 612 613 614

int
virJSONValueObjectAppendNumberLong(virJSONValuePtr object,
                                   const char *key,
                                   long long number)
615 616 617 618 619 620 621 622 623 624 625
{
    virJSONValuePtr jvalue = virJSONValueNewNumberLong(number);
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}

626 627 628 629 630

int
virJSONValueObjectAppendNumberUlong(virJSONValuePtr object,
                                    const char *key,
                                    unsigned long long number)
631 632 633 634 635 636 637 638 639 640 641
{
    virJSONValuePtr jvalue = virJSONValueNewNumberUlong(number);
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}

642 643 644 645 646

int
virJSONValueObjectAppendNumberDouble(virJSONValuePtr object,
                                     const char *key,
                                     double number)
647 648 649 650 651 652 653 654 655 656 657
{
    virJSONValuePtr jvalue = virJSONValueNewNumberDouble(number);
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}

658 659 660 661 662

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

674 675 676 677

int
virJSONValueObjectAppendNull(virJSONValuePtr object,
                             const char *key)
678 679 680 681 682 683 684 685 686 687 688 689
{
    virJSONValuePtr jvalue = virJSONValueNewNull();
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}


690 691 692
int
virJSONValueArrayAppend(virJSONValuePtr array,
                        virJSONValuePtr value)
693 694 695 696 697 698 699 700 701 702 703 704 705 706
{
    if (array->type != VIR_JSON_TYPE_ARRAY)
        return -1;

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

707 708 709 710

int
virJSONValueObjectHasKey(virJSONValuePtr object,
                         const char *key)
711
{
712
    size_t i;
713 714 715 716

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

717
    for (i = 0; i < object->data.object.npairs; i++) {
718 719 720 721 722 723 724
        if (STREQ(object->data.object.pairs[i].key, key))
            return 1;
    }

    return 0;
}

725 726 727 728

virJSONValuePtr
virJSONValueObjectGet(virJSONValuePtr object,
                      const char *key)
729
{
730
    size_t i;
731 732 733 734

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

735
    for (i = 0; i < object->data.object.npairs; i++) {
736 737 738 739 740 741 742
        if (STREQ(object->data.object.pairs[i].key, key))
            return object->data.object.pairs[i].value;
    }

    return NULL;
}

743 744 745

int
virJSONValueObjectKeysNumber(virJSONValuePtr object)
746 747 748 749 750 751 752
{
    if (object->type != VIR_JSON_TYPE_OBJECT)
        return -1;

    return object->data.object.npairs;
}

753 754 755 756

const char *
virJSONValueObjectGetKey(virJSONValuePtr object,
                         unsigned int n)
757 758 759 760 761 762 763 764 765 766
{
    if (object->type != VIR_JSON_TYPE_OBJECT)
        return NULL;

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

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

767

768 769 770 771
/* 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
772 773
virJSONValueObjectRemoveKey(virJSONValuePtr object,
                            const char *key,
774 775
                            virJSONValuePtr *value)
{
776
    size_t i;
777 778 779 780 781 782 783

    if (value)
        *value = NULL;

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

784
    for (i = 0; i < object->data.object.npairs; i++) {
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
        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;
}

801 802 803 804

virJSONValuePtr
virJSONValueObjectGetValue(virJSONValuePtr object,
                           unsigned int n)
805 806 807 808 809 810 811 812 813 814
{
    if (object->type != VIR_JSON_TYPE_OBJECT)
        return NULL;

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

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

815

816 817 818 819 820 821 822
bool
virJSONValueIsArray(virJSONValuePtr array)
{
    return array->type == VIR_JSON_TYPE_ARRAY;
}


823
int
824
virJSONValueArraySize(const virJSONValue *array)
825 826 827 828 829 830 831 832
{
    if (array->type != VIR_JSON_TYPE_ARRAY)
        return -1;

    return array->data.array.nvalues;
}


833 834 835
virJSONValuePtr
virJSONValueArrayGet(virJSONValuePtr array,
                     unsigned int element)
836 837 838 839 840 841 842 843 844 845
{
    if (array->type != VIR_JSON_TYPE_ARRAY)
        return NULL;

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

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

846

847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
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;
}


869 870
const char *
virJSONValueGetString(virJSONValuePtr string)
871 872 873 874 875 876 877 878
{
    if (string->type != VIR_JSON_TYPE_STRING)
        return NULL;

    return string->data.string;
}


879 880 881
int
virJSONValueGetNumberInt(virJSONValuePtr number,
                         int *value)
882 883 884 885 886 887 888
{
    if (number->type != VIR_JSON_TYPE_NUMBER)
        return -1;

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

889 890 891 892

int
virJSONValueGetNumberUint(virJSONValuePtr number,
                          unsigned int *value)
893 894 895 896 897 898 899
{
    if (number->type != VIR_JSON_TYPE_NUMBER)
        return -1;

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

900 901 902 903

int
virJSONValueGetNumberLong(virJSONValuePtr number,
                          long long *value)
904 905 906 907 908 909 910
{
    if (number->type != VIR_JSON_TYPE_NUMBER)
        return -1;

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

911 912 913 914

int
virJSONValueGetNumberUlong(virJSONValuePtr number,
                           unsigned long long *value)
915 916 917 918 919 920 921
{
    if (number->type != VIR_JSON_TYPE_NUMBER)
        return -1;

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

922 923 924 925

int
virJSONValueGetNumberDouble(virJSONValuePtr number,
                            double *value)
926 927 928 929 930 931 932 933
{
    if (number->type != VIR_JSON_TYPE_NUMBER)
        return -1;

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


934 935 936
int
virJSONValueGetBoolean(virJSONValuePtr val,
                       bool *value)
937
{
J
Jiri Denemark 已提交
938
    if (val->type != VIR_JSON_TYPE_BOOLEAN)
939 940
        return -1;

J
Jiri Denemark 已提交
941 942
    *value = val->data.boolean;
    return 0;
943 944 945
}


946 947
int
virJSONValueIsNull(virJSONValuePtr val)
948 949 950 951 952 953 954 955
{
    if (val->type != VIR_JSON_TYPE_NULL)
        return 0;

    return 1;
}


956 957 958
const char *
virJSONValueObjectGetString(virJSONValuePtr object,
                            const char *key)
959 960 961 962 963 964 965 966 967 968 969 970 971
{
    virJSONValuePtr val;
    if (object->type != VIR_JSON_TYPE_OBJECT)
        return NULL;

    val = virJSONValueObjectGet(object, key);
    if (!val)
        return NULL;

    return virJSONValueGetString(val);
}


972 973 974 975
int
virJSONValueObjectGetNumberInt(virJSONValuePtr object,
                               const char *key,
                               int *value)
976 977 978 979 980 981 982 983 984 985 986 987 988
{
    virJSONValuePtr val;
    if (object->type != VIR_JSON_TYPE_OBJECT)
        return -1;

    val = virJSONValueObjectGet(object, key);
    if (!val)
        return -1;

    return virJSONValueGetNumberInt(val, value);
}


989 990 991 992
int
virJSONValueObjectGetNumberUint(virJSONValuePtr object,
                                const char *key,
                                unsigned int *value)
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
{
    virJSONValuePtr val;
    if (object->type != VIR_JSON_TYPE_OBJECT)
        return -1;

    val = virJSONValueObjectGet(object, key);
    if (!val)
        return -1;

    return virJSONValueGetNumberUint(val, value);
}


1006 1007 1008 1009
int
virJSONValueObjectGetNumberLong(virJSONValuePtr object,
                                const char *key,
                                long long *value)
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
{
    virJSONValuePtr val;
    if (object->type != VIR_JSON_TYPE_OBJECT)
        return -1;

    val = virJSONValueObjectGet(object, key);
    if (!val)
        return -1;

    return virJSONValueGetNumberLong(val, value);
}


1023 1024 1025 1026
int
virJSONValueObjectGetNumberUlong(virJSONValuePtr object,
                                 const char *key,
                                 unsigned long long *value)
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
{
    virJSONValuePtr val;
    if (object->type != VIR_JSON_TYPE_OBJECT)
        return -1;

    val = virJSONValueObjectGet(object, key);
    if (!val)
        return -1;

    return virJSONValueGetNumberUlong(val, value);
}


1040 1041 1042 1043
int
virJSONValueObjectGetNumberDouble(virJSONValuePtr object,
                                  const char *key,
                                  double *value)
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
{
    virJSONValuePtr val;
    if (object->type != VIR_JSON_TYPE_OBJECT)
        return -1;

    val = virJSONValueObjectGet(object, key);
    if (!val)
        return -1;

    return virJSONValueGetNumberDouble(val, value);
}


1057 1058 1059 1060
int
virJSONValueObjectGetBoolean(virJSONValuePtr object,
                             const char *key,
                             bool *value)
1061 1062 1063 1064 1065 1066 1067 1068 1069
{
    virJSONValuePtr val;
    if (object->type != VIR_JSON_TYPE_OBJECT)
        return -1;

    val = virJSONValueObjectGet(object, key);
    if (!val)
        return -1;

J
Jiri Denemark 已提交
1070
    return virJSONValueGetBoolean(val, value);
1071 1072 1073
}


1074 1075 1076
int
virJSONValueObjectIsNull(virJSONValuePtr object,
                         const char *key)
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
{
    virJSONValuePtr val;
    if (object->type != VIR_JSON_TYPE_OBJECT)
        return -1;

    val = virJSONValueObjectGet(object, key);
    if (!val)
        return -1;

    return virJSONValueIsNull(val);
}


1090
#if WITH_YAJL
1091 1092 1093
static int
virJSONParserInsertValue(virJSONParserPtr parser,
                         virJSONValuePtr value)
1094 1095 1096 1097 1098 1099
{
    if (!parser->head) {
        parser->head = value;
    } else {
        virJSONParserStatePtr state;
        if (!parser->nstate) {
1100
            VIR_DEBUG("got a value to insert without a container");
1101 1102 1103 1104 1105 1106 1107 1108
            return -1;
        }

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

        switch (state->value->type) {
        case VIR_JSON_TYPE_OBJECT: {
            if (!state->key) {
1109
                VIR_DEBUG("missing key when inserting object value");
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
                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) {
1123
                VIR_DEBUG("unexpected key when inserting array value");
1124 1125 1126 1127 1128 1129 1130 1131 1132
                return -1;
            }

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

        default:
1133
            VIR_DEBUG("unexpected value type, not a container");
1134 1135 1136 1137 1138 1139 1140
            return -1;
        }
    }

    return 0;
}

1141 1142 1143

static int
virJSONParserHandleNull(void *ctx)
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
{
    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;
}

1161 1162 1163 1164

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

1169
    VIR_DEBUG("parser=%p boolean=%d", parser, boolean_);
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181

    if (!value)
        return 0;

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

    return 1;
}

1182 1183 1184 1185 1186

static int
virJSONParserHandleNumber(void *ctx,
                          const char *s,
                          yajl_size_t l)
1187 1188
{
    virJSONParserPtr parser = ctx;
1189
    char *str;
1190 1191
    virJSONValuePtr value;

1192
    if (VIR_STRNDUP(str, s, l) < 0)
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
        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;
}

1210 1211 1212 1213 1214

static int
virJSONParserHandleString(void *ctx,
                          const unsigned char *stringVal,
                          yajl_size_t stringLen)
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
{
    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;
}

1233 1234 1235 1236 1237

static int
virJSONParserHandleMapKey(void *ctx,
                          const unsigned char *stringVal,
                          yajl_size_t stringLen)
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
{
    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;
1250
    if (VIR_STRNDUP(state->key, (const char *)stringVal, stringLen) < 0)
1251 1252 1253 1254
        return 0;
    return 1;
}

1255 1256 1257

static int
virJSONParserHandleStartMap(void *ctx)
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
{
    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,
1273
                      parser->nstate + 1) < 0) {
1274
        return 0;
1275
    }
1276 1277 1278 1279 1280 1281 1282 1283 1284

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

    return 1;
}


1285 1286
static int
virJSONParserHandleEndMap(void *ctx)
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
{
    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;
    }

1302
    VIR_DELETE_ELEMENT(parser->state, parser->nstate - 1, parser->nstate);
1303 1304 1305 1306

    return 1;
}

1307 1308 1309

static int
virJSONParserHandleStartArray(void *ctx)
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
{
    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;
}

1335 1336 1337

static int
virJSONParserHandleEndArray(void *ctx)
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
{
    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;
    }

1353
    VIR_DELETE_ELEMENT(parser->state, parser->nstate - 1, parser->nstate);
1354 1355 1356 1357

    return 1;
}

1358

1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
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 */
1375 1376
virJSONValuePtr
virJSONValueFromString(const char *jsonstring)
1377 1378 1379
{
    yajl_handle hand;
    virJSONParser parser = { NULL, NULL, 0 };
1380
    virJSONValuePtr ret = NULL;
1381
# ifndef WITH_YAJL2
1382 1383
    yajl_parser_config cfg = { 1, 1 };
# endif
1384 1385 1386

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

1387
# ifdef WITH_YAJL2
1388 1389 1390 1391 1392 1393
    hand = yajl_alloc(&parserCallbacks, NULL, &parser);
    if (hand) {
        yajl_config(hand, yajl_allow_comments, 1);
        yajl_config(hand, yajl_dont_validate_strings, 0);
    }
# else
1394
    hand = yajl_alloc(&parserCallbacks, &cfg, NULL, &parser);
1395 1396
# endif
    if (!hand) {
1397 1398
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to create JSON parser"));
1399 1400
        goto cleanup;
    }
1401 1402 1403 1404 1405 1406 1407 1408

    if (yajl_parse(hand,
                   (const unsigned char *)jsonstring,
                   strlen(jsonstring)) != yajl_status_ok) {
        unsigned char *errstr = yajl_get_error(hand, 1,
                                               (const unsigned char*)jsonstring,
                                               strlen(jsonstring));

1409 1410 1411
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot parse json %s: %s"),
                       jsonstring, (const char*) errstr);
1412 1413 1414 1415 1416
        VIR_FREE(errstr);
        virJSONValueFree(parser.head);
        goto cleanup;
    }

1417 1418 1419 1420 1421 1422 1423 1424
    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;
    }
1425

1426
 cleanup:
1427 1428 1429
    yajl_free(hand);

    if (parser.nstate) {
1430
        size_t i;
J
Ján Tomko 已提交
1431
        for (i = 0; i < parser.nstate; i++)
1432
            VIR_FREE(parser.state[i].key);
1433
        VIR_FREE(parser.state);
1434 1435 1436 1437
    }

    VIR_DEBUG("result=%p", parser.head);

1438
    return ret;
1439 1440 1441
}


1442 1443 1444
static int
virJSONValueToStringOne(virJSONValuePtr object,
                        yajl_gen g)
1445
{
1446
    size_t i;
1447 1448 1449 1450 1451 1452 1453

    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;
1454
        for (i = 0; i < object->data.object.npairs; i++) {
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
            if (yajl_gen_string(g,
                                (unsigned char *)object->data.object.pairs[i].key,
                                strlen(object->data.object.pairs[i].key))
                                != yajl_gen_status_ok)
                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;
1469
        for (i = 0; i < object->data.array.nvalues; i++) {
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
            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;
}

1506 1507 1508 1509

char *
virJSONValueToString(virJSONValuePtr object,
                     bool pretty)
1510 1511 1512 1513
{
    yajl_gen g;
    const unsigned char *str;
    char *ret = NULL;
1514
    yajl_size_t len;
1515
# ifndef WITH_YAJL2
1516
    yajl_gen_config conf = { pretty ? 1 : 0, pretty ? "    " : " "};
1517
# endif
1518 1519 1520

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

1521
# ifdef WITH_YAJL2
1522 1523
    g = yajl_gen_alloc(NULL);
    if (g) {
1524 1525
        yajl_gen_config(g, yajl_gen_beautify, pretty ? 1 : 0);
        yajl_gen_config(g, yajl_gen_indent_string, pretty ? "    " : " ");
1526 1527 1528
        yajl_gen_config(g, yajl_gen_validate_utf8, 1);
    }
# else
1529
    g = yajl_gen_alloc(&conf, NULL);
1530 1531
# endif
    if (!g) {
1532 1533
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to create JSON formatter"));
1534 1535
        goto cleanup;
    }
1536 1537

    if (virJSONValueToStringOne(object, g) < 0) {
1538
        virReportOOMError();
1539 1540 1541 1542
        goto cleanup;
    }

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

1547
    ignore_value(VIR_STRDUP(ret, (const char *)str));
1548

1549
 cleanup:
1550 1551 1552 1553 1554 1555 1556 1557 1558
    yajl_gen_free(g);

    VIR_DEBUG("result=%s", NULLSTR(ret));

    return ret;
}


#else
1559 1560
virJSONValuePtr
virJSONValueFromString(const char *jsonstring ATTRIBUTE_UNUSED)
1561
{
1562 1563
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("No JSON parser implementation is available"));
1564 1565
    return NULL;
}
1566 1567 1568 1569 1570


char *
virJSONValueToString(virJSONValuePtr object ATTRIBUTE_UNUSED,
                     bool pretty ATTRIBUTE_UNUSED)
1571
{
1572 1573
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("No JSON parser implementation is available"));
1574 1575 1576
    return NULL;
}
#endif