cJSON_Utils.c 33.7 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
static unsigned char* cJSONUtils_strdup(const unsigned char* const string)
34
{
M
Max Bruckner 已提交
35
    size_t length = 0;
36
    unsigned char *copy = NULL;
37

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

    return copy;
}

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

    if (string1 == string2)
M
Max Bruckner 已提交
58
    {
M
Max Bruckner 已提交
59
        return 0;
M
Max Bruckner 已提交
60
    }
M
Max Bruckner 已提交
61 62

    for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++)
M
Max Bruckner 已提交
63
    {
M
Max Bruckner 已提交
64
        if (*string1 == '\0')
M
Max Bruckner 已提交
65 66 67 68 69
        {
            return 0;
        }
    }

M
Max Bruckner 已提交
70
    return tolower(*string1) - tolower(*string2);
71 72
}

M
Max Bruckner 已提交
73 74
/* 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)
75
{
M
Max Bruckner 已提交
76
    if ((name == NULL) || (pointer == NULL))
77
    {
M
Max Bruckner 已提交
78
        return 1;
79
    }
M
Max Bruckner 已提交
80 81

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

    return 0;
108 109
}

110 111
/* 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)
112
{
113 114
    size_t length;
    for (length = 0; *string != '\0'; (void)string++, length++)
115
    {
116 117
        /* character needs to be escaped? */
        if ((*string == '~') || (*string == '/'))
118
        {
119
            length++;
120 121 122
        }
    }

123
    return length;
124
}
125

126 127
/* 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)
128
{
129
    for (; source[0] != '\0'; (void)source++, destination++)
130
    {
131
        if (source[0] == '/')
132
        {
133 134
            destination[1] = '1';
            destination++;
135
        }
136
        else if (source[0] == '~')
137
        {
138 139 140
            destination[0] = '~';
            destination[1] = '1';
            destination++;
141 142 143
        }
        else
        {
144
            destination[0] = source[0];
145 146 147
        }
    }

148
    destination[0] = '\0';
149 150
}

151
CJSON_PUBLIC(char *) cJSONUtils_FindPointerFromObjectTo(const cJSON * const object, const cJSON * const target)
152
{
153 154
    size_t child_index = 0;
    cJSON *current_child = 0;
155

156 157 158
    if (object == target)
    {
        /* found */
159
        return (char*)cJSONUtils_strdup((const unsigned char*)"");
160
    }
161

162 163
    /* 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++)
164
    {
165 166 167
        unsigned char *target_pointer = (unsigned char*)cJSONUtils_FindPointerFromObjectTo(current_child, target);
        /* found the target? */
        if (target_pointer != NULL)
168
        {
169
            if (cJSON_IsArray(object))
170 171
            {
                /* reserve enough memory for a 64 bit integer + '/' and '\0' */
172
                unsigned char *full_pointer = (unsigned char*)cJSON_malloc(strlen((char*)target_pointer) + 20 + sizeof("/"));
173 174 175
                /* 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 */
176
                if (child_index > ULONG_MAX)
177
                {
178
                    cJSON_free(target_pointer);
179 180
                    return NULL;
                }
181 182
                sprintf((char*)full_pointer, "/%lu%s", (unsigned long)child_index, target_pointer); /* /<array_index><path> */
                cJSON_free(target_pointer);
183

184
                return (char*)full_pointer;
185
            }
186 187

            if (cJSON_IsObject(object))
188
            {
189 190 191 192 193
                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);
194

195
                return (char*)full_pointer;
196 197 198
            }

            /* reached leaf of the tree, found nothing */
199
            cJSON_free(target_pointer);
200
            return NULL;
201 202 203 204
        }
    }

    /* not found */
205
    return NULL;
206 207
}

208 209 210 211 212 213 214 215 216 217 218 219 220
/* 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;
}

221 222 223 224 225 226 227 228 229 230 231
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;
    }

232
    for (position = 0; (pointer[position] >= '0') && (pointer[0] <= '9'); position++)
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
    {
        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 已提交
248
CJSON_PUBLIC(cJSON *) cJSONUtils_GetPointer(cJSON * const object, const char *pointer)
249
{
M
Max Bruckner 已提交
250
    cJSON *current_element = object;
251
    /* follow path of the pointer */
M
Max Bruckner 已提交
252
    while ((pointer[0] == '/') && (current_element != NULL))
253
    {
M
Max Bruckner 已提交
254 255
        pointer++;
        if (cJSON_IsArray(current_element))
256
        {
257
            size_t index = 0;
258
            if (!decode_array_index_from_pointer((const unsigned char*)pointer, &index))
259
            {
260
                return NULL;
261
            }
262

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

M
Max Bruckner 已提交
285
    return current_element;
286 287
}

288
/* JSON Patch implementation. */
289
static void cJSONUtils_InplaceDecodePointerString(unsigned char *string)
290
{
291
    unsigned char *decoded_string = string;
292 293 294 295 296

    if (string == NULL) {
        return;
    }

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

            string++;
        }
317 318
    }

319
    decoded_string[0] = '\0';
320 321
}

322 323 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
/* 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;
}

355
static cJSON *cJSONUtils_PatchDetach(cJSON *object, const unsigned char *path)
356
{
M
Max Bruckner 已提交
357 358
    unsigned char *parent_pointer = NULL;
    unsigned char *child_pointer = NULL;
359
    cJSON *parent = NULL;
M
Max Bruckner 已提交
360
    cJSON *detached_item = NULL;
361 362

    /* copy path and split it in parent and child */
M
Max Bruckner 已提交
363 364 365
    parent_pointer = cJSONUtils_strdup(path);
    if (parent_pointer == NULL) {
        goto cleanup;
366 367
    }

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

M
Max Bruckner 已提交
377 378
    parent = cJSONUtils_GetPointer(object, (char*)parent_pointer);
    cJSONUtils_InplaceDecodePointerString(child_pointer);
379

M
Max Bruckner 已提交
380
    if (cJSON_IsArray(parent))
381
    {
382
        size_t index = 0;
M
Max Bruckner 已提交
383
        if (!decode_array_index_from_pointer(child_pointer, &index))
384
        {
M
Max Bruckner 已提交
385
            goto cleanup;
386
        }
M
Max Bruckner 已提交
387
        detached_item = detach_item_from_array(parent, index);
388
    }
389
    else if (cJSON_IsObject(parent))
390
    {
M
Max Bruckner 已提交
391 392 393 394 395 396 397 398 399 400 401 402
        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);
403
    }
404

M
Max Bruckner 已提交
405
    return detached_item;
406 407
}

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

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

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

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

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

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

M
Max Bruckner 已提交
488 489 490
        default:
            break;
    }
M
Max Bruckner 已提交
491

M
Max Bruckner 已提交
492 493
    /* null, true or false */
    return 0;
494 495
}

496 497 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
/* 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 已提交
534 535
enum patch_operation { INVALID, ADD, REMOVE, REPLACE, MOVE, COPY, TEST };

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

M
Max Bruckner 已提交
544
    if (strcmp(operation->valuestring, "add") == 0)
M
Max Bruckner 已提交
545
    {
M
Max Bruckner 已提交
546
        return ADD;
M
Max Bruckner 已提交
547
    }
548

M
Max Bruckner 已提交
549
    if (strcmp(operation->valuestring, "remove") == 0)
M
Max Bruckner 已提交
550
    {
M
Max Bruckner 已提交
551
        return REMOVE;
M
Max Bruckner 已提交
552
    }
M
Max Bruckner 已提交
553 554

    if (strcmp(operation->valuestring, "replace") == 0)
M
Max Bruckner 已提交
555
    {
M
Max Bruckner 已提交
556
        return REPLACE;
M
Max Bruckner 已提交
557
    }
M
Max Bruckner 已提交
558 559

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

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

    if (strcmp(operation->valuestring, "test") == 0)
M
Max Bruckner 已提交
570
    {
M
Max Bruckner 已提交
571
        return TEST;
M
Max Bruckner 已提交
572
    }
M
Max Bruckner 已提交
573 574 575 576 577 578 579 580

    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 已提交
581
    {
M
Max Bruckner 已提交
582
        return;
M
Max Bruckner 已提交
583
    }
M
Max Bruckner 已提交
584 585 586 587 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

    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 已提交
613
    {
M
Max Bruckner 已提交
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
        /* 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 已提交
630
    }
631

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

M
Max Bruckner 已提交
639
            overwrite_item(object, invalid);
640

M
Max Bruckner 已提交
641 642
            status = 0;
            goto cleanup;
643 644 645 646 647 648 649 650
        }

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

            value = cJSON_Duplicate(value, 1);
            if (value == NULL)
            {
                /* out of memory for add/replace. */
M
Max Bruckner 已提交
659 660
                status = 8;
                goto cleanup;
661 662
            }

M
Max Bruckner 已提交
663
            overwrite_item(object, *value);
664 665 666

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

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

            status = 0;
            goto cleanup;
678 679 680
        }
    }

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

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

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

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

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

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

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

cleanup:
    if (value != NULL)
M
Max Bruckner 已提交
806 807 808
    {
        cJSON_Delete(value);
    }
M
Max Bruckner 已提交
809 810 811 812
    if (parent_pointer != NULL)
    {
        cJSON_free(parent_pointer);
    }
M
Max Bruckner 已提交
813

M
Max Bruckner 已提交
814
    return status;
M
Max Bruckner 已提交
815
}
816

M
Max Bruckner 已提交
817
CJSON_PUBLIC(int) cJSONUtils_ApplyPatches(cJSON * const object, const cJSON * const patches)
818
{
M
Max Bruckner 已提交
819 820
    const cJSON *current_patch = NULL;
    int status = 0;
821

822
    if (!cJSON_IsArray(patches))
823 824 825 826
    {
        /* malformed patches. */
        return 1;
    }
M
Max Bruckner 已提交
827 828

    if (patches != NULL)
829
    {
M
Max Bruckner 已提交
830
        current_patch = patches->child;
831
    }
M
Max Bruckner 已提交
832 833

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

    return 0;
844
}
845

M
Max Bruckner 已提交
846
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)
847
{
848
    cJSON *patch = cJSON_CreateObject();
M
Max Bruckner 已提交
849
    if (patch == NULL)
850
    {
M
Max Bruckner 已提交
851
        return;
852
    }
M
Max Bruckner 已提交
853 854 855
    cJSON_AddItemToObject(patch, "op", cJSON_CreateString((const char*)operation));

    if (suffix == NULL)
856
    {
857
        cJSON_AddItemToObject(patch, "path", cJSON_CreateString((const char*)path));
858
    }
M
Max Bruckner 已提交
859 860 861 862 863 864 865 866 867 868 869 870 871 872
    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)
873
    {
M
Max Bruckner 已提交
874
        cJSON_AddItemToObject(patch, "value", cJSON_Duplicate(value, 1));
875 876
    }
    cJSON_AddItemToArray(patches, patch);
877 878
}

879
CJSON_PUBLIC(void) cJSONUtils_AddPatchToArray(cJSON * const array, const char * const operation, const char * const path, const cJSON * const value)
M
Max Bruckner 已提交
880
{
881
    cJSONUtils_GeneratePatch(array, (const unsigned char*)operation, (const unsigned char*)path, NULL, value);
M
Max Bruckner 已提交
882
}
883

884
static void cJSONUtils_CompareToPatch(cJSON * const patches, const unsigned char * const path, cJSON * const from, cJSON * const to)
885
{
886 887 888 889 890
    if ((from == NULL) || (to == NULL))
    {
        return;
    }

891
    if ((from->type & 0xFF) != (to->type & 0xFF))
892
    {
893
        cJSONUtils_GeneratePatch(patches, (const unsigned char*)"replace", path, 0, to);
894 895 896
        return;
    }

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

        case cJSON_String:
            if (strcmp(from->valuestring, to->valuestring) != 0)
            {
909
                cJSONUtils_GeneratePatch(patches, (const unsigned char*)"replace", path, NULL, to);
910 911
            }
            return;
912

913 914
        case cJSON_Array:
        {
915 916 917 918 919 920 921
            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++)
922
            {
923 924 925
                /* 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 */
926
                if (index > ULONG_MAX)
927
                {
928
                    free(new_path);
929 930
                    return;
                }
931 932
                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);
933
            }
934

935
            /* remove leftover elements from 'from' that are not in 'to' */
936
            for (; (from_child != NULL); (void)(from_child = from_child->next))
937
            {
938 939 940
                /* 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 */
941
                if (index > ULONG_MAX)
942
                {
943
                    free(new_path);
944 945
                    return;
                }
946 947
                sprintf((char*)new_path, "%lu", (unsigned long)index);
                cJSONUtils_GeneratePatch(patches, (const unsigned char*)"remove", path, new_path, NULL);
948 949
            }
            /* add new elements in 'to' that were not in 'from' */
950
            for (; (to_child != NULL); (void)(to_child = to_child->next), index++)
951
            {
952
                cJSONUtils_GeneratePatch(patches, (const unsigned char*)"add", path, (const unsigned char*)"-", to_child);
953
            }
954
            free(new_path);
955 956 957 958 959
            return;
        }

        case cJSON_Object:
        {
960 961
            cJSON *from_child = NULL;
            cJSON *to_child = NULL;
962 963 964
            cJSONUtils_SortObject(from);
            cJSONUtils_SortObject(to);

965 966
            from_child = from->child;
            to_child = to->child;
967
            /* for all object values in the object with more of them */
968
            while ((from_child != NULL) || (to_child != NULL))
969
            {
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
                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)
985 986
                {
                    /* both object keys are the same */
987 988 989 990 991 992 993
                    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);

994
                    /* create a patch for the element */
995 996 997 998 999
                    cJSONUtils_CompareToPatch(patches, new_path, from_child, to_child);
                    free(new_path);

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

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

                    to_child = to_child->next;
1014 1015 1016 1017 1018 1019 1020 1021 1022
                }
            }
            return;
        }

        default:
            break;
    }
}
1023

1024
CJSON_PUBLIC(cJSON *) cJSONUtils_GeneratePatches(cJSON * const from, cJSON * const to)
1025
{
1026
    cJSON *patches = cJSON_CreateArray();
1027
    cJSONUtils_CompareToPatch(patches, (const unsigned char*)"", from, to);
1028

1029 1030
    return patches;
}
1031

M
Max Bruckner 已提交
1032
/* sort lists using mergesort */
1033 1034
static cJSON *cJSONUtils_SortList(cJSON *list)
{
M
Max Bruckner 已提交
1035 1036 1037
    cJSON *first = list;
    cJSON *second = list;
    cJSON *ptr = list;
1038

M
Max Bruckner 已提交
1039 1040 1041 1042 1043
    if (!list || !list->next)
    {
        /* One entry is sorted already. */
        return list;
    }
1044

1045
    while (ptr && ptr->next && (cJSONUtils_strcasecmp((unsigned char*)ptr->string, (unsigned char*)ptr->next->string) < 0))
M
Max Bruckner 已提交
1046 1047 1048 1049 1050 1051 1052 1053 1054
    {
        /* Test for list sorted. */
        ptr = ptr->next;
    }
    if (!ptr || !ptr->next)
    {
        /* Leave sorted lists unmodified. */
        return list;
    }
1055

M
Max Bruckner 已提交
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
    /* reset ptr to the beginning */
    ptr = list;
    while (ptr)
    {
        /* Walk two pointers to find the middle. */
        second = second->next;
        ptr = ptr->next;
        /* advances ptr two steps at a time */
        if (ptr)
        {
            ptr = ptr->next;
        }
    }
    if (second && second->prev)
    {
        /* Split the lists */
1072
        second->prev->next = NULL;
M
Max Bruckner 已提交
1073
    }
1074

M
Max Bruckner 已提交
1075 1076 1077
    /* Recursively sort the sub-lists. */
    first = cJSONUtils_SortList(first);
    second = cJSONUtils_SortList(second);
1078
    list = ptr = NULL;
M
Max Bruckner 已提交
1079 1080 1081

    while (first && second) /* Merge the sub-lists */
    {
1082
        if (cJSONUtils_strcasecmp((unsigned char*)first->string, (unsigned char*)second->string) < 0)
M
Max Bruckner 已提交
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
        {
            if (!list)
            {
                /* start merged list with the first element of the first list */
                list = ptr = first;
            }
            else
            {
                /* add first element of first list to merged list */
                ptr->next = first;
                first->prev = ptr;
                ptr = first;
            }
            first = first->next;
        }
        else
        {
            if (!list)
            {
                /* start merged list with the first element of the second list */
                list = ptr = second;
            }
            else
            {
                /* add first element of second list to merged list */
                ptr->next = second;
                second->prev = ptr;
                ptr = second;
            }
            second = second->next;
        }
    }
    if (first)
    {
        /* Append rest of first list. */
        if (!list)
        {
            return first;
        }
        ptr->next = first;
        first->prev = ptr;
    }
    if (second)
    {
        /* Append rest of second list */
        if (!list)
        {
            return second;
        }
        ptr->next = second;
        second->prev = ptr;
    }

    return list;
1137 1138
}

1139
CJSON_PUBLIC(void) cJSONUtils_SortObject(cJSON *object)
M
Max Bruckner 已提交
1140 1141 1142
{
    object->child = cJSONUtils_SortList(object->child);
}
1143

1144
CJSON_PUBLIC(cJSON *) cJSONUtils_MergePatch(cJSON *target, cJSON *patch)
1145
{
1146
    if (!cJSON_IsObject(patch))
M
Max Bruckner 已提交
1147 1148 1149 1150 1151
    {
        /* scalar value, array or NULL, just duplicate */
        cJSON_Delete(target);
        return cJSON_Duplicate(patch, 1);
    }
1152

1153
    if (!cJSON_IsObject(target))
M
Max Bruckner 已提交
1154 1155 1156 1157 1158 1159 1160 1161
    {
        cJSON_Delete(target);
        target = cJSON_CreateObject();
    }

    patch = patch->child;
    while (patch)
    {
1162
        if (cJSON_IsNull(patch))
M
Max Bruckner 已提交
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
        {
            /* NULL is the indicator to remove a value, see RFC7396 */
            cJSON_DeleteItemFromObject(target, patch->string);
        }
        else
        {
            cJSON *replaceme = cJSON_DetachItemFromObject(target, patch->string);
            cJSON_AddItemToObject(target, patch->string, cJSONUtils_MergePatch(replaceme, patch));
        }
        patch = patch->next;
    }
    return target;
1175
}
1176

1177
CJSON_PUBLIC(cJSON *) cJSONUtils_GenerateMergePatch(cJSON *from, cJSON *to)
1178
{
1179
    cJSON *patch = NULL;
1180 1181 1182 1183 1184
    if (!to)
    {
        /* patch to delete everything */
        return cJSON_CreateNull();
    }
1185
    if (!cJSON_IsObject(to) || !cJSON_IsObject(from))
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
    {
        return cJSON_Duplicate(to, 1);
    }

    cJSONUtils_SortObject(from);
    cJSONUtils_SortObject(to);

    from = from->child;
    to = to->child;
    patch = cJSON_CreateObject();
    while (from || to)
    {
        int compare = from ? (to ? strcmp(from->string, to->string) : -1) : 1;
        if (compare < 0)
        {
            /* from has a value that to doesn't have -> remove */
            cJSON_AddItemToObject(patch, from->string, cJSON_CreateNull());
            from = from->next;
        }
        else if (compare > 0)
        {
            /* to has a value that from doesn't have -> add to patch */
            cJSON_AddItemToObject(patch, to->string, cJSON_Duplicate(to, 1));
            to = to->next;
        }
        else
        {
            /* object key exists in both objects */
            if (cJSONUtils_Compare(from, to))
            {
                /* not identical --> generate a patch */
                cJSON_AddItemToObject(patch, to->string, cJSONUtils_GenerateMergePatch(from, to));
            }
            /* next key in the object */
            from = from->next;
            to = to->next;
        }
    }
    if (!patch->child)
    {
        cJSON_Delete(patch);
1227
        return NULL;
1228 1229 1230
    }

    return patch;
M
Max Bruckner 已提交
1231
}