virjson.c 42.3 KB
Newer Older
1
/*
2
 * virjson.c: JSON object parsing/formatting
3
 *
M
Martin Kletzander 已提交
4
 * Copyright (C) 2009-2010, 2012-2015 Red Hat, Inc.
5
 * Copyright (C) 2009 Daniel P. Berrange
6 7 8 9 10 11 12 13 14 15 16 17
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
20 21 22 23 24 25
 *
 */


#include <config.h>

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

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

37
# ifdef WITH_YAJL2
38
#  define yajl_size_t size_t
39
#  define VIR_YAJL_STATUS_OK(status) ((status) == yajl_status_ok)
40 41
# else
#  define yajl_size_t unsigned int
E
Eric Blake 已提交
42
#  define yajl_complete_parse yajl_parse_complete
43 44
#  define VIR_YAJL_STATUS_OK(status) \
    ((status) == yajl_status_ok || (status) == yajl_status_insufficient_data)
45 46
# endif

47
#endif
48 49 50 51

/* XXX fixme */
#define VIR_FROM_THIS VIR_FROM_NONE

52
VIR_LOG_INIT("util.json");
53 54 55 56 57 58 59 60 61 62 63 64 65

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;
66
    size_t nstate;
67
    int wrap;
68 69 70
};


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

169
            rc = virJSONValueObjectAppendNumberInt(obj, key, val);
170 171 172 173 174 175 176 177 178
        }   break;

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

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

179
            rc = virJSONValueObjectAppendNumberUint(obj, key, val);
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
        }   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;

198
            rc = virJSONValueObjectAppendNumberLong(obj, key, val);
199 200 201 202 203 204 205 206 207 208 209 210 211 212
        }   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;

213
            rc = virJSONValueObjectAppendNumberLong(obj, key, val);
214 215 216 217
        }   break;

        case 'd': {
            double val = va_arg(args, double);
218
            rc = virJSONValueObjectAppendNumberDouble(obj, key, val);
219 220 221 222 223 224 225 226 227
        }   break;

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

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

228
            rc = virJSONValueObjectAppendBoolean(obj, key, val);
229 230 231
        }   break;

        case 'n': {
232
            rc = virJSONValueObjectAppendNull(obj, key);
233 234
        }   break;

235
        case 'A':
236 237
        case 'a': {
            virJSONValuePtr val = va_arg(args, virJSONValuePtr);
238 239

            if (!val) {
240 241 242
                if (type == 'A')
                    continue;

243 244 245 246 247 248
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("argument key '%s' must not have null value"),
                               key);
                goto cleanup;
            }

249
            rc = virJSONValueObjectAppend(obj, key, val);
250 251
        }   break;

252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
        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;

274 275 276 277 278 279 280 281 282 283 284
        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 */
285
    if (virJSONValueObjectKeysNumber(obj) == 0) {
286 287 288 289 290 291 292
        ret = 0;
        goto cleanup;
    }

    ret = 1;

 cleanup:
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
    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;
    }

326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
    return ret;
}


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

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

    return ret;
}


344 345
void
virJSONValueFree(virJSONValuePtr value)
346
{
347
    size_t i;
E
Eric Blake 已提交
348
    if (!value || value->protect)
349 350
        return;

E
Eric Blake 已提交
351
    switch ((virJSONType) value->type) {
352
    case VIR_JSON_TYPE_OBJECT:
353
        for (i = 0; i < value->data.object.npairs; i++) {
354 355 356 357 358 359
            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:
360
        for (i = 0; i < value->data.array.nvalues; i++)
361 362 363 364 365 366 367 368 369
            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 已提交
370 371 372
    case VIR_JSON_TYPE_BOOLEAN:
    case VIR_JSON_TYPE_NULL:
        break;
373
    }
374 375

    VIR_FREE(value);
376 377 378
}


379 380
virJSONValuePtr
virJSONValueNewString(const char *data)
381 382 383 384 385 386 387 388 389 390
{
    virJSONValuePtr val;

    if (!data)
        return virJSONValueNewNull();

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

    val->type = VIR_JSON_TYPE_STRING;
391
    if (VIR_STRDUP(val->data.string, data) < 0) {
392 393 394 395 396 397 398
        VIR_FREE(val);
        return NULL;
    }

    return val;
}

399 400 401 402

virJSONValuePtr
virJSONValueNewStringLen(const char *data,
                         size_t length)
403 404 405 406 407 408 409 410 411 412
{
    virJSONValuePtr val;

    if (!data)
        return virJSONValueNewNull();

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

    val->type = VIR_JSON_TYPE_STRING;
413
    if (VIR_STRNDUP(val->data.string, data, length) < 0) {
414 415 416 417 418 419 420
        VIR_FREE(val);
        return NULL;
    }

    return val;
}

421 422 423

static virJSONValuePtr
virJSONValueNewNumber(const char *data)
424 425 426 427 428 429 430
{
    virJSONValuePtr val;

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

    val->type = VIR_JSON_TYPE_NUMBER;
431
    if (VIR_STRDUP(val->data.number, data) < 0) {
432 433 434 435 436 437 438
        VIR_FREE(val);
        return NULL;
    }

    return val;
}

439 440 441

virJSONValuePtr
virJSONValueNewNumberInt(int data)
442 443 444 445 446 447 448 449 450 451 452
{
    virJSONValuePtr val = NULL;
    char *str;
    if (virAsprintf(&str, "%i", data) < 0)
        return NULL;
    val = virJSONValueNewNumber(str);
    VIR_FREE(str);
    return val;
}


453 454
virJSONValuePtr
virJSONValueNewNumberUint(unsigned int data)
455 456 457 458 459 460 461 462 463 464 465
{
    virJSONValuePtr val = NULL;
    char *str;
    if (virAsprintf(&str, "%u", data) < 0)
        return NULL;
    val = virJSONValueNewNumber(str);
    VIR_FREE(str);
    return val;
}


466 467
virJSONValuePtr
virJSONValueNewNumberLong(long long data)
468 469 470 471 472 473 474 475 476 477 478
{
    virJSONValuePtr val = NULL;
    char *str;
    if (virAsprintf(&str, "%lld", data) < 0)
        return NULL;
    val = virJSONValueNewNumber(str);
    VIR_FREE(str);
    return val;
}


479 480
virJSONValuePtr
virJSONValueNewNumberUlong(unsigned long long data)
481 482 483 484 485 486 487 488 489 490 491
{
    virJSONValuePtr val = NULL;
    char *str;
    if (virAsprintf(&str, "%llu", data) < 0)
        return NULL;
    val = virJSONValueNewNumber(str);
    VIR_FREE(str);
    return val;
}


492 493
virJSONValuePtr
virJSONValueNewNumberDouble(double data)
494 495 496
{
    virJSONValuePtr val = NULL;
    char *str;
497
    if (virDoubleToStr(&str, data) < 0)
498 499 500 501 502 503 504
        return NULL;
    val = virJSONValueNewNumber(str);
    VIR_FREE(str);
    return val;
}


505 506
virJSONValuePtr
virJSONValueNewBoolean(int boolean_)
507 508 509 510 511 512 513
{
    virJSONValuePtr val;

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

    val->type = VIR_JSON_TYPE_BOOLEAN;
514
    val->data.boolean = boolean_;
515 516 517 518

    return val;
}

519 520 521

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

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

    val->type = VIR_JSON_TYPE_NULL;

    return val;
}

533 534 535

virJSONValuePtr
virJSONValueNewArray(void)
536 537 538 539 540 541 542 543 544 545 546
{
    virJSONValuePtr val;

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

    val->type = VIR_JSON_TYPE_ARRAY;

    return val;
}

547 548 549

virJSONValuePtr
virJSONValueNewObject(void)
550 551 552 553 554 555 556 557 558 559 560
{
    virJSONValuePtr val;

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

    val->type = VIR_JSON_TYPE_OBJECT;

    return val;
}

561 562 563 564 565

int
virJSONValueObjectAppend(virJSONValuePtr object,
                         const char *key,
                         virJSONValuePtr value)
566 567 568 569 570 571 572 573 574
{
    char *newkey;

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

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

575
    if (VIR_STRDUP(newkey, key) < 0)
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
        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;
}


592 593 594 595
int
virJSONValueObjectAppendString(virJSONValuePtr object,
                               const char *key,
                               const char *value)
596 597 598 599 600 601 602 603 604 605 606
{
    virJSONValuePtr jvalue = virJSONValueNewString(value);
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}

607 608 609 610 611

int
virJSONValueObjectAppendNumberInt(virJSONValuePtr object,
                                  const char *key,
                                  int number)
612 613 614 615 616 617 618 619 620 621 622 623
{
    virJSONValuePtr jvalue = virJSONValueNewNumberInt(number);
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}


624 625 626 627
int
virJSONValueObjectAppendNumberUint(virJSONValuePtr object,
                                   const char *key,
                                   unsigned int number)
628 629 630 631 632 633 634 635 636 637 638
{
    virJSONValuePtr jvalue = virJSONValueNewNumberUint(number);
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}

639 640 641 642 643

int
virJSONValueObjectAppendNumberLong(virJSONValuePtr object,
                                   const char *key,
                                   long long number)
644 645 646 647 648 649 650 651 652 653 654
{
    virJSONValuePtr jvalue = virJSONValueNewNumberLong(number);
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}

655 656 657 658 659

int
virJSONValueObjectAppendNumberUlong(virJSONValuePtr object,
                                    const char *key,
                                    unsigned long long number)
660 661 662 663 664 665 666 667 668 669 670
{
    virJSONValuePtr jvalue = virJSONValueNewNumberUlong(number);
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}

671 672 673 674 675

int
virJSONValueObjectAppendNumberDouble(virJSONValuePtr object,
                                     const char *key,
                                     double number)
676 677 678 679 680 681 682 683 684 685 686
{
    virJSONValuePtr jvalue = virJSONValueNewNumberDouble(number);
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}

687 688 689 690 691

int
virJSONValueObjectAppendBoolean(virJSONValuePtr object,
                                const char *key,
                                int boolean_)
692
{
693
    virJSONValuePtr jvalue = virJSONValueNewBoolean(boolean_);
694 695 696 697 698 699 700 701 702
    if (!jvalue)
        return -1;
    if (virJSONValueObjectAppend(object, key, jvalue) < 0) {
        virJSONValueFree(jvalue);
        return -1;
    }
    return 0;
}

703 704 705 706

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


719 720 721
int
virJSONValueArrayAppend(virJSONValuePtr array,
                        virJSONValuePtr value)
722 723 724 725 726 727 728 729 730 731 732 733 734 735
{
    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;
}

736 737 738 739

int
virJSONValueObjectHasKey(virJSONValuePtr object,
                         const char *key)
740
{
741
    size_t i;
742 743 744 745

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

746
    for (i = 0; i < object->data.object.npairs; i++) {
747 748 749 750 751 752 753
        if (STREQ(object->data.object.pairs[i].key, key))
            return 1;
    }

    return 0;
}

754 755 756 757

virJSONValuePtr
virJSONValueObjectGet(virJSONValuePtr object,
                      const char *key)
758
{
759
    size_t i;
760 761 762 763

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

764
    for (i = 0; i < object->data.object.npairs; i++) {
765 766 767 768 769 770 771
        if (STREQ(object->data.object.pairs[i].key, key))
            return object->data.object.pairs[i].value;
    }

    return NULL;
}

772

773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
/* 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;
}


788 789
int
virJSONValueObjectKeysNumber(virJSONValuePtr object)
790 791 792 793 794 795 796
{
    if (object->type != VIR_JSON_TYPE_OBJECT)
        return -1;

    return object->data.object.npairs;
}

797 798 799 800

const char *
virJSONValueObjectGetKey(virJSONValuePtr object,
                         unsigned int n)
801 802 803 804 805 806 807 808 809 810
{
    if (object->type != VIR_JSON_TYPE_OBJECT)
        return NULL;

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

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

811

812 813 814 815
/* 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
816 817
virJSONValueObjectRemoveKey(virJSONValuePtr object,
                            const char *key,
818 819
                            virJSONValuePtr *value)
{
820
    size_t i;
821 822 823 824 825 826 827

    if (value)
        *value = NULL;

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

828
    for (i = 0; i < object->data.object.npairs; i++) {
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
        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;
}

845 846 847 848

virJSONValuePtr
virJSONValueObjectGetValue(virJSONValuePtr object,
                           unsigned int n)
849 850 851 852 853 854 855 856 857 858
{
    if (object->type != VIR_JSON_TYPE_OBJECT)
        return NULL;

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

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

859

860 861 862 863 864 865 866
bool
virJSONValueIsArray(virJSONValuePtr array)
{
    return array->type == VIR_JSON_TYPE_ARRAY;
}


867
ssize_t
868
virJSONValueArraySize(const virJSONValue *array)
869 870 871 872 873 874 875 876
{
    if (array->type != VIR_JSON_TYPE_ARRAY)
        return -1;

    return array->data.array.nvalues;
}


877 878 879
virJSONValuePtr
virJSONValueArrayGet(virJSONValuePtr array,
                     unsigned int element)
880 881 882 883 884 885 886 887 888 889
{
    if (array->type != VIR_JSON_TYPE_ARRAY)
        return NULL;

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

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

890

891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
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;
}


913 914
const char *
virJSONValueGetString(virJSONValuePtr string)
915 916 917 918 919 920 921 922
{
    if (string->type != VIR_JSON_TYPE_STRING)
        return NULL;

    return string->data.string;
}


923 924 925
int
virJSONValueGetNumberInt(virJSONValuePtr number,
                         int *value)
926 927 928 929 930 931 932
{
    if (number->type != VIR_JSON_TYPE_NUMBER)
        return -1;

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

933 934 935 936

int
virJSONValueGetNumberUint(virJSONValuePtr number,
                          unsigned int *value)
937 938 939 940 941 942 943
{
    if (number->type != VIR_JSON_TYPE_NUMBER)
        return -1;

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

944 945 946 947

int
virJSONValueGetNumberLong(virJSONValuePtr number,
                          long long *value)
948 949 950 951 952 953 954
{
    if (number->type != VIR_JSON_TYPE_NUMBER)
        return -1;

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

955 956 957 958

int
virJSONValueGetNumberUlong(virJSONValuePtr number,
                           unsigned long long *value)
959 960 961 962 963 964 965
{
    if (number->type != VIR_JSON_TYPE_NUMBER)
        return -1;

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

966 967 968 969

int
virJSONValueGetNumberDouble(virJSONValuePtr number,
                            double *value)
970 971 972 973 974 975 976 977
{
    if (number->type != VIR_JSON_TYPE_NUMBER)
        return -1;

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


978 979 980
int
virJSONValueGetBoolean(virJSONValuePtr val,
                       bool *value)
981
{
J
Jiri Denemark 已提交
982
    if (val->type != VIR_JSON_TYPE_BOOLEAN)
983 984
        return -1;

J
Jiri Denemark 已提交
985 986
    *value = val->data.boolean;
    return 0;
987 988 989
}


990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 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
/**
 * 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)
{
    int ret = -1;
    virJSONValuePtr elem;
    size_t i;
    unsigned long long *elems = NULL;
    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)
            goto cleanup;

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

    if (!(*bitmap = virBitmapNewQuiet(maxelem + 1)))
        goto cleanup;

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

    ret = 0;

 cleanup:
    VIR_FREE(elems);

    return ret;
}


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


1079
bool
1080
virJSONValueIsNull(virJSONValuePtr val)
1081
{
1082
    return val->type == VIR_JSON_TYPE_NULL;
1083 1084 1085
}


1086 1087 1088
const char *
virJSONValueObjectGetString(virJSONValuePtr object,
                            const char *key)
1089
{
1090
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1091 1092 1093 1094 1095 1096 1097 1098

    if (!val)
        return NULL;

    return virJSONValueGetString(val);
}


1099 1100 1101 1102
int
virJSONValueObjectGetNumberInt(virJSONValuePtr object,
                               const char *key,
                               int *value)
1103
{
1104
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1105 1106 1107 1108 1109 1110 1111 1112

    if (!val)
        return -1;

    return virJSONValueGetNumberInt(val, value);
}


1113 1114 1115 1116
int
virJSONValueObjectGetNumberUint(virJSONValuePtr object,
                                const char *key,
                                unsigned int *value)
1117
{
1118
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1119 1120 1121 1122 1123 1124 1125 1126

    if (!val)
        return -1;

    return virJSONValueGetNumberUint(val, value);
}


1127 1128 1129 1130
int
virJSONValueObjectGetNumberLong(virJSONValuePtr object,
                                const char *key,
                                long long *value)
1131
{
1132
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1133 1134 1135 1136 1137 1138 1139 1140

    if (!val)
        return -1;

    return virJSONValueGetNumberLong(val, value);
}


1141 1142 1143 1144
int
virJSONValueObjectGetNumberUlong(virJSONValuePtr object,
                                 const char *key,
                                 unsigned long long *value)
1145
{
1146
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1147 1148 1149 1150 1151 1152 1153 1154

    if (!val)
        return -1;

    return virJSONValueGetNumberUlong(val, value);
}


1155 1156 1157 1158
int
virJSONValueObjectGetNumberDouble(virJSONValuePtr object,
                                  const char *key,
                                  double *value)
1159
{
1160
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1161 1162 1163 1164 1165 1166 1167 1168

    if (!val)
        return -1;

    return virJSONValueGetNumberDouble(val, value);
}


1169 1170 1171 1172
int
virJSONValueObjectGetBoolean(virJSONValuePtr object,
                             const char *key,
                             bool *value)
1173
{
1174
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1175 1176 1177 1178

    if (!val)
        return -1;

J
Jiri Denemark 已提交
1179
    return virJSONValueGetBoolean(val, value);
1180 1181 1182
}


1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
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);
}


1197 1198 1199
int
virJSONValueObjectIsNull(virJSONValuePtr object,
                         const char *key)
1200
{
1201
    virJSONValuePtr val = virJSONValueObjectGet(object, key);
1202 1203 1204 1205 1206 1207 1208 1209

    if (!val)
        return -1;

    return virJSONValueIsNull(val);
}


1210 1211 1212 1213 1214 1215 1216 1217 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
/**
 * 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
virJSONValueObjectForeachKeyValue(virJSONValuePtr object,
                                  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 已提交
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
virJSONValuePtr
virJSONValueCopy(virJSONValuePtr in)
{
    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;
}


1306
#if WITH_YAJL
1307 1308 1309
static int
virJSONParserInsertValue(virJSONParserPtr parser,
                         virJSONValuePtr value)
1310 1311 1312 1313 1314 1315
{
    if (!parser->head) {
        parser->head = value;
    } else {
        virJSONParserStatePtr state;
        if (!parser->nstate) {
1316
            VIR_DEBUG("got a value to insert without a container");
1317 1318 1319 1320 1321 1322 1323 1324
            return -1;
        }

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

        switch (state->value->type) {
        case VIR_JSON_TYPE_OBJECT: {
            if (!state->key) {
1325
                VIR_DEBUG("missing key when inserting object value");
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
                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) {
1339
                VIR_DEBUG("unexpected key when inserting array value");
1340 1341 1342 1343 1344 1345 1346 1347 1348
                return -1;
            }

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

        default:
1349
            VIR_DEBUG("unexpected value type, not a container");
1350 1351 1352 1353 1354 1355 1356
            return -1;
        }
    }

    return 0;
}

1357 1358 1359

static int
virJSONParserHandleNull(void *ctx)
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
{
    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;
}

1377 1378 1379 1380

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

1385
    VIR_DEBUG("parser=%p boolean=%d", parser, boolean_);
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397

    if (!value)
        return 0;

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

    return 1;
}

1398 1399 1400 1401 1402

static int
virJSONParserHandleNumber(void *ctx,
                          const char *s,
                          yajl_size_t l)
1403 1404
{
    virJSONParserPtr parser = ctx;
1405
    char *str;
1406 1407
    virJSONValuePtr value;

1408
    if (VIR_STRNDUP(str, s, l) < 0)
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
        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;
}

1426 1427 1428 1429 1430

static int
virJSONParserHandleString(void *ctx,
                          const unsigned char *stringVal,
                          yajl_size_t stringLen)
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
{
    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;
}

1449 1450 1451 1452 1453

static int
virJSONParserHandleMapKey(void *ctx,
                          const unsigned char *stringVal,
                          yajl_size_t stringLen)
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
{
    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;
1466
    if (VIR_STRNDUP(state->key, (const char *)stringVal, stringLen) < 0)
1467 1468 1469 1470
        return 0;
    return 1;
}

1471 1472 1473

static int
virJSONParserHandleStartMap(void *ctx)
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
{
    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,
1489
                      parser->nstate + 1) < 0) {
1490
        return 0;
1491
    }
1492 1493 1494 1495 1496 1497 1498 1499 1500

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

    return 1;
}


1501 1502
static int
virJSONParserHandleEndMap(void *ctx)
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517
{
    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;
    }

1518
    VIR_DELETE_ELEMENT(parser->state, parser->nstate - 1, parser->nstate);
1519 1520 1521 1522

    return 1;
}

1523 1524 1525

static int
virJSONParserHandleStartArray(void *ctx)
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
{
    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;
}

1551 1552 1553

static int
virJSONParserHandleEndArray(void *ctx)
1554 1555 1556 1557 1558 1559
{
    virJSONParserPtr parser = ctx;
    virJSONParserStatePtr state;

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

1560
    if (!(parser->nstate - parser->wrap))
1561 1562 1563 1564 1565 1566 1567 1568
        return 0;

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

1569
    VIR_DELETE_ELEMENT(parser->state, parser->nstate - 1, parser->nstate);
1570 1571 1572 1573

    return 1;
}

1574

1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
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 */
1591 1592
virJSONValuePtr
virJSONValueFromString(const char *jsonstring)
1593 1594
{
    yajl_handle hand;
1595
    virJSONParser parser = { NULL, NULL, 0, 0 };
1596
    virJSONValuePtr ret = NULL;
1597 1598
    int rc;
    size_t len = strlen(jsonstring);
1599
# ifndef WITH_YAJL2
E
Eric Blake 已提交
1600
    yajl_parser_config cfg = { 0, 1 }; /* Match yajl 2 default behavior */
E
Eric Blake 已提交
1601
    virJSONValuePtr tmp;
1602
# endif
1603 1604 1605

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

1606
# ifdef WITH_YAJL2
1607 1608
    hand = yajl_alloc(&parserCallbacks, NULL, &parser);
# else
1609
    hand = yajl_alloc(&parserCallbacks, &cfg, NULL, &parser);
1610 1611
# endif
    if (!hand) {
1612 1613
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to create JSON parser"));
1614 1615
        goto cleanup;
    }
1616

E
Eric Blake 已提交
1617 1618 1619 1620 1621 1622 1623
    /* Yajl 2 is nice enough to default to rejecting trailing garbage.
     * Yajl 1.0.12 has yajl_get_bytes_consumed to make that detection
     * simpler.  But we're stuck with yajl 1.0.7 on RHEL 6, which
     * happily quits parsing at the end of a valid JSON construct,
     * with no visibility into how much more input remains.  Wrapping
     * things in an array forces yajl to confess the truth.  */
# ifdef WITH_YAJL2
1624
    rc = yajl_parse(hand, (const unsigned char *)jsonstring, len);
E
Eric Blake 已提交
1625 1626
# else
    rc = yajl_parse(hand, (const unsigned char *)"[", 1);
1627
    parser.wrap = 1;
E
Eric Blake 已提交
1628 1629
    if (VIR_YAJL_STATUS_OK(rc))
        rc = yajl_parse(hand, (const unsigned char *)jsonstring, len);
1630
    parser.wrap = 0;
E
Eric Blake 已提交
1631 1632 1633
    if (VIR_YAJL_STATUS_OK(rc))
        rc = yajl_parse(hand, (const unsigned char *)"]", 1);
# endif
1634
    if (!VIR_YAJL_STATUS_OK(rc) ||
E
Eric Blake 已提交
1635
        yajl_complete_parse(hand) != yajl_status_ok) {
1636 1637 1638 1639
        unsigned char *errstr = yajl_get_error(hand, 1,
                                               (const unsigned char*)jsonstring,
                                               strlen(jsonstring));

1640 1641 1642
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot parse json %s: %s"),
                       jsonstring, (const char*) errstr);
1643
        yajl_free_error(hand, errstr);
1644 1645 1646 1647
        virJSONValueFree(parser.head);
        goto cleanup;
    }

1648 1649 1650 1651 1652 1653 1654
    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;
E
Eric Blake 已提交
1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
# ifndef WITH_YAJL2
        /* Undo the array wrapping above */
        tmp = ret;
        ret = NULL;
        if (virJSONValueArraySize(tmp) > 1)
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot parse json %s: too many items present"),
                           jsonstring);
        else
            ret = virJSONValueArraySteal(tmp, 0);
        virJSONValueFree(tmp);
# endif
1667
    }
1668

1669
 cleanup:
1670 1671 1672
    yajl_free(hand);

    if (parser.nstate) {
1673
        size_t i;
J
Ján Tomko 已提交
1674
        for (i = 0; i < parser.nstate; i++)
1675
            VIR_FREE(parser.state[i].key);
1676
        VIR_FREE(parser.state);
1677 1678
    }

E
Eric Blake 已提交
1679
    VIR_DEBUG("result=%p", ret);
1680

1681
    return ret;
1682 1683 1684
}


1685 1686 1687
static int
virJSONValueToStringOne(virJSONValuePtr object,
                        yajl_gen g)
1688
{
1689
    size_t i;
1690 1691 1692 1693 1694 1695 1696

    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;
1697
        for (i = 0; i < object->data.object.npairs; i++) {
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711
            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;
1712
        for (i = 0; i < object->data.array.nvalues; i++) {
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
            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;
}

1749 1750 1751 1752

char *
virJSONValueToString(virJSONValuePtr object,
                     bool pretty)
1753 1754 1755 1756
{
    yajl_gen g;
    const unsigned char *str;
    char *ret = NULL;
1757
    yajl_size_t len;
1758
# ifndef WITH_YAJL2
1759
    yajl_gen_config conf = { pretty ? 1 : 0, pretty ? "    " : " "};
1760
# endif
1761 1762 1763

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

1764
# ifdef WITH_YAJL2
1765 1766
    g = yajl_gen_alloc(NULL);
    if (g) {
1767 1768
        yajl_gen_config(g, yajl_gen_beautify, pretty ? 1 : 0);
        yajl_gen_config(g, yajl_gen_indent_string, pretty ? "    " : " ");
1769 1770 1771
        yajl_gen_config(g, yajl_gen_validate_utf8, 1);
    }
# else
1772
    g = yajl_gen_alloc(&conf, NULL);
1773 1774
# endif
    if (!g) {
1775 1776
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to create JSON formatter"));
1777 1778
        goto cleanup;
    }
1779 1780

    if (virJSONValueToStringOne(object, g) < 0) {
1781
        virReportOOMError();
1782 1783 1784 1785
        goto cleanup;
    }

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

1790
    ignore_value(VIR_STRDUP(ret, (const char *)str));
1791

1792
 cleanup:
1793 1794 1795 1796 1797 1798 1799 1800 1801
    yajl_gen_free(g);

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

    return ret;
}


#else
1802 1803
virJSONValuePtr
virJSONValueFromString(const char *jsonstring ATTRIBUTE_UNUSED)
1804
{
1805 1806
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("No JSON parser implementation is available"));
1807 1808
    return NULL;
}
1809 1810 1811 1812 1813


char *
virJSONValueToString(virJSONValuePtr object ATTRIBUTE_UNUSED,
                     bool pretty ATTRIBUTE_UNUSED)
1814
{
1815 1816
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("No JSON parser implementation is available"));
1817 1818 1819
    return NULL;
}
#endif