cJSON_Utils.c 34.5 KB
Newer Older
M
Max Bruckner 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*
  Copyright (c) 2009-2017 Dave Gamble and cJSON contributors

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
*/

23
#pragma GCC visibility push(default)
24
#include <ctype.h>
25 26
#include <string.h>
#include <stdlib.h>
27
#include <stdio.h>
M
Max Bruckner 已提交
28
#include <limits.h>
29
#pragma GCC visibility pop
M
Max Bruckner 已提交
30

31 32
#include "cJSON_Utils.h"

M
Max Bruckner 已提交
33 34 35 36
/* define our own boolean type */
#define true ((cJSON_bool)1)
#define false ((cJSON_bool)0)

M
Max Bruckner 已提交
37
static unsigned char* cJSONUtils_strdup(const unsigned char* const string)
38
{
M
Max Bruckner 已提交
39
    size_t length = 0;
40
    unsigned char *copy = NULL;
41

M
Max Bruckner 已提交
42 43 44
    length = strlen((const char*)string) + sizeof("");
    copy = (unsigned char*) cJSON_malloc(length);
    if (copy == NULL)
45
    {
46
        return NULL;
47
    }
M
Max Bruckner 已提交
48
    memcpy(copy, string, length);
49 50 51 52

    return copy;
}

M
Max Bruckner 已提交
53 54
/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */
static int cJSONUtils_strcasecmp(const unsigned char *string1, const unsigned char *string2)
55
{
M
Max Bruckner 已提交
56
    if ((string1 == NULL) || (string2 == NULL))
M
Max Bruckner 已提交
57
    {
M
Max Bruckner 已提交
58
        return 1;
M
Max Bruckner 已提交
59
    }
M
Max Bruckner 已提交
60 61

    if (string1 == string2)
M
Max Bruckner 已提交
62
    {
M
Max Bruckner 已提交
63
        return 0;
M
Max Bruckner 已提交
64
    }
M
Max Bruckner 已提交
65 66

    for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++)
M
Max Bruckner 已提交
67
    {
M
Max Bruckner 已提交
68
        if (*string1 == '\0')
M
Max Bruckner 已提交
69 70 71 72 73
        {
            return 0;
        }
    }

M
Max Bruckner 已提交
74
    return tolower(*string1) - tolower(*string2);
75 76
}

M
Max Bruckner 已提交
77 78
/* Compare the next path element of two JSON pointers, two NULL pointers are considered unequal: */
static int cJSONUtils_Pstrcasecmp(const unsigned char *name, const unsigned char *pointer)
79
{
M
Max Bruckner 已提交
80
    if ((name == NULL) || (pointer == NULL))
81
    {
M
Max Bruckner 已提交
82
        return 1;
83
    }
M
Max Bruckner 已提交
84 85

    for (; (*name != '\0') && (*pointer != '\0') && (*pointer != '/'); (void)name++, pointer++) /* compare until next '/' */
86
    {
M
Max Bruckner 已提交
87
        if (*pointer == '~')
88 89
        {
            /* check for escaped '~' (~0) and '/' (~1) */
M
Max Bruckner 已提交
90
            if (((pointer[1] != '0') || (*name != '~')) && ((pointer[1] != '1') || (*name != '/')))
91
            {
M
Max Bruckner 已提交
92
                /* invalid escape sequence or wrong character in *name */
93 94 95 96
                return 1;
            }
            else
            {
M
Max Bruckner 已提交
97
                pointer++;
98 99
            }
        }
M
Max Bruckner 已提交
100
        else if (tolower(*name) != tolower(*pointer))
101 102 103 104
        {
            return 1;
        }
    }
M
Max Bruckner 已提交
105
    if (((*pointer != 0) && (*pointer != '/')) != (*name != 0))
106 107 108 109 110 111
    {
        /* one string has ended, the other not */
        return 1;
    }

    return 0;
112 113
}

114 115
/* calculate the length of a string if encoded as JSON pointer with ~0 and ~1 escape sequences */
static size_t cJSONUtils_PointerEncodedstrlen(const unsigned char *string)
116
{
117 118
    size_t length;
    for (length = 0; *string != '\0'; (void)string++, length++)
119
    {
120 121
        /* character needs to be escaped? */
        if ((*string == '~') || (*string == '/'))
122
        {
123
            length++;
124 125 126
        }
    }

127
    return length;
128
}
129

130 131
/* copy a string while escaping '~' and '/' with ~0 and ~1 JSON pointer escape codes */
static void cJSONUtils_PointerEncodedstrcpy(unsigned char *destination, const unsigned char *source)
132
{
133
    for (; source[0] != '\0'; (void)source++, destination++)
134
    {
135
        if (source[0] == '/')
136
        {
137 138
            destination[1] = '1';
            destination++;
139
        }
140
        else if (source[0] == '~')
141
        {
142 143 144
            destination[0] = '~';
            destination[1] = '1';
            destination++;
145 146 147
        }
        else
        {
148
            destination[0] = source[0];
149 150 151
        }
    }

152
    destination[0] = '\0';
153 154
}

155
CJSON_PUBLIC(char *) cJSONUtils_FindPointerFromObjectTo(const cJSON * const object, const cJSON * const target)
156
{
157 158
    size_t child_index = 0;
    cJSON *current_child = 0;
159

160 161 162
    if (object == target)
    {
        /* found */
163
        return (char*)cJSONUtils_strdup((const unsigned char*)"");
164
    }
165

166 167
    /* recursively search all children of the object or array */
    for (current_child = object->child; current_child != NULL; (void)(current_child = current_child->next), child_index++)
168
    {
169 170 171
        unsigned char *target_pointer = (unsigned char*)cJSONUtils_FindPointerFromObjectTo(current_child, target);
        /* found the target? */
        if (target_pointer != NULL)
172
        {
173
            if (cJSON_IsArray(object))
174 175
            {
                /* reserve enough memory for a 64 bit integer + '/' and '\0' */
176
                unsigned char *full_pointer = (unsigned char*)cJSON_malloc(strlen((char*)target_pointer) + 20 + sizeof("/"));
177 178 179
                /* check if conversion to unsigned long is valid
                 * This should be eliminated at compile time by dead code elimination
                 * if size_t is an alias of unsigned long, or if it is bigger */
180
                if (child_index > ULONG_MAX)
181
                {
182
                    cJSON_free(target_pointer);
183 184
                    return NULL;
                }
185 186
                sprintf((char*)full_pointer, "/%lu%s", (unsigned long)child_index, target_pointer); /* /<array_index><path> */
                cJSON_free(target_pointer);
187

188
                return (char*)full_pointer;
189
            }
190 191

            if (cJSON_IsObject(object))
192
            {
193 194 195 196 197
                unsigned char *full_pointer = (unsigned char*)cJSON_malloc(strlen((char*)target_pointer) + cJSONUtils_PointerEncodedstrlen((unsigned char*)current_child->string) + 2);
                full_pointer[0] = '/';
                cJSONUtils_PointerEncodedstrcpy(full_pointer + 1, (unsigned char*)current_child->string);
                strcat((char*)full_pointer, (char*)target_pointer);
                cJSON_free(target_pointer);
198

199
                return (char*)full_pointer;
200 201 202
            }

            /* reached leaf of the tree, found nothing */
203
            cJSON_free(target_pointer);
204
            return NULL;
205 206 207 208
        }
    }

    /* not found */
209
    return NULL;
210 211
}

212 213 214 215 216 217 218 219 220 221 222 223 224
/* non broken version of cJSON_GetArrayItem */
static cJSON *get_array_item(const cJSON *array, size_t item)
{
    cJSON *child = array ? array->child : NULL;
    while ((child != NULL) && (item > 0))
    {
        item--;
        child = child->next;
    }

    return child;
}

225 226 227 228 229 230 231 232 233 234 235
static cJSON_bool decode_array_index_from_pointer(const unsigned char * const pointer, size_t * const index)
{
    size_t parsed_index = 0;
    size_t position = 0;

    if ((pointer[0] == '0') && ((pointer[1] != '\0') && (pointer[1] != '/')))
    {
        /* leading zeroes are not permitted */
        return 0;
    }

236
    for (position = 0; (pointer[position] >= '0') && (pointer[0] <= '9'); position++)
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
    {
        parsed_index = (10 * parsed_index) + (size_t)(pointer[position] - '0');

    }

    if ((pointer[position] != '\0') && (pointer[position] != '/'))
    {
        return 0;
    }

    *index = parsed_index;

    return 1;
}

M
Max Bruckner 已提交
252
CJSON_PUBLIC(cJSON *) cJSONUtils_GetPointer(cJSON * const object, const char *pointer)
253
{
M
Max Bruckner 已提交
254
    cJSON *current_element = object;
255
    /* follow path of the pointer */
M
Max Bruckner 已提交
256
    while ((pointer[0] == '/') && (current_element != NULL))
257
    {
M
Max Bruckner 已提交
258 259
        pointer++;
        if (cJSON_IsArray(current_element))
260
        {
261
            size_t index = 0;
262
            if (!decode_array_index_from_pointer((const unsigned char*)pointer, &index))
263
            {
264
                return NULL;
265
            }
266

M
Max Bruckner 已提交
267
            current_element = get_array_item(current_element, index);
268
        }
M
Max Bruckner 已提交
269
        else if (cJSON_IsObject(current_element))
270
        {
M
Max Bruckner 已提交
271
            current_element = current_element->child;
272
            /* GetObjectItem. */
M
Max Bruckner 已提交
273
            while ((current_element != NULL) && cJSONUtils_Pstrcasecmp((unsigned char*)current_element->string, (const unsigned char*)pointer))
274
            {
M
Max Bruckner 已提交
275
                current_element = current_element->next;
276 277
            }
            /* skip to the next path token or end of string */
M
Max Bruckner 已提交
278
            while ((pointer[0] != '\0') && (pointer[0] != '/'))
279 280 281 282 283 284
            {
                pointer++;
            }
        }
        else
        {
285
            return NULL;
286 287 288
        }
    }

M
Max Bruckner 已提交
289
    return current_element;
290 291
}

292
/* JSON Patch implementation. */
293
static void cJSONUtils_InplaceDecodePointerString(unsigned char *string)
294
{
295
    unsigned char *decoded_string = string;
296 297 298 299 300

    if (string == NULL) {
        return;
    }

301
    for (; *string; (void)decoded_string++, string++)
302
    {
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
        if (string[0] == '~')
        {
            if (string[1] == '0')
            {
                decoded_string[0] = '~';
            }
            else if (string[1] == '1')
            {
                decoded_string[1] = '/';
            }
            else
            {
                /* invalid escape sequence */
                return;
            }

            string++;
        }
321 322
    }

323
    decoded_string[0] = '\0';
324 325
}

326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
/* non-broken cJSON_DetachItemFromArray */
static cJSON *detach_item_from_array(cJSON *array, size_t which)
{
    cJSON *c = array->child;
    while (c && (which > 0))
    {
        c = c->next;
        which--;
    }
    if (!c)
    {
        /* item doesn't exist */
        return NULL;
    }
    if (c->prev)
    {
        /* not the first element */
        c->prev->next = c->next;
    }
    if (c->next)
    {
        c->next->prev = c->prev;
    }
    if (c==array->child)
    {
        array->child = c->next;
    }
    /* make sure the detached item doesn't point anywhere anymore */
    c->prev = c->next = NULL;

    return c;
}

359
static cJSON *cJSONUtils_PatchDetach(cJSON *object, const unsigned char *path)
360
{
M
Max Bruckner 已提交
361 362
    unsigned char *parent_pointer = NULL;
    unsigned char *child_pointer = NULL;
363
    cJSON *parent = NULL;
M
Max Bruckner 已提交
364
    cJSON *detached_item = NULL;
365 366

    /* copy path and split it in parent and child */
M
Max Bruckner 已提交
367 368 369
    parent_pointer = cJSONUtils_strdup(path);
    if (parent_pointer == NULL) {
        goto cleanup;
370 371
    }

M
Max Bruckner 已提交
372 373
    child_pointer = (unsigned char*)strrchr((char*)parent_pointer, '/'); /* last '/' */
    if (child_pointer == NULL)
374
    {
M
Max Bruckner 已提交
375
        goto cleanup;
376
    }
377
    /* split strings */
M
Max Bruckner 已提交
378 379
    child_pointer[0] = '\0';
    child_pointer++;
380

M
Max Bruckner 已提交
381 382
    parent = cJSONUtils_GetPointer(object, (char*)parent_pointer);
    cJSONUtils_InplaceDecodePointerString(child_pointer);
383

M
Max Bruckner 已提交
384
    if (cJSON_IsArray(parent))
385
    {
386
        size_t index = 0;
M
Max Bruckner 已提交
387
        if (!decode_array_index_from_pointer(child_pointer, &index))
388
        {
M
Max Bruckner 已提交
389
            goto cleanup;
390
        }
M
Max Bruckner 已提交
391
        detached_item = detach_item_from_array(parent, index);
392
    }
393
    else if (cJSON_IsObject(parent))
394
    {
M
Max Bruckner 已提交
395 396 397 398 399 400 401 402 403 404 405 406
        detached_item = cJSON_DetachItemFromObject(parent, (char*)child_pointer);
    }
    else
    {
        /* Couldn't find object to remove child from. */
        goto cleanup;
    }

cleanup:
    if (parent_pointer != NULL)
    {
        cJSON_free(parent_pointer);
407
    }
408

M
Max Bruckner 已提交
409
    return detached_item;
410 411
}

M
Max Bruckner 已提交
412
static int cJSONUtils_Compare(cJSON *a, cJSON *b)
413
{
414
    if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF)))
M
Max Bruckner 已提交
415 416 417 418
    {
        /* mismatched type. */
        return -1;
    }
419
    switch (a->type & 0xFF)
M
Max Bruckner 已提交
420 421 422
    {
        case cJSON_Number:
            /* numeric mismatch. */
M
Max Bruckner 已提交
423 424 425 426 427 428 429 430 431
            if ((a->valueint != b->valueint) || (a->valuedouble != b->valuedouble))
            {
                return -2;
            }
            else
            {
                return 0;
            }

M
Max Bruckner 已提交
432 433
        case cJSON_String:
            /* string mismatch. */
M
Max Bruckner 已提交
434 435 436 437 438 439 440 441 442
            if (strcmp(a->valuestring, b->valuestring) != 0)
            {
                return -3;
            }
            else
            {
                return 0;
            }

M
Max Bruckner 已提交
443
        case cJSON_Array:
M
Max Bruckner 已提交
444
            for ((void)(a = a->child), b = b->child; (a != NULL) && (b != NULL); (void)(a = a->next), b = b->next)
M
Max Bruckner 已提交
445
            {
M
Max Bruckner 已提交
446 447
                int status = cJSONUtils_Compare(a, b);
                if (status != 0)
M
Max Bruckner 已提交
448
                {
M
Max Bruckner 已提交
449
                    return status;
M
Max Bruckner 已提交
450 451
                }
            }
M
Max Bruckner 已提交
452

M
Max Bruckner 已提交
453
            /* array size mismatch? (one of both children is not NULL) */
M
Max Bruckner 已提交
454 455 456 457 458 459 460 461 462
            if ((a != NULL) || (b != NULL))
            {
                return -4;
            }
            else
            {
                return 0;
            }

M
Max Bruckner 已提交
463 464 465
        case cJSON_Object:
            cJSONUtils_SortObject(a);
            cJSONUtils_SortObject(b);
M
Max Bruckner 已提交
466
            for ((void)(a = a->child), b = b->child; (a != NULL) && (b != NULL); (void)(a = a->next), b = b->next)
M
Max Bruckner 已提交
467
            {
M
Max Bruckner 已提交
468
                int status = 0;
M
Max Bruckner 已提交
469
                /* compare object keys */
470
                if (cJSONUtils_strcasecmp((unsigned char*)a->string, (unsigned char*)b->string))
M
Max Bruckner 已提交
471 472 473 474
                {
                    /* missing member */
                    return -6;
                }
M
Max Bruckner 已提交
475 476
                status = cJSONUtils_Compare(a, b);
                if (status != 0)
M
Max Bruckner 已提交
477
                {
M
Max Bruckner 已提交
478
                    return status;
M
Max Bruckner 已提交
479 480
                }
            }
M
Max Bruckner 已提交
481

M
Max Bruckner 已提交
482
            /* object length mismatch (one of both children is not null) */
M
Max Bruckner 已提交
483 484 485 486 487 488 489 490
            if ((a != NULL) || (b != NULL))
            {
                return -5;
            }
            else
            {
                return 0;
            }
491

M
Max Bruckner 已提交
492 493 494
        default:
            break;
    }
M
Max Bruckner 已提交
495

M
Max Bruckner 已提交
496 497
    /* null, true or false */
    return 0;
498 499
}

500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
/* non broken version of cJSON_InsertItemInArray */
static cJSON_bool insert_item_in_array(cJSON *array, size_t which, cJSON *newitem)
{
    cJSON *child = array->child;
    while (child && (which > 0))
    {
        child = child->next;
        which--;
    }
    if (which > 0)
    {
        /* item is after the end of the array */
        return 0;
    }
    if (child == NULL)
    {
        cJSON_AddItemToArray(array, newitem);
        return 1;
    }

    /* insert into the linked list */
    newitem->next = child;
    newitem->prev = child->prev;
    child->prev = newitem;

    /* was it at the beginning */
    if (child == array->child)
    {
        array->child = newitem;
    }
    else
    {
        newitem->prev->next = newitem;
    }

    return 1;
}

M
Max Bruckner 已提交
538 539
enum patch_operation { INVALID, ADD, REMOVE, REPLACE, MOVE, COPY, TEST };

M
Max Bruckner 已提交
540
static enum patch_operation decode_patch_operation(const cJSON * const patch)
541
{
M
Max Bruckner 已提交
542 543 544 545 546
    cJSON *operation = cJSON_GetObjectItem(patch, "op");
    if (!cJSON_IsString(operation))
    {
        return INVALID;
    }
547

M
Max Bruckner 已提交
548
    if (strcmp(operation->valuestring, "add") == 0)
M
Max Bruckner 已提交
549
    {
M
Max Bruckner 已提交
550
        return ADD;
M
Max Bruckner 已提交
551
    }
552

M
Max Bruckner 已提交
553
    if (strcmp(operation->valuestring, "remove") == 0)
M
Max Bruckner 已提交
554
    {
M
Max Bruckner 已提交
555
        return REMOVE;
M
Max Bruckner 已提交
556
    }
M
Max Bruckner 已提交
557 558

    if (strcmp(operation->valuestring, "replace") == 0)
M
Max Bruckner 已提交
559
    {
M
Max Bruckner 已提交
560
        return REPLACE;
M
Max Bruckner 已提交
561
    }
M
Max Bruckner 已提交
562 563

    if (strcmp(operation->valuestring, "move") == 0)
M
Max Bruckner 已提交
564
    {
M
Max Bruckner 已提交
565
        return MOVE;
M
Max Bruckner 已提交
566
    }
M
Max Bruckner 已提交
567 568

    if (strcmp(operation->valuestring, "copy") == 0)
M
Max Bruckner 已提交
569
    {
M
Max Bruckner 已提交
570
        return COPY;
M
Max Bruckner 已提交
571
    }
M
Max Bruckner 已提交
572 573

    if (strcmp(operation->valuestring, "test") == 0)
M
Max Bruckner 已提交
574
    {
M
Max Bruckner 已提交
575
        return TEST;
M
Max Bruckner 已提交
576
    }
M
Max Bruckner 已提交
577 578 579 580 581 582 583 584

    return INVALID;
}

/* overwrite and existing item with another one and free resources on the way */
static void overwrite_item(cJSON * const root, const cJSON replacement)
{
    if (root == NULL)
M
Max Bruckner 已提交
585
    {
M
Max Bruckner 已提交
586
        return;
M
Max Bruckner 已提交
587
    }
M
Max Bruckner 已提交
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616

    if (root->string != NULL)
    {
        cJSON_free(root->string);
    }
    if (root->valuestring != NULL)
    {
        cJSON_free(root->valuestring);
    }
    if (root->child != NULL)
    {
        cJSON_Delete(root->child);
    }

    memcpy(root, &replacement, sizeof(cJSON));
}

static int cJSONUtils_ApplyPatch(cJSON *object, const cJSON *patch)
{
    cJSON *path = NULL;
    cJSON *value = NULL;
    cJSON *parent = NULL;
    enum patch_operation opcode = INVALID;
    unsigned char *parent_pointer = NULL;
    unsigned char *child_pointer = NULL;
    int status = 0;

    path = cJSON_GetObjectItem(patch, "path");
    if (!cJSON_IsString(path))
M
Max Bruckner 已提交
617
    {
M
Max Bruckner 已提交
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
        /* malformed patch. */
        status = 2;
        goto cleanup;
    }

    opcode = decode_patch_operation(patch);
    if (opcode == INVALID)
    {
        status = 3;
        goto cleanup;
    }
    else if (opcode == TEST)
    {
        /* compare value: {...} with the given path */
        status = cJSONUtils_Compare(cJSONUtils_GetPointer(object, path->valuestring), cJSON_GetObjectItem(patch, "value"));
        goto cleanup;
M
Max Bruckner 已提交
634
    }
635

636 637 638 639 640
    /* special case for replacing the root */
    if (path->valuestring[0] == '\0')
    {
        if (opcode == REMOVE)
        {
M
Max Bruckner 已提交
641
            static const cJSON invalid = { NULL, NULL, NULL, cJSON_Invalid, NULL, 0, 0, NULL};
642

M
Max Bruckner 已提交
643
            overwrite_item(object, invalid);
644

M
Max Bruckner 已提交
645 646
            status = 0;
            goto cleanup;
647 648 649 650 651 652 653 654
        }

        if ((opcode == REPLACE) || (opcode == ADD))
        {
            value = cJSON_GetObjectItem(patch, "value");
            if (value == NULL)
            {
                /* missing "value" for add/replace. */
M
Max Bruckner 已提交
655 656
                status = 7;
                goto cleanup;
657 658 659 660 661 662
            }

            value = cJSON_Duplicate(value, 1);
            if (value == NULL)
            {
                /* out of memory for add/replace. */
M
Max Bruckner 已提交
663 664
                status = 8;
                goto cleanup;
665 666
            }

M
Max Bruckner 已提交
667
            overwrite_item(object, *value);
668 669 670

            /* delete the duplicated value */
            cJSON_free(value);
M
Max Bruckner 已提交
671
            value = NULL;
672

M
Max Bruckner 已提交
673 674 675 676 677 678 679 680 681
            /* the string "value" isn't needed */
            if (object->string != NULL)
            {
                cJSON_free(object->string);
                object->string = NULL;
            }

            status = 0;
            goto cleanup;
682 683 684
        }
    }

M
Max Bruckner 已提交
685
    if ((opcode == REMOVE) || (opcode == REPLACE))
M
Max Bruckner 已提交
686 687
    {
        /* Get rid of old. */
688 689 690
        cJSON *old_item = cJSONUtils_PatchDetach(object, (unsigned char*)path->valuestring);
        if (old_item == NULL)
        {
M
Max Bruckner 已提交
691 692
            status = 13;
            goto cleanup;
693 694
        }
        cJSON_Delete(old_item);
M
Max Bruckner 已提交
695
        if (opcode == REMOVE)
M
Max Bruckner 已提交
696
        {
697
            /* For Remove, this job is done. */
M
Max Bruckner 已提交
698 699
            status = 0;
            goto cleanup;
M
Max Bruckner 已提交
700 701
        }
    }
702

M
Max Bruckner 已提交
703
    /* Copy/Move uses "from". */
M
Max Bruckner 已提交
704
    if ((opcode == MOVE) || (opcode == COPY))
M
Max Bruckner 已提交
705 706
    {
        cJSON *from = cJSON_GetObjectItem(patch, "from");
M
Max Bruckner 已提交
707
        if (from == NULL)
M
Max Bruckner 已提交
708 709
        {
            /* missing "from" for copy/move. */
M
Max Bruckner 已提交
710 711
            status = 4;
            goto cleanup;
M
Max Bruckner 已提交
712
        }
713

M
Max Bruckner 已提交
714
        if (opcode == MOVE)
M
Max Bruckner 已提交
715
        {
716
            value = cJSONUtils_PatchDetach(object, (unsigned char*)from->valuestring);
M
Max Bruckner 已提交
717
        }
M
Max Bruckner 已提交
718
        if (opcode == COPY)
M
Max Bruckner 已提交
719 720 721
        {
            value = cJSONUtils_GetPointer(object, from->valuestring);
        }
M
Max Bruckner 已提交
722
        if (value == NULL)
M
Max Bruckner 已提交
723 724
        {
            /* missing "from" for copy/move. */
M
Max Bruckner 已提交
725 726
            status = 5;
            goto cleanup;
M
Max Bruckner 已提交
727
        }
M
Max Bruckner 已提交
728
        if (opcode == COPY)
M
Max Bruckner 已提交
729 730 731
        {
            value = cJSON_Duplicate(value, 1);
        }
M
Max Bruckner 已提交
732
        if (value == NULL)
M
Max Bruckner 已提交
733 734
        {
            /* out of memory for copy/move. */
M
Max Bruckner 已提交
735 736
            status = 6;
            goto cleanup;
M
Max Bruckner 已提交
737 738 739 740 741
        }
    }
    else /* Add/Replace uses "value". */
    {
        value = cJSON_GetObjectItem(patch, "value");
M
Max Bruckner 已提交
742
        if (value == NULL)
M
Max Bruckner 已提交
743 744
        {
            /* missing "value" for add/replace. */
M
Max Bruckner 已提交
745 746
            status = 7;
            goto cleanup;
M
Max Bruckner 已提交
747 748
        }
        value = cJSON_Duplicate(value, 1);
M
Max Bruckner 已提交
749
        if (value == NULL)
M
Max Bruckner 已提交
750 751
        {
            /* out of memory for add/replace. */
M
Max Bruckner 已提交
752 753
            status = 8;
            goto cleanup;
M
Max Bruckner 已提交
754 755
        }
    }
756

M
Max Bruckner 已提交
757
    /* Now, just add "value" to "path". */
758

M
Max Bruckner 已提交
759
    /* split pointer in parent and child */
M
Max Bruckner 已提交
760 761 762
    parent_pointer = cJSONUtils_strdup((unsigned char*)path->valuestring);
    child_pointer = (unsigned char*)strrchr((char*)parent_pointer, '/');
    if (child_pointer != NULL)
M
Max Bruckner 已提交
763
    {
M
Max Bruckner 已提交
764 765
        child_pointer[0] = '\0';
        child_pointer++;
M
Max Bruckner 已提交
766
    }
M
Max Bruckner 已提交
767 768
    parent = cJSONUtils_GetPointer(object, (char*)parent_pointer);
    cJSONUtils_InplaceDecodePointerString(child_pointer);
769

M
Max Bruckner 已提交
770
    /* add, remove, replace, move, copy, test. */
M
Max Bruckner 已提交
771
    if ((parent == NULL) || (child_pointer == NULL))
M
Max Bruckner 已提交
772 773
    {
        /* Couldn't find object to add to. */
M
Max Bruckner 已提交
774 775
        status = 9;
        goto cleanup;
M
Max Bruckner 已提交
776
    }
777
    else if (cJSON_IsArray(parent))
M
Max Bruckner 已提交
778
    {
M
Max Bruckner 已提交
779
        if (strcmp((char*)child_pointer, "-") == 0)
M
Max Bruckner 已提交
780 781
        {
            cJSON_AddItemToArray(parent, value);
M
Max Bruckner 已提交
782
            value = NULL;
M
Max Bruckner 已提交
783 784 785
        }
        else
        {
786
            size_t index = 0;
M
Max Bruckner 已提交
787
            if (!decode_array_index_from_pointer(child_pointer, &index))
788
            {
M
Max Bruckner 已提交
789 790
                status = 11;
                goto cleanup;
791 792
            }

793
            if (!insert_item_in_array(parent, index, value))
794
            {
M
Max Bruckner 已提交
795 796
                status = 10;
                goto cleanup;
797
            }
M
Max Bruckner 已提交
798
            value = NULL;
M
Max Bruckner 已提交
799 800
        }
    }
801
    else if (cJSON_IsObject(parent))
M
Max Bruckner 已提交
802
    {
M
Max Bruckner 已提交
803 804 805
        cJSON_DeleteItemFromObject(parent, (char*)child_pointer);
        cJSON_AddItemToObject(parent, (char*)child_pointer, value);
        value = NULL;
M
Max Bruckner 已提交
806
    }
M
Max Bruckner 已提交
807 808 809

cleanup:
    if (value != NULL)
M
Max Bruckner 已提交
810 811 812
    {
        cJSON_Delete(value);
    }
M
Max Bruckner 已提交
813 814 815 816
    if (parent_pointer != NULL)
    {
        cJSON_free(parent_pointer);
    }
M
Max Bruckner 已提交
817

M
Max Bruckner 已提交
818
    return status;
M
Max Bruckner 已提交
819
}
820

M
Max Bruckner 已提交
821
CJSON_PUBLIC(int) cJSONUtils_ApplyPatches(cJSON * const object, const cJSON * const patches)
822
{
M
Max Bruckner 已提交
823 824
    const cJSON *current_patch = NULL;
    int status = 0;
825

826
    if (!cJSON_IsArray(patches))
827 828 829 830
    {
        /* malformed patches. */
        return 1;
    }
M
Max Bruckner 已提交
831 832

    if (patches != NULL)
833
    {
M
Max Bruckner 已提交
834
        current_patch = patches->child;
835
    }
M
Max Bruckner 已提交
836 837

    while (current_patch != NULL)
838
    {
M
Max Bruckner 已提交
839 840
        status = cJSONUtils_ApplyPatch(object, current_patch);
        if (status != 0)
841
        {
M
Max Bruckner 已提交
842
            return status;
843
        }
M
Max Bruckner 已提交
844
        current_patch = current_patch->next;
845 846 847
    }

    return 0;
848
}
849

M
Max Bruckner 已提交
850
static void cJSONUtils_GeneratePatch(cJSON * const patches, const unsigned char * const operation, const unsigned char * const path, const unsigned char *suffix, const cJSON * const value)
851
{
852
    cJSON *patch = cJSON_CreateObject();
M
Max Bruckner 已提交
853
    if (patch == NULL)
854
    {
M
Max Bruckner 已提交
855
        return;
856
    }
M
Max Bruckner 已提交
857 858 859
    cJSON_AddItemToObject(patch, "op", cJSON_CreateString((const char*)operation));

    if (suffix == NULL)
860
    {
861
        cJSON_AddItemToObject(patch, "path", cJSON_CreateString((const char*)path));
862
    }
M
Max Bruckner 已提交
863 864 865 866 867 868 869 870 871 872 873 874 875 876
    else
    {
        size_t suffix_length = cJSONUtils_PointerEncodedstrlen(suffix);
        size_t path_length = strlen((const char*)path);
        unsigned char *full_path = (unsigned char*)cJSON_malloc(path_length + suffix_length + sizeof("/"));

        sprintf((char*)full_path, "%s/", (const char*)path);
        cJSONUtils_PointerEncodedstrcpy(full_path + path_length + 1, suffix);

        cJSON_AddItemToObject(patch, "path", cJSON_CreateString((const char*)full_path));
        free(full_path);
    }

    if (value != NULL)
877
    {
M
Max Bruckner 已提交
878
        cJSON_AddItemToObject(patch, "value", cJSON_Duplicate(value, 1));
879 880
    }
    cJSON_AddItemToArray(patches, patch);
881 882
}

883
CJSON_PUBLIC(void) cJSONUtils_AddPatchToArray(cJSON * const array, const char * const operation, const char * const path, const cJSON * const value)
M
Max Bruckner 已提交
884
{
885
    cJSONUtils_GeneratePatch(array, (const unsigned char*)operation, (const unsigned char*)path, NULL, value);
M
Max Bruckner 已提交
886
}
887

888
static void cJSONUtils_CompareToPatch(cJSON * const patches, const unsigned char * const path, cJSON * const from, cJSON * const to)
889
{
890 891 892 893 894
    if ((from == NULL) || (to == NULL))
    {
        return;
    }

895
    if ((from->type & 0xFF) != (to->type & 0xFF))
896
    {
897
        cJSONUtils_GeneratePatch(patches, (const unsigned char*)"replace", path, 0, to);
898 899 900
        return;
    }

901
    switch (from->type & 0xFF)
902 903 904 905
    {
        case cJSON_Number:
            if ((from->valueint != to->valueint) || (from->valuedouble != to->valuedouble))
            {
906
                cJSONUtils_GeneratePatch(patches, (const unsigned char*)"replace", path, NULL, to);
907 908 909 910 911 912
            }
            return;

        case cJSON_String:
            if (strcmp(from->valuestring, to->valuestring) != 0)
            {
913
                cJSONUtils_GeneratePatch(patches, (const unsigned char*)"replace", path, NULL, to);
914 915
            }
            return;
916

917 918
        case cJSON_Array:
        {
919 920 921 922 923 924 925
            size_t index = 0;
            cJSON *from_child = from->child;
            cJSON *to_child = to->child;
            unsigned char *new_path = (unsigned char*)cJSON_malloc(strlen((const char*)path) + 20 + sizeof("/")); /* Allow space for 64bit int. log10(2^64) = 20 */

            /* generate patches for all array elements that exist in both "from" and "to" */
            for (index = 0; (from_child != NULL) && (to_child != NULL); (void)(from_child = from_child->next), (void)(to_child = to_child->next), index++)
926
            {
927 928 929
                /* check if conversion to unsigned long is valid
                 * This should be eliminated at compile time by dead code elimination
                 * if size_t is an alias of unsigned long, or if it is bigger */
930
                if (index > ULONG_MAX)
931
                {
932
                    free(new_path);
933 934
                    return;
                }
935 936
                sprintf((char*)new_path, "%s/%lu", path, (unsigned long)index); /* path of the current array element */
                cJSONUtils_CompareToPatch(patches, new_path, from_child, to_child);
937
            }
938

939
            /* remove leftover elements from 'from' that are not in 'to' */
940
            for (; (from_child != NULL); (void)(from_child = from_child->next))
941
            {
942 943 944
                /* check if conversion to unsigned long is valid
                 * This should be eliminated at compile time by dead code elimination
                 * if size_t is an alias of unsigned long, or if it is bigger */
945
                if (index > ULONG_MAX)
946
                {
947
                    free(new_path);
948 949
                    return;
                }
950 951
                sprintf((char*)new_path, "%lu", (unsigned long)index);
                cJSONUtils_GeneratePatch(patches, (const unsigned char*)"remove", path, new_path, NULL);
952 953
            }
            /* add new elements in 'to' that were not in 'from' */
954
            for (; (to_child != NULL); (void)(to_child = to_child->next), index++)
955
            {
956
                cJSONUtils_GeneratePatch(patches, (const unsigned char*)"add", path, (const unsigned char*)"-", to_child);
957
            }
958
            free(new_path);
959 960 961 962 963
            return;
        }

        case cJSON_Object:
        {
964 965
            cJSON *from_child = NULL;
            cJSON *to_child = NULL;
966 967 968
            cJSONUtils_SortObject(from);
            cJSONUtils_SortObject(to);

969 970
            from_child = from->child;
            to_child = to->child;
971
            /* for all object values in the object with more of them */
972
            while ((from_child != NULL) || (to_child != NULL))
973
            {
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
                int diff;
                if (from_child == NULL)
                {
                    diff = 1;
                }
                else if (to_child == NULL)
                {
                    diff = -1;
                }
                else
                {
                    diff = cJSONUtils_strcasecmp((unsigned char*)from_child->string, (unsigned char*)to_child->string);
                }

                if (diff == 0)
989 990
                {
                    /* both object keys are the same */
991 992 993 994 995 996 997
                    size_t path_length = strlen((const char*)path);
                    size_t from_child_name_length = cJSONUtils_PointerEncodedstrlen((unsigned char*)from_child->string);
                    unsigned char *new_path = (unsigned char*)cJSON_malloc(path_length + from_child_name_length + sizeof("/"));

                    sprintf((char*)new_path, "%s/", path);
                    cJSONUtils_PointerEncodedstrcpy(new_path + path_length + 1, (unsigned char*)from_child->string);

998
                    /* create a patch for the element */
999 1000 1001 1002 1003
                    cJSONUtils_CompareToPatch(patches, new_path, from_child, to_child);
                    free(new_path);

                    from_child = from_child->next;
                    to_child = to_child->next;
1004 1005 1006 1007
                }
                else if (diff < 0)
                {
                    /* object element doesn't exist in 'to' --> remove it */
1008 1009 1010
                    cJSONUtils_GeneratePatch(patches, (const unsigned char*)"remove", path, (unsigned char*)from_child->string, NULL);

                    from_child = from_child->next;
1011 1012 1013 1014
                }
                else
                {
                    /* object element doesn't exist in 'from' --> add it */
1015 1016 1017
                    cJSONUtils_GeneratePatch(patches, (const unsigned char*)"add", path, (unsigned char*)to_child->string, to_child);

                    to_child = to_child->next;
1018 1019 1020 1021 1022 1023 1024 1025 1026
                }
            }
            return;
        }

        default:
            break;
    }
}
1027

1028
CJSON_PUBLIC(cJSON *) cJSONUtils_GeneratePatches(cJSON * const from, cJSON * const to)
1029
{
1030
    cJSON *patches = cJSON_CreateArray();
1031
    cJSONUtils_CompareToPatch(patches, (const unsigned char*)"", from, to);
1032

1033 1034
    return patches;
}
1035

M
Max Bruckner 已提交
1036
/* sort lists using mergesort */
1037 1038
static cJSON *cJSONUtils_SortList(cJSON *list)
{
M
Max Bruckner 已提交
1039 1040
    cJSON *first = list;
    cJSON *second = list;
M
Max Bruckner 已提交
1041 1042 1043
    cJSON *current_item = list;
    cJSON *result = list;
    cJSON *result_tail = NULL;
1044

M
Max Bruckner 已提交
1045
    if ((list == NULL) || (list->next == NULL))
M
Max Bruckner 已提交
1046 1047
    {
        /* One entry is sorted already. */
M
Max Bruckner 已提交
1048
        return result;
M
Max Bruckner 已提交
1049
    }
1050

M
Max Bruckner 已提交
1051
    while ((current_item != NULL) && (current_item->next != NULL) && (cJSONUtils_strcasecmp((unsigned char*)current_item->string, (unsigned char*)current_item->next->string) < 0))
M
Max Bruckner 已提交
1052 1053
    {
        /* Test for list sorted. */
M
Max Bruckner 已提交
1054
        current_item = current_item->next;
M
Max Bruckner 已提交
1055
    }
M
Max Bruckner 已提交
1056
    if ((current_item == NULL) || (current_item->next == NULL))
M
Max Bruckner 已提交
1057 1058
    {
        /* Leave sorted lists unmodified. */
M
Max Bruckner 已提交
1059
        return result;
M
Max Bruckner 已提交
1060
    }
1061

M
Max Bruckner 已提交
1062 1063 1064
    /* reset pointer to the beginning */
    current_item = list;
    while (current_item != NULL)
M
Max Bruckner 已提交
1065 1066 1067
    {
        /* Walk two pointers to find the middle. */
        second = second->next;
M
Max Bruckner 已提交
1068 1069 1070
        current_item = current_item->next;
        /* advances current_item two steps at a time */
        if (current_item != NULL)
M
Max Bruckner 已提交
1071
        {
M
Max Bruckner 已提交
1072
            current_item = current_item->next;
M
Max Bruckner 已提交
1073 1074
        }
    }
M
Max Bruckner 已提交
1075
    if ((second != NULL) && (second->prev != NULL))
M
Max Bruckner 已提交
1076 1077
    {
        /* Split the lists */
1078
        second->prev->next = NULL;
M
Max Bruckner 已提交
1079
    }
1080

M
Max Bruckner 已提交
1081 1082 1083
    /* Recursively sort the sub-lists. */
    first = cJSONUtils_SortList(first);
    second = cJSONUtils_SortList(second);
M
Max Bruckner 已提交
1084
    result = NULL;
M
Max Bruckner 已提交
1085

M
Max Bruckner 已提交
1086 1087
    /* Merge the sub-lists */
    while ((first != NULL) && (second != NULL))
M
Max Bruckner 已提交
1088
    {
M
Max Bruckner 已提交
1089
        cJSON *smaller = NULL;
1090
        if (cJSONUtils_strcasecmp((unsigned char*)first->string, (unsigned char*)second->string) < 0)
M
Max Bruckner 已提交
1091
        {
M
Max Bruckner 已提交
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
            smaller = first;
        }
        else
        {
            smaller = second;
        }

        if (result == NULL)
        {
            /* start merged list with the smaller element */
            result_tail = smaller;
            result = smaller;
        }
        else
        {
            /* add smaller element to the list */
            result_tail->next = smaller;
            smaller->prev = result_tail;
            result_tail = smaller;
        }

        if (first == smaller)
        {
M
Max Bruckner 已提交
1115 1116 1117 1118 1119 1120 1121
            first = first->next;
        }
        else
        {
            second = second->next;
        }
    }
M
Max Bruckner 已提交
1122 1123

    if (first != NULL)
M
Max Bruckner 已提交
1124 1125
    {
        /* Append rest of first list. */
M
Max Bruckner 已提交
1126
        if (result == NULL)
M
Max Bruckner 已提交
1127 1128 1129
        {
            return first;
        }
M
Max Bruckner 已提交
1130 1131
        result_tail->next = first;
        first->prev = result_tail;
M
Max Bruckner 已提交
1132
    }
M
Max Bruckner 已提交
1133
    if (second != NULL)
M
Max Bruckner 已提交
1134 1135
    {
        /* Append rest of second list */
M
Max Bruckner 已提交
1136
        if (result == NULL)
M
Max Bruckner 已提交
1137 1138 1139
        {
            return second;
        }
M
Max Bruckner 已提交
1140 1141
        result_tail->next = second;
        second->prev = result_tail;
M
Max Bruckner 已提交
1142 1143
    }

M
Max Bruckner 已提交
1144
    return result;
1145 1146
}

M
Max Bruckner 已提交
1147
CJSON_PUBLIC(void) cJSONUtils_SortObject(cJSON * const object)
M
Max Bruckner 已提交
1148 1149 1150
{
    object->child = cJSONUtils_SortList(object->child);
}
1151

M
Max Bruckner 已提交
1152
CJSON_PUBLIC(cJSON *) cJSONUtils_MergePatch(cJSON *target, const cJSON * const patch)
1153
{
M
Max Bruckner 已提交
1154 1155
    cJSON *patch_child = NULL;

1156
    if (!cJSON_IsObject(patch))
M
Max Bruckner 已提交
1157 1158 1159 1160 1161
    {
        /* scalar value, array or NULL, just duplicate */
        cJSON_Delete(target);
        return cJSON_Duplicate(patch, 1);
    }
1162

1163
    if (!cJSON_IsObject(target))
M
Max Bruckner 已提交
1164 1165 1166 1167 1168
    {
        cJSON_Delete(target);
        target = cJSON_CreateObject();
    }

M
Max Bruckner 已提交
1169 1170
    patch_child = patch->child;
    while (patch_child != NULL)
M
Max Bruckner 已提交
1171
    {
M
Max Bruckner 已提交
1172
        if (cJSON_IsNull(patch_child))
M
Max Bruckner 已提交
1173 1174
        {
            /* NULL is the indicator to remove a value, see RFC7396 */
M
Max Bruckner 已提交
1175
            cJSON_DeleteItemFromObject(target, patch_child->string);
M
Max Bruckner 已提交
1176 1177 1178
        }
        else
        {
M
Max Bruckner 已提交
1179 1180
            cJSON *replace_me = cJSON_DetachItemFromObject(target, patch_child->string);
            cJSON_AddItemToObject(target, patch_child->string, cJSONUtils_MergePatch(replace_me, patch_child));
M
Max Bruckner 已提交
1181
        }
M
Max Bruckner 已提交
1182
        patch_child = patch_child->next;
M
Max Bruckner 已提交
1183 1184
    }
    return target;
1185
}
1186

1187
CJSON_PUBLIC(cJSON *) cJSONUtils_GenerateMergePatch(cJSON * const from, cJSON * const to)
1188
{
1189 1190
    cJSON *from_child = NULL;
    cJSON *to_child = NULL;
1191
    cJSON *patch = NULL;
1192
    if (to == NULL)
1193 1194 1195 1196
    {
        /* patch to delete everything */
        return cJSON_CreateNull();
    }
1197
    if (!cJSON_IsObject(to) || !cJSON_IsObject(from))
1198 1199 1200 1201 1202 1203 1204
    {
        return cJSON_Duplicate(to, 1);
    }

    cJSONUtils_SortObject(from);
    cJSONUtils_SortObject(to);

1205 1206
    from_child = from->child;
    to_child = to->child;
1207
    patch = cJSON_CreateObject();
1208
    while (from_child || to_child)
1209
    {
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
        int diff;
        if (from_child != NULL)
        {
            if (to_child != NULL)
            {
                diff = strcmp(from_child->string, to_child->string);
            }
            else
            {
                diff = -1;
            }
        }
        else
        {
            diff = 1;
        }

        if (diff < 0)
1228 1229
        {
            /* from has a value that to doesn't have -> remove */
1230 1231 1232
            cJSON_AddItemToObject(patch, from_child->string, cJSON_CreateNull());

            from_child = from_child->next;
1233
        }
1234
        else if (diff > 0)
1235 1236
        {
            /* to has a value that from doesn't have -> add to patch */
1237 1238 1239
            cJSON_AddItemToObject(patch, to_child->string, cJSON_Duplicate(to_child, 1));

            to_child = to_child->next;
1240 1241 1242 1243
        }
        else
        {
            /* object key exists in both objects */
1244
            if (cJSONUtils_Compare(from_child, to_child))
1245 1246
            {
                /* not identical --> generate a patch */
1247
                cJSON_AddItemToObject(patch, to_child->string, cJSONUtils_GenerateMergePatch(from_child, to_child));
1248
            }
1249

1250
            /* next key in the object */
1251 1252
            from_child = from_child->next;
            to_child = to_child->next;
1253 1254
        }
    }
1255
    if (patch->child == NULL)
1256
    {
1257
        /* no patch generated */
1258
        cJSON_Delete(patch);
1259
        return NULL;
1260 1261 1262
    }

    return patch;
M
Max Bruckner 已提交
1263
}