Coverage Report

Created: 2026-12-01 06:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gpsd/gpsd-3.28.1~dev/libgps/json.c
Line
Count
Source
1
/****************************************************************************
2
 *
3
 *  NAME
4
 *  json.c - parse JSON into fixed-extent data structures
5
 *
6
 *  DESCRIPTION
7
 *  This module parses a large subset of JSON (JavaScript Object
8
 *  Notation).  Unlike more general JSON parsers, it doesn't use malloc(3)
9
 *  and doesn't support polymorphism; you need to give it a set of
10
 *  template structures describing the expected shape of the incoming
11
 *  JSON, and it will error out if that shape is not matched.  When the
12
 *  parse succeeds, attribute values will be extracted into static
13
 *  locations specified in the template structures.
14
 *
15
 *  The "shape" of a JSON object in the type signature of its
16
 *  attributes (and attribute values, and so on recursively down through
17
 *  all nestings of objects and arrays).  This parser is indifferent to
18
 *  the order of attributes at any level, but you have to tell it in
19
 *  advance what the type of each attribute value will be and where the
20
 *  parsed value will be stored. The template structures may supply
21
 *  default values to be used when an expected attribute is omitted.
22
 *
23
 *  The preceding paragraph told one fib.  A single attribute may
24
 *  actually have a span of multiple specifications with different
25
 *  syntactically distinguishable types (e.g. string vs. real vs. integer
26
 *  vs. boolean, but not signed integer vs. unsigned integer).  The parser
27
 *  will match the right spec against the actual data.
28
 *
29
 *  The dialect this parses has some limitations.  First, it cannot
30
 *  recognize the JSON "null" value.  Secondly, arrays may not have
31
 *  character values as elements (this limitation could be easily removed
32
 *  if required). Third, all elements of an array must be of the same
33
 *  type.  Fourth, it can not handle NaN's in doubles (Issue 53150).
34
 *
35
 *  There are separate entry points for beginning a parse of either
36
 *  JSON object or a JSON array. JSON "float" quantities are actually
37
 *  stored as doubles.
38
 *
39
 *  This parser processes object arrays in one of two different ways,
40
 *  defending on whether the array subtype is declared as object or
41
 *  structobject.
42
 *
43
 *  Object arrays take one base address per object subfield, and are
44
 *  mapped into parallel C arrays (one per subfield).  Strings are not
45
 *  supported in this kind of array, as they don't have a "natural" size
46
 *  to use as an offset multiplier.
47
 *
48
 *  Structobjects arrays are a way to parse a list of objects to a set
49
 *  of modifications to a corresponding array of C structs.  The trick is
50
 *  that the array object initialization has to specify both the C struct
51
 *  array's base address and the stride length (the size of the C struct).
52
 *  If you initialize the offset fields with the correct offsetof calls,
53
 *  everything will work. Strings are supported but all string storage
54
 *  has to be inline in the struct.
55
 *
56
 *  NOTE
57
 *  This code has been spun out, packaged, and documented as a
58
 *  reusable module; search for "microjson".
59
 *
60
 *  PERMISSIONS
61
 *  This file is Copyright by the GPSD project
62
 *  SPDX-License-Identifier: BSD-2-clause
63
 *
64
 ***************************************************************************/
65
#include "../include/gpsd_config.h" // must be before all includes
66
67
#include <math.h>                   // for HUGE_VAL
68
#include <stdarg.h>                 // for va_arg(), etc.
69
#include <stdbool.h>
70
#include <stdio.h>
71
#include <stdlib.h>
72
#include <string.h>
73
74
#include "../include/compiler.h"    // for FALLTHROUGH
75
#include "../include/os_compat.h"
76
#include "../include/json.h"
77
78
#include "../include/gps.h"         // for safe_atof() prototype
79
#include "../include/strfuncs.h"
80
#include "../include/timespec.h"
81
82
static int debuglevel = 0;
83
static FILE *debugjsfp = NULL;
84
85
// control the level and destination of debug trace messages
86
void json_enable_debug(int level, FILE *fp)
87
0
{
88
0
    debuglevel = level;
89
0
    debugjsfp = fp;
90
0
}
91
92
static void json_trace(const char *, ...);
93
94
// assemble command in printf(3) style
95
static void json_trace(const char *fmt, ...)
96
0
{
97
0
    va_list ap;
98
99
0
    va_start(ap, fmt);
100
0
    (void)vfprintf(debugjsfp, fmt, ap);
101
0
    va_end(ap);
102
0
}
103
104
// HOTCODE!  Do not change without profiling.
105
// major speedup by checking debuglvl before callin json_trace()
106
#define json_debug_trace(lvl, fmt, ...)                \
107
1.36M
        do {                                              \
108
1.36M
            if (unlikely((lvl) <= debuglevel &&           \
109
1.36M
                         NULL != debugjsfp) ) {            \
110
0
                json_trace(fmt, __VA_ARGS__);              \
111
0
            }                                             \
112
1.36M
        } while (0)
113
114
115
static char *json_target_address(const struct json_attr_t *cursor,
116
                                 const struct json_array_t
117
                                 *parent, int offset)
118
193k
{
119
193k
    char *targetaddr = NULL;
120
193k
    if (NULL == parent ||
121
106k
        parent->element_type != t_structobject) {
122
        // ordinary case - use the address in the cursor structure
123
106k
        switch (cursor->type) {
124
0
        case t_byte:
125
0
            targetaddr = (char *)&cursor->addr.byte[offset];
126
0
            break;
127
865
        case t_ubyte:
128
865
            targetaddr = (char *)&cursor->addr.ubyte[offset];
129
865
            break;
130
22.4k
        case t_ignore:
131
22.4k
            targetaddr = NULL;
132
22.4k
            break;
133
18.7k
        case t_integer:
134
18.7k
            targetaddr = (char *)&cursor->addr.integer[offset];
135
18.7k
            break;
136
6.06k
        case t_uinteger:
137
6.06k
            targetaddr = (char *)&cursor->addr.uinteger[offset];
138
6.06k
            break;
139
1.48k
        case t_longint:
140
1.48k
            targetaddr = (char *)&cursor->addr.longint[offset];
141
1.48k
            break;
142
571
        case t_ulongint:
143
571
            targetaddr = (char *)&cursor->addr.ulongint[offset];
144
571
            break;
145
0
        case t_short:
146
0
            targetaddr = (char *)&cursor->addr.shortint[offset];
147
0
            break;
148
0
        case t_ushort:
149
0
            targetaddr = (char *)&cursor->addr.ushortint[offset];
150
0
            break;
151
3.98k
        case t_time:
152
3.98k
            targetaddr = (char *)&cursor->addr.ts[offset];
153
3.98k
            break;
154
0
        case t_timespec:
155
0
            targetaddr = (char *)&cursor->addr.ts[offset];
156
0
            break;
157
35.7k
        case t_real:
158
35.7k
            targetaddr = (char *)&cursor->addr.real[offset];
159
35.7k
            break;
160
7.26k
        case t_string:
161
7.26k
            targetaddr = cursor->addr.string;
162
7.26k
            break;
163
1.59k
        case t_boolean:
164
1.59k
            targetaddr = (char *)&cursor->addr.boolean[offset];
165
1.59k
            break;
166
1.10k
        case t_character:
167
1.10k
            targetaddr = (char *)&cursor->addr.character[offset];
168
1.10k
            break;
169
729
        case t_array:
170
729
            FALLTHROUGH
171
6.20k
        case t_check:
172
6.20k
            FALLTHROUGH
173
6.20k
        case t_object:
174
6.20k
            FALLTHROUGH
175
6.20k
        case t_structobject:
176
6.20k
            FALLTHROUGH
177
6.20k
        default:
178
6.20k
            targetaddr = NULL;
179
6.20k
            break;
180
106k
        }
181
106k
    } else {
182
        // tricky case - hacking a member in an array of structures
183
86.9k
        targetaddr =
184
86.9k
            parent->arr.objects.base + (offset * parent->arr.objects.stride) +
185
86.9k
            cursor->addr.offset;
186
86.9k
    }
187
193k
    json_debug_trace(1, "json: Target address for %s (offset %d) is %p\n",
188
193k
                     cursor->attribute, offset, targetaddr);
189
193k
    return targetaddr;
190
193k
}
191
192
193
static int json_internal_read_object(const char *cp,
194
                                     const struct json_attr_t *attrs,
195
                                     const struct json_array_t *parent,
196
                                     int offset,
197
                                     const char **end)
198
11.1k
{
199
11.1k
    enum {
200
11.1k
        init, await_attr, in_attr, await_value, in_val_string,
201
11.1k
        in_escape, in_val_token, post_val, post_element, in_ignore_array
202
11.1k
    } state = 0;
203
11.1k
    char *statenames[] = {
204
11.1k
        "init", "await_attr", "in_attr", "await_value", "in_val_string",
205
11.1k
        "in_escape", "in_val_token", "post_val", "post_element",
206
11.1k
        "in_ignore_array"
207
11.1k
    };
208
11.1k
    char attrbuf[JSON_ATTR_MAX + 1], *pattr = NULL;
209
11.1k
    char valbuf[JSON_VAL_MAX + 1], *pval = NULL;
210
11.1k
    bool value_quoted = false;
211
11.1k
    char uescape[5];            // enough space for 4 hex digits and a NUL
212
11.1k
    const struct json_attr_t *cursor;
213
11.1k
    int substatus, maxlen = 0;
214
11.1k
    unsigned int u;
215
11.1k
    const struct json_enum_t *mp;
216
11.1k
    char *lptr;
217
218
11.1k
    if (NULL != end) {
219
5.64k
        *end = NULL;    // give it a well-defined value on parse failure
220
5.64k
    }
221
11.1k
    memset(valbuf, 0, sizeof(valbuf));
222
223
    // stuff fields with defaults in case they're omitted in the JSON input
224
165k
    for (cursor = attrs; cursor->attribute != NULL; cursor++) {
225
154k
        if (!cursor->nodefault) {
226
154k
            lptr = json_target_address(cursor, parent, offset);
227
154k
            if (NULL != lptr) {
228
143k
                switch (cursor->type) {
229
3.53k
                case t_byte:
230
3.53k
                    lptr[0] = cursor->dflt.byte;
231
3.53k
                    break;
232
22.9k
                case t_ubyte:
233
22.9k
                    lptr[0] = cursor->dflt.ubyte;
234
22.9k
                    break;
235
18.3k
                case t_integer:
236
18.3k
                    memcpy(lptr, &cursor->dflt.integer, sizeof(int));
237
18.3k
                    break;
238
7.79k
                case t_uinteger:
239
7.79k
                    memcpy(lptr, &cursor->dflt.uinteger, sizeof(unsigned int));
240
7.79k
                    break;
241
828
                case t_longint:
242
828
                    memcpy(lptr, &cursor->dflt.longint, sizeof(long));
243
828
                    break;
244
131
                case t_ulongint:
245
131
                    memcpy(lptr, &cursor->dflt.ulongint,
246
131
                           sizeof(unsigned long));
247
131
                    break;
248
3.53k
                case t_short:
249
3.53k
                    memcpy(lptr, &cursor->dflt.shortint, sizeof(short));
250
3.53k
                    break;
251
0
                case t_ushort:
252
0
                    memcpy(lptr, &cursor->dflt.ushortint,
253
0
                           sizeof(unsigned short));
254
0
                    break;
255
1.75k
                case t_time:
256
1.75k
                    memcpy(lptr, &cursor->dflt.ts, sizeof(timespec_t));
257
1.75k
                    break;
258
1.26k
                case t_timespec:
259
1.26k
                    memcpy(lptr, &cursor->dflt.ts, sizeof(timespec_t));
260
1.26k
                    break;
261
59.2k
                case t_real:
262
59.2k
                    memcpy(lptr, &cursor->dflt.real, sizeof(double));
263
59.2k
                    break;
264
11.8k
                case t_string:
265
11.8k
                    if (parent != NULL
266
5.24k
                        && parent->element_type != t_structobject
267
0
                        && offset > 0) {
268
0
                        return JSON_ERR_NOPARSTR;
269
0
                    }
270
11.8k
                    lptr[0] = '\0';
271
11.8k
                    break;
272
4.60k
                case t_boolean:
273
4.60k
                    memcpy(lptr, &cursor->dflt.boolean, sizeof(bool));
274
4.60k
                    break;
275
1.17k
                case t_character:
276
1.17k
                    lptr[0] = cursor->dflt.character;
277
1.17k
                    break;
278
0
                case t_object:  // silences a compiler warning
279
0
                    FALLTHROUGH
280
0
                case t_structobject:
281
0
                    FALLTHROUGH
282
0
                case t_array:
283
0
                    FALLTHROUGH
284
631
                case t_check:
285
631
                    FALLTHROUGH
286
6.25k
                case t_ignore:
287
6.25k
                    break;
288
143k
                }
289
143k
            }
290
154k
        }
291
154k
    }
292
293
11.1k
    json_debug_trace(1, "json: JSON parse of '%s' begins.\n", cp);
294
295
    // parse input JSON
296
594k
    for (; *cp != '\0'; cp++) {
297
591k
        json_debug_trace(2, "json: State %-14s, looking at '%c' (%p)\n",
298
591k
                         statenames[state], *cp, cp);
299
591k
        switch (state) {
300
11.4k
        case init:
301
11.4k
            if (ISSPACE(*cp)) {
302
388
                continue;
303
388
            }
304
11.0k
            if (*cp == '{') {
305
11.0k
                state = await_attr;
306
11.0k
            } else {
307
24
                json_debug_trace(1, "json: %s",
308
24
                                 "Non-WS when expecting object start.\n");
309
24
                if (NULL != end) {
310
24
                    *end = cp;
311
24
                }
312
24
                return JSON_ERR_OBSTART;
313
24
            }
314
11.0k
            break;
315
43.9k
        case await_attr:
316
43.9k
            if (ISSPACE(*cp)) {
317
422
                continue;
318
422
            }
319
43.5k
            if (*cp == '"') {
320
43.2k
                state = in_attr;
321
43.2k
                pattr = attrbuf;
322
43.2k
                if (NULL != end) {
323
6.86k
                    *end = cp;
324
6.86k
                }
325
43.2k
            } else if (*cp == '}') {
326
198
                break;
327
198
            } else {
328
109
                json_debug_trace(1, "json: %s",
329
109
                                 "Non-WS when expecting attribute.\n");
330
109
                if (NULL != end) {
331
1
                    *end = cp;
332
1
                }
333
109
                return JSON_ERR_ATTRSTART;
334
109
            }
335
43.2k
            break;
336
178k
        case in_attr:
337
178k
            if (NULL == pattr) {
338
                // don't update end here, leave at attribute start
339
0
                return JSON_ERR_NULLPTR;
340
0
            }
341
178k
            if (*cp == '"') {
342
43.2k
                *pattr++ = '\0';
343
43.2k
                json_debug_trace(1, "json: Collected attribute name %s\n",
344
43.2k
                                 attrbuf);
345
458k
                for (cursor = attrs; cursor->attribute != NULL; cursor++) {
346
458k
                    json_debug_trace(2, "json: Checking against %s\n",
347
458k
                                     cursor->attribute);
348
458k
                    if (strcmp(cursor->attribute, attrbuf) == 0) {
349
29.3k
                        break;
350
29.3k
                    }
351
429k
                    if (cursor->type == t_ignore &&
352
14.0k
                        strncmp(cursor->attribute, "", 1) == 0) {
353
13.8k
                        break;
354
13.8k
                    }
355
429k
                }
356
43.2k
                if (NULL == cursor->attribute) {
357
75
                    json_debug_trace(1,
358
75
                                     "json: Unknown attribute name '%s'"
359
75
                                     " (attributes begin with '%s').\n",
360
75
                                     attrbuf, attrs->attribute);
361
                    // don't update end here, leave at attribute start
362
75
                    return JSON_ERR_BADATTR;
363
75
                }
364
43.1k
                state = await_value;
365
43.1k
                if (cursor->type == t_string) {
366
863
                    maxlen = (int)cursor->len - 1;
367
42.2k
                } else if (cursor->type == t_check) {
368
2.14k
                    maxlen = (int)strnlen(cursor->dflt.check, JSON_VAL_MAX);
369
40.1k
                } else if (cursor->type == t_time ||
370
37.2k
                           cursor->type == t_ignore) {
371
23.8k
                    maxlen = JSON_VAL_MAX;
372
23.8k
                } else if (NULL != cursor->map) {
373
447
                    maxlen = (int)sizeof(valbuf) - 1;
374
447
                }
375
43.1k
                pval = valbuf;
376
134k
            } else if (pattr >= attrbuf + JSON_ATTR_MAX - 1) {
377
19
                json_debug_trace(1, "json: %s","Attribute name too long.\n");
378
                // don't update end here, leave at attribute start
379
19
                return JSON_ERR_ATTRLEN;
380
134k
            } else {
381
134k
                *pattr++ = *cp;
382
134k
            }
383
178k
            break;
384
178k
        case await_value:
385
45.7k
            if (ISSPACE(*cp) ||
386
45.2k
                *cp == ':') {
387
2.70k
                continue;
388
2.70k
            }
389
43.0k
            if (*cp == '[') {
390
2.88k
                if (cursor->type == t_ignore) {
391
                    /* skip to terminating ], not being fooled by
392
                     * sub arrays, etc.
393
                     * FIXME:  someday  */
394
1.86k
                    state = in_ignore_array;
395
1.86k
                    ;
396
1.86k
                    value_quoted = false;
397
1.86k
                    break;
398
1.86k
                }
399
1.02k
                if (cursor->type != t_array) {
400
28
                    json_debug_trace(1,"json: %s",
401
28
                                     "Saw [ when not expecting array.\n");
402
28
                    if (NULL != end) {
403
2
                        *end = cp;
404
2
                    }
405
28
                    return JSON_ERR_NOARRAY;
406
28
                }
407
995
                substatus = json_read_array(cp, &cursor->addr.array, &cp);
408
995
                if (substatus != 0) {
409
344
                    return substatus;
410
344
                }
411
651
                state = post_element;
412
40.1k
            } else if (cursor->type == t_array) {
413
2
                json_debug_trace(1, "json: %s",
414
2
                                 "Array element was specified, but no [.\n");
415
2
                if (NULL != end) {
416
0
                    *end = cp;
417
0
                }
418
2
                return JSON_ERR_NOBRAK;
419
40.1k
            } else if (*cp == '"') {
420
8.98k
                value_quoted = true;
421
8.98k
                state = in_val_string;
422
8.98k
                pval = valbuf;
423
31.1k
            } else {
424
31.1k
                value_quoted = false;
425
31.1k
                state = in_val_token;
426
31.1k
                pval = valbuf;
427
31.1k
                *pval++ = *cp;
428
31.1k
            }
429
40.7k
            break;
430
101k
        case in_ignore_array:
431
101k
            if (*cp == '"') {
432
27.0k
                if (value_quoted == false) {
433
                    // now in quotes
434
13.6k
                    value_quoted = true;
435
13.6k
                } else {
436
13.4k
                    value_quoted = false;
437
13.4k
                }
438
74.4k
            } else if (*cp == ']') {
439
                // FIXME: does not handle sub arrays, etc.
440
1.65k
                if (value_quoted == false) {
441
1.45k
                    state = post_val;
442
1.45k
                }
443
                // else in quotes, ignore it.
444
1.65k
            }
445
101k
            break;
446
63.4k
        case in_val_string:
447
63.4k
            if (NULL == pval) {
448
                // don't update end here, leave at value start
449
0
                return JSON_ERR_NULLPTR;
450
0
            }
451
63.4k
            if (*cp == '\\') {
452
2.75k
                state = in_escape;
453
60.6k
            } else if (*cp == '"') {
454
8.34k
                *pval++ = '\0';
455
8.34k
                json_debug_trace(1, "json: Collected string value %s\n", valbuf);
456
8.34k
                state = post_val;
457
52.3k
            } else if (pval > valbuf + JSON_VAL_MAX - 1 ||
458
52.3k
                       pval > valbuf + maxlen - 1) {
459
134
                json_debug_trace(1, "json: %s",  "String value too long.\n");
460
                // don't update end here, leave at value start
461
134
                return JSON_ERR_STRLONG;
462
52.2k
            } else {
463
52.2k
                *pval++ = *cp;
464
52.2k
            }
465
63.3k
            break;
466
63.3k
        case in_escape:
467
2.75k
            if (NULL == pval) {
468
                // don't update end here, leave at value start
469
0
                return JSON_ERR_NULLPTR;
470
0
            }
471
2.75k
            if (pval > valbuf + JSON_VAL_MAX - 1 ||
472
2.74k
                pval > valbuf + maxlen) {
473
9
                json_debug_trace(1, "json: %s",  "String value too long.\n");
474
                // don't update end here, leave at value start
475
9
                return JSON_ERR_STRLONG;
476
9
            }
477
2.74k
            switch (*cp) {
478
199
            case 'b':
479
199
                *pval++ = '\b';
480
199
                break;
481
197
            case 'f':
482
197
                *pval++ = '\f';
483
197
                break;
484
197
            case 'n':
485
197
                *pval++ = '\n';
486
197
                break;
487
201
            case 'r':
488
201
                *pval++ = '\r';
489
201
                break;
490
198
            case 't':
491
198
                *pval++ = '\t';
492
198
                break;
493
1.49k
            case 'u': {
494
1.49k
                unsigned n;
495
496
1.49k
                cp++;                       // skip the 'u'
497
                // NetBSD 6 wants the cast
498
6.84k
                for (n = 0; n < 4 && ISXDIGIT(*cp); n++) {
499
5.35k
                    uescape[n] = *cp++;
500
5.35k
                }
501
1.49k
                uescape[n] = '\0';          // terminate
502
1.49k
                --cp;
503
                // ECMA-404 says JSON \u must have 4 hex digits
504
1.49k
                if ((4 != n) ||
505
1.24k
                    (1 != sscanf(uescape, "%4x", &u))) {
506
250
                    return JSON_ERR_BADSTRING;
507
250
                }
508
                // truncate values above 0xff
509
1.24k
                *pval++ = (unsigned char)u;
510
1.24k
            }
511
0
            break;
512
254
            default:            // handles double quote and solidus
513
254
                *pval++ = *cp;
514
254
                break;
515
2.74k
            }
516
2.49k
            state = in_val_string;
517
2.49k
            break;
518
103k
        case in_val_token:
519
103k
            if (NULL == pval) {
520
                // don't update end here, leave at value start
521
0
                return JSON_ERR_NULLPTR;
522
0
            }
523
103k
            if (ISSPACE(*cp) ||
524
103k
                *cp == ',' ||
525
78.4k
                *cp == '}') {
526
30.9k
                *pval = '\0';
527
30.9k
                json_debug_trace(1, "json: Collected token valuen %s\n",
528
30.9k
                                 valbuf);
529
30.9k
                state = post_val;
530
30.9k
                if (*cp == '}' ||
531
30.1k
                    *cp == ',') {
532
30.1k
                    --cp;
533
30.1k
                }
534
72.9k
            } else if (pval > valbuf + JSON_VAL_MAX - 1) {
535
8
                json_debug_trace(1, "json: %s", "Token value too long.\n");
536
                // don't update end here, leave at value start
537
8
                return JSON_ERR_TOKLONG;
538
72.9k
            } else {
539
72.9k
                *pval++ = *cp;
540
72.9k
            }
541
103k
            break;
542
        // coverity[unterminated_case]
543
103k
        case post_val:
544
            // Ignore whitespace after either string or token values.
545
39.6k
            if (ISSPACE(*cp)) {
546
1.92k
                while (*cp != '\0' && ISSPACE(*cp)) {
547
1.43k
                    ++cp;
548
1.43k
                }
549
488
                json_debug_trace(1,
550
488
                                 "json: Skipped trailing whitespace: value \"%s\"\n", valbuf);
551
488
            }
552
            /*
553
             * We know that cursor points at the first spec matching
554
             * the current attribute.  We don't know that it's *the*
555
             * correct spec; our dialect allows there to be any number
556
             * of adjacent ones with the same attrname but different
557
             * types.  Here's where we try to seek forward for a
558
             * matching type/attr pair if we're not looking at one.
559
             */
560
39.6k
            for (;;) {
561
39.6k
                int seeking = cursor->type;
562
563
39.6k
                if (value_quoted &&
564
7.29k
                    (cursor->type == t_string ||
565
6.46k
                     cursor->type == t_time)) {
566
2.70k
                    break;
567
2.70k
                }
568
36.9k
                if ((strcmp(valbuf, "true") == 0 ||
569
34.7k
                     strcmp(valbuf, "false") == 0) &&
570
2.30k
                    seeking == t_boolean) {
571
1.81k
                    break;
572
1.81k
                }
573
35.0k
                if (ISDIGIT(valbuf[0])) {
574
18.3k
                    bool decimal = strchr(valbuf, '.') != NULL;
575
576
18.3k
                    if (decimal &&
577
856
                        seeking == t_real) {
578
220
                        break;
579
220
                    }
580
18.0k
                    if (!decimal && (seeking == t_byte ||
581
17.2k
                                     seeking == t_ubyte ||
582
16.5k
                                     seeking == t_integer ||
583
15.3k
                                     seeking == t_uinteger ||
584
14.6k
                                     seeking == t_longint ||
585
14.0k
                                     seeking == t_ulongint ||
586
13.6k
                                     seeking == t_time ||
587
13.2k
                                     seeking == t_short ||
588
11.3k
                                     seeking == t_ushort)) {
589
6.11k
                        break;
590
6.11k
                    }
591
18.0k
                }
592
28.7k
                if (NULL == cursor[1].attribute) {  // out of possibilities
593
20.0k
                    break;
594
20.0k
                }
595
8.71k
                if (0 != strcmp(cursor[1].attribute, attrbuf)) {
596
8.71k
                    break;
597
8.71k
                }
598
0
                ++cursor;
599
0
            }
600
39.6k
            if (value_quoted &&
601
7.29k
                (cursor->type != t_string &&
602
6.46k
                 cursor->type != t_character &&
603
6.26k
                 cursor->type != t_check &&
604
5.50k
                 cursor->type != t_time &&
605
3.62k
                 cursor->type != t_ignore &&
606
462
                 cursor->map == 0)) {
607
22
                json_debug_trace(1, "json: %s", "Saw quoted value when expecting"
608
22
                                 " non-string.\n");
609
22
                return JSON_ERR_QNONSTRING;
610
22
            }
611
39.5k
            if (!value_quoted &&
612
32.3k
                (cursor->type == t_string ||
613
32.3k
                 cursor->type == t_check ||
614
32.2k
                 cursor->map != 0)) {
615
55
                json_debug_trace(1, "json: %s",
616
55
                                 "Didn't see quoted value when expecting"
617
55
                                 " string.\n");
618
55
                return JSON_ERR_NONQSTRING;
619
55
            }
620
39.5k
            if (cursor->map != 0) {
621
887
                for (mp = cursor->map; mp->name != NULL; mp++) {
622
821
                    if (strcmp(mp->name, valbuf) == 0) {
623
374
                        goto foundit;
624
374
                    }
625
821
                }
626
66
                json_debug_trace(1,
627
66
                                 "json: Invalid enumerated value string %s.\n",
628
66
                                 valbuf);
629
66
                return JSON_ERR_BADENUM;
630
374
foundit:
631
374
                (void)snprintf(valbuf, sizeof(valbuf), "%d", mp->value);
632
374
            }
633
39.4k
            if (cursor->type == t_check) {
634
760
                lptr = cursor->dflt.check;
635
38.7k
            } else {
636
38.7k
                lptr = json_target_address(cursor, parent, offset);
637
38.7k
            }
638
39.4k
            if (NULL != lptr) {
639
21.9k
                switch (cursor->type) {
640
228
                case t_byte: {
641
228
                    int tmp = atoi(valbuf);
642
228
                    lptr[0] = (char)tmp;
643
228
                }
644
228
                break;
645
820
                case t_ubyte: {
646
820
                    int tmp = atoi(valbuf);
647
820
                    lptr[0] = (unsigned char)tmp;
648
820
                }
649
820
                break;
650
1.69k
                case t_integer: {
651
1.69k
                    int tmp = atoi(valbuf);
652
1.69k
                    memcpy(lptr, &tmp, sizeof(int));
653
1.69k
                }
654
1.69k
                break;
655
1.05k
                case t_uinteger: {
656
1.05k
                    unsigned int tmp = (unsigned int)atol(valbuf);
657
1.05k
                    memcpy(lptr, &tmp, sizeof(unsigned int));
658
1.05k
                }
659
1.05k
                break;
660
659
                case t_longint: {
661
659
                    long tmp = atol(valbuf);
662
659
                    memcpy(lptr, &tmp, sizeof(long));
663
659
                }
664
659
                break;
665
440
                case t_ulongint: {
666
440
                    unsigned long tmp = (unsigned long)atoll(valbuf);
667
440
                    memcpy(lptr, &tmp, sizeof(unsigned long));
668
440
                }
669
440
                break;
670
1.97k
                case t_short: {
671
1.97k
                    short tmp = atoi(valbuf);
672
1.97k
                    memcpy(lptr, &tmp, sizeof(short));
673
1.97k
                }
674
1.97k
                break;
675
0
                case t_ushort: {
676
0
                    unsigned short tmp = (unsigned int)atoi(valbuf);
677
0
                    memcpy(lptr, &tmp, sizeof(unsigned short));
678
0
                }
679
0
                break;
680
2.86k
                case t_time: {
681
2.86k
                    timespec_t ts_tmp = {0, 0};
682
683
2.86k
                    if (value_quoted) {
684
1.88k
                        ts_tmp = iso8601_to_timespec(valbuf);
685
1.88k
                    } else if (NULL == strchr(valbuf, '.')) {
686
                        // integer
687
446
                        ts_tmp.tv_sec = (time_t)atoll(valbuf);
688
533
                    } else {
689
                        // real
690
533
                        double sec_tmp = safe_atof(valbuf);
691
533
                        if (0 != isfinite(sec_tmp)) {
692
339
                            DTOTS(&ts_tmp, sec_tmp);
693
339
                        }      // else, leave at default
694
533
                    }
695
2.86k
                    memcpy(lptr, &ts_tmp, sizeof(timespec_t));
696
2.86k
                }
697
2.86k
                break;
698
388
                case t_timespec: {
699
388
                    double sec_tmp = safe_atof(valbuf);
700
388
                    timespec_t ts_tmp;
701
388
                    if (0 != isfinite(sec_tmp)) {
702
194
                        DTOTS(&ts_tmp, sec_tmp);
703
194
                        memcpy(lptr, &ts_tmp, sizeof(timespec_t));
704
194
                    }     // else leave at .dflt
705
388
                }
706
388
                break;
707
5.09k
                case t_real: {
708
5.09k
                    double tmp = safe_atof(valbuf);
709
5.09k
                    if (0 != isfinite(tmp)) {
710
3.90k
                        memcpy(lptr, &tmp, sizeof(double));
711
3.90k
                    }     // else leave at .dflt
712
5.09k
                }
713
5.09k
                break;
714
824
                case t_string:
715
824
                    if (NULL != parent &&
716
194
                        parent->element_type != t_structobject &&
717
0
                        offset > 0) {
718
0
                        return JSON_ERR_NOPARSTR;
719
0
                    }
720
824
                    (void)strlcpy(lptr, valbuf, cursor->len);
721
824
                    break;
722
2.19k
                case t_boolean: {
723
2.19k
                    bool tmp = (strcmp(valbuf, "true") == 0);
724
2.19k
                    memcpy(lptr, &tmp, sizeof(bool));
725
2.19k
                }
726
2.19k
                break;
727
561
                case t_character:
728
561
                    if (strnlen(valbuf, 2) > 1) {
729
                        // don't update end here, leave at value start
730
6
                        return JSON_ERR_STRLONG;
731
555
                    } else {
732
555
                        lptr[0] = valbuf[0];
733
555
                    }
734
555
                    break;
735
2.40k
                case t_ignore:  // silences a compiler warning
736
2.40k
                    FALLTHROUGH
737
2.40k
                case t_object:  // silences a compiler warning
738
2.40k
                    FALLTHROUGH
739
2.40k
                case t_structobject:
740
2.40k
                    FALLTHROUGH
741
2.40k
                case t_array:
742
2.40k
                    break;
743
760
                case t_check:
744
760
                    if (strcmp(cursor->dflt.check, valbuf) != 0) {
745
180
                        json_debug_trace(1, "json: Required attribute value %s"
746
180
                                         " not present.\n",
747
180
                                         cursor->dflt.check);
748
                        // don't update end here, leave at start of attribute
749
180
                        return JSON_ERR_CHECKFAIL;
750
180
                    }
751
580
                    break;
752
21.9k
                }
753
21.9k
            }
754
39.2k
            FALLTHROUGH
755
40.4k
        case post_element:
756
40.4k
            if (ISSPACE(*cp)) {
757
568
                continue;
758
568
            }
759
39.8k
            if (*cp == ',') {
760
33.3k
                state = await_attr;
761
33.3k
            } else if (*cp == '}') {
762
5.87k
                ++cp;
763
5.87k
                goto good_parse;
764
5.87k
            } else {
765
682
                json_debug_trace(1, "json: %s",
766
682
                                 "Garbage while expecting comma or }\n");
767
682
                if (NULL != end) {
768
10
                    *end = cp;
769
10
                }
770
682
                return JSON_ERR_BADTRAIL;
771
682
            }
772
33.3k
            break;
773
591k
        }
774
591k
    }
775
3.23k
    if (state == init) {
776
57
        json_debug_trace(1, "json: %s", "Input was empty or white-space only\n");
777
57
        return JSON_ERR_EMPTY;
778
57
    }
779
780
9.04k
good_parse:
781
    // in case there's another object following, consume trailing WS
782
9.45k
    while (ISSPACE(*cp)) {
783
410
        ++cp;
784
410
    }
785
9.04k
    if (NULL != end) {
786
5.51k
        *end = cp;
787
5.51k
    }
788
9.04k
    json_debug_trace(1, "%s", "json: JSON parse ends.\n");
789
9.04k
    return 0;
790
3.23k
}
791
792
int json_read_array(const char *cp, const struct json_array_t *arr,
793
                    const char **end)
794
995
{
795
995
    int substatus;
796
995
    unsigned offset, arrcount;
797
995
    char *tp;
798
799
995
    if (NULL != end) {
800
995
        *end = NULL;    // give it a well-defined value on parse failure
801
995
    }
802
803
995
    json_debug_trace(1, "json: %s", "Entered json_read_array()\n");
804
805
995
    while (ISSPACE(*cp)) {
806
0
        cp++;
807
0
    }
808
995
    if (*cp != '[') {
809
0
        json_debug_trace(1, "json: %s", "Didn't find expected array start\n");
810
0
        return JSON_ERR_ARRAYSTART;
811
0
    }
812
995
    cp++;
813
814
995
    tp = arr->arr.strings.store;
815
995
    arrcount = 0;
816
817
    // Check for empty array
818
1.38k
    while (ISSPACE(*cp)) {
819
391
        cp++;
820
391
    }
821
995
    if (*cp == ']') {
822
273
        goto breakout;
823
273
    }
824
825
9.30k
    for (offset = 0; offset < arr->maxlen; offset++) {
826
9.30k
        char *ep = NULL;
827
828
9.30k
        json_debug_trace(1, "json: Looking at %s\n", cp);
829
9.30k
        switch (arr->element_type) {
830
3.66k
        case t_string:
831
3.66k
            if (ISSPACE(*cp)) {
832
467
                cp++;
833
467
            }
834
3.66k
            if (*cp != '"') {
835
22
                return JSON_ERR_BADSTRING;
836
3.63k
            } else {
837
3.63k
                ++cp;
838
3.63k
            }
839
3.63k
            arr->arr.strings.ptrs[offset] = tp;
840
14.6k
            for (; tp - arr->arr.strings.store < arr->arr.strings.storelen;
841
14.6k
                 tp++) {
842
14.6k
                if (*cp == '"') {
843
3.63k
                    ++cp;
844
3.63k
                    *tp++ = '\0';
845
3.63k
                    goto stringend;
846
11.0k
                } else if (*cp == '\0') {
847
1
                    json_debug_trace(1, "json: %s",
848
1
                                     "Bad string syntax in string list.\n");
849
1
                    return JSON_ERR_BADSTRING;
850
11.0k
                } else {
851
11.0k
                    *tp = *cp++;
852
11.0k
                }
853
14.6k
            }
854
3
            json_debug_trace(1, "json: %s",
855
3
                             "Bad string syntax in string list.\n");
856
3
            return JSON_ERR_BADSTRING;
857
3.63k
stringend:
858
3.63k
            break;
859
0
        case t_object:
860
0
            FALLTHROUGH
861
5.64k
        case t_structobject:
862
5.64k
            substatus =
863
5.64k
                json_internal_read_object(cp, arr->arr.objects.subtype, arr,
864
5.64k
                                          offset, &cp);
865
5.64k
            if (substatus != 0) {
866
129
                if (NULL != end) {
867
129
                    *end = cp;
868
129
                }
869
129
                return substatus;
870
129
            }
871
5.51k
            break;
872
5.51k
        case t_integer:
873
0
            arr->arr.integers.store[offset] = (int)strtol(cp, &ep, 0);
874
0
            if (ep == cp) {
875
0
                return JSON_ERR_BADNUM;
876
0
            }
877
0
            cp = ep;
878
0
            break;
879
0
        case t_uinteger:
880
0
            arr->arr.uintegers.store[offset] = (unsigned int)strtoul(cp,
881
0
                                                                     &ep, 0);
882
0
            if (ep == cp) {
883
0
                return JSON_ERR_BADNUM;
884
0
            }
885
0
            cp = ep;
886
0
            break;
887
0
        case t_longint:
888
0
            arr->arr.longint.store[offset] = strtol(cp, &ep, 0);
889
0
            if (ep == cp) {
890
0
                return JSON_ERR_BADNUM;
891
0
            }
892
0
            cp = ep;
893
0
            break;
894
0
        case t_ulongint:
895
0
            arr->arr.ulongint.store[offset] = strtoul(cp, &ep, 0);
896
0
            if (ep == cp) {
897
0
                return JSON_ERR_BADNUM;
898
0
            }
899
0
            cp = ep;
900
0
            break;
901
0
        case t_byte:
902
0
            arr->arr.bytes.store[offset] = (char)strtol(cp, &ep, 0);
903
0
            if (ep == cp) {
904
0
                return JSON_ERR_BADNUM;
905
0
            }
906
0
            cp = ep;
907
0
            break;
908
0
        case t_ubyte:
909
0
            arr->arr.ubytes.store[offset] = (unsigned char)strtoul(cp,
910
0
                                                                   &ep, 0);
911
0
            if (ep == cp) {
912
0
                return JSON_ERR_BADNUM;
913
0
            }
914
0
            cp = ep;
915
0
            break;
916
0
        case t_short:
917
0
            arr->arr.shorts.store[offset] = (short)strtol(cp, &ep, 0);
918
0
            if (ep == cp) {
919
0
                return JSON_ERR_BADNUM;
920
0
            }
921
0
            cp = ep;
922
0
            break;
923
0
        case t_ushort:
924
0
            arr->arr.ushorts.store[offset] = (unsigned short)strtoul(cp,
925
0
                                                                     &ep, 0);
926
0
            if (ep == cp) {
927
0
                return JSON_ERR_BADNUM;
928
0
            }
929
0
            cp = ep;
930
0
            break;
931
0
        case t_time: {
932
0
            timespec_t ts_tmp;
933
0
            if (*cp != '"') {
934
0
                return JSON_ERR_BADSTRING;
935
0
            } else {
936
0
                ++cp;
937
0
            }
938
0
            ts_tmp = iso8601_to_timespec(cp);
939
0
            arr->arr.timespecs.store[offset] = ts_tmp;
940
0
            while (*cp &&
941
0
                   *cp != '"') {
942
0
                cp++;
943
0
            }
944
0
            if (*cp != '"') {
945
0
                return JSON_ERR_BADSTRING;
946
0
            }
947
0
            ++cp;
948
0
        }
949
0
        break;
950
0
        case t_timespec:
951
            // TODO not sure how to implement this
952
0
            return JSON_ERR_BADNUM;
953
0
            break;
954
0
        case t_real:
955
0
            arr->arr.reals.store[offset] = strtod(cp, &ep);
956
0
            if (ep == cp) {
957
0
                return JSON_ERR_BADNUM;
958
0
            }
959
0
            cp = ep;
960
0
            break;
961
0
        case t_boolean:
962
0
            if (str_starts_with(cp, "true")) {
963
0
                arr->arr.booleans.store[offset] = true;
964
0
                cp += 4;
965
0
            } else if (str_starts_with(cp, "false")) {
966
0
                arr->arr.booleans.store[offset] = false;
967
0
                cp += 5;
968
0
            }
969
0
            break;
970
0
        case t_character:
971
0
            FALLTHROUGH
972
0
        case t_array:
973
0
            FALLTHROUGH
974
0
        case t_check:
975
0
            FALLTHROUGH
976
0
        case t_ignore:
977
0
            json_debug_trace(1, "json: %s", "Invalid array subtype.\n");
978
0
            return JSON_ERR_SUBTYPE;
979
9.30k
        }
980
9.15k
        arrcount++;
981
9.15k
        if (ISSPACE(*cp)) {
982
414
            cp++;
983
414
        }
984
9.15k
        if (*cp == ']') {
985
378
            json_debug_trace(1, "json: %s", "End of array found.\n");
986
378
            goto breakout;
987
378
        }
988
8.77k
        if (*cp == ',') {
989
8.58k
            cp++;
990
8.58k
        } else {
991
188
            json_debug_trace(1, "json: %s", "Bad trailing syntax on array.\n");
992
188
            return JSON_ERR_BADSUBTRAIL;
993
188
        }
994
8.77k
    }
995
1
    json_debug_trace(1, "json: %s", "Too many elements in array.\n");
996
1
    if (NULL != end) {
997
1
        *end = cp;
998
1
    }
999
1
    return JSON_ERR_SUBTOOLONG;
1000
651
breakout:
1001
651
    if (NULL != arr->count) {
1002
651
        *(arr->count) = arrcount;
1003
651
    }
1004
651
    if (NULL != end) {
1005
651
        *end = cp;
1006
651
    }
1007
651
    json_debug_trace(1, "json: leaving json_read_array() with %d elements\n",
1008
651
                     arrcount);
1009
651
    return 0;
1010
722
}
1011
1012
int json_read_object(const char *cp, const struct json_attr_t *attrs,
1013
                     const char **end)
1014
5.47k
{
1015
5.47k
    int st;
1016
1017
5.47k
    json_debug_trace(1, "json: json_read_object() sees '%s'\n", cp);
1018
5.47k
    st = json_internal_read_object(cp, attrs, NULL, 0, end);
1019
5.47k
    return st;
1020
5.47k
}
1021
1022
const char *json_error_string(int err)
1023
0
{
1024
0
    const char *errors[] = {
1025
0
        "unknown error while parsing JSON",
1026
0
        "non-whitespace when expecting object start",
1027
0
        "non-whitespace when expecting attribute start",
1028
0
        "unknown attribute name",
1029
0
        "attribute name too long",
1030
0
        "saw [ when not expecting array",
1031
0
        "array element specified, but no [",
1032
0
        "string value too long",
1033
0
        "token value too long",
1034
0
        "garbage while expecting comma or } or ]",
1035
0
        "didn't find expected array start",
1036
0
        "error while parsing object array",
1037
0
        "too many array elements",
1038
0
        "garbage while expecting array comma",
1039
0
        "unsupported array element type",
1040
0
        "error while string parsing",
1041
0
        "check attribute not matched",
1042
0
        "can't support strings in parallel arrays",
1043
0
        "invalid enumerated value",
1044
0
        "saw quoted value when expecting nonstring",
1045
0
        "didn't see quoted value when expecting string",
1046
0
        "other data conversion error",
1047
0
        "unexpected null value or attribute pointer",
1048
0
        "object element specified, but no {",
1049
0
        "input was empty or white-space only",
1050
0
    };
1051
1052
0
    if (err <= 0 ||
1053
0
        err >= (int)(sizeof(errors) / sizeof(errors[0]))) {
1054
0
        return errors[0];
1055
0
    }
1056
0
    return errors[err];
1057
0
}
1058
1059
/* quote a JSON string so it can be used as a simple JSON string.
1060
 * Used to output the JSON as a literal JSON string
1061
 * escape control chars, escape double quote.
1062
 * stop at NUL, in_len or bad unicode char
1063
 */
1064
char *json_quote(const char *in_buffer, char *out_buffer, size_t in_len,
1065
                 size_t out_len)
1066
0
{
1067
0
    const char *escape_match = "'\"/\\\b\f\n\r\t";
1068
0
    const char *escaped_bit = "'\"/\\bfnrt";
1069
0
    unsigned out_index = 0;
1070
0
    const char *escape_ptr;
1071
0
    unsigned in_index = 0;
1072
0
    unsigned to_copy = 0;
1073
1074
0
    out_buffer[0] = '\0';
1075
1076
    // check in string, stop at NUL, done in_len, or out_buffer full
1077
0
    for (in_index = 0; in_buffer[in_index] != '\0'; in_index++) {
1078
1079
0
        if (in_index >= in_len) {
1080
            // got all from input buffer
1081
0
            break;
1082
0
        }
1083
1084
0
        if (out_index > (out_len - 8) ) {
1085
            /* output out_buffer full.  Not enough space for a 4-byte UTF + NUL,
1086
             * or \uxxxx + NUL.  Safer to check once, at the top,
1087
             * than a lot of specific size checks later in the loop.
1088
             */
1089
0
            break;
1090
0
        }
1091
1092
0
        if (in_buffer[in_index] & 0x80) {
1093
            // highbit set. assume unicode
1094
0
            to_copy = 0;    // always reset before use, to shut up coverity
1095
1096
            // check in_len so we don't overrun in_buffer
1097
0
            if ((in_len > (in_index + 1)) &&
1098
0
                (0xC0 == (0xE0 & (uint8_t)in_buffer[in_index])) &&
1099
0
                (0x80 == (0xC0 & (uint8_t)in_buffer[in_index + 1]))) {
1100
                // utf-8 ish 16bit rune - deg, plusm, mplus etc.
1101
0
                to_copy = 2;
1102
0
            } else if ((in_len > (in_index + 2)) &&
1103
0
                       (0xE0 == (0xF0 & (uint8_t)in_buffer[in_index])) &&
1104
0
                       (0x80 == (0xC0 & (uint8_t)in_buffer[in_index + 1])) &&
1105
0
                       (0x80 == (0xC0 & (uint8_t)in_buffer[in_index + 2]))) {
1106
                // utf-8 ish 24 bit rune - (double) prime etc.
1107
0
                to_copy = 3;
1108
0
            } else if ((in_len > (in_index + 3)) &&
1109
0
                       (0xF0 == (0xF8 & (uint8_t)in_buffer[in_index])) &&
1110
0
                       (0x80 == (0xC0 & (uint8_t)in_buffer[in_index + 1])) &&
1111
0
                       (0x80 == (0xC0 & (uint8_t)in_buffer[in_index + 2])) &&
1112
0
                       (0x80 == (0xC0 & (uint8_t)in_buffer[in_index + 3]))) {
1113
                // utf-8 ish 32 bit rune - musical symbol g clef etc.
1114
0
                to_copy = 4;
1115
0
            } else {
1116
                // WTF??  Short UTF?  Bad UTF?
1117
0
                str_appendf(out_buffer, out_len,
1118
0
                            "\\u%04x", in_buffer[in_index] & 0x0ff);
1119
0
                out_index += 6;
1120
0
                continue;
1121
0
            }
1122
1123
0
            memcpy(&out_buffer[out_index], &in_buffer[in_index], to_copy);
1124
0
            out_index += to_copy;
1125
            // minus one as the for loop does in_index++
1126
0
            in_index += to_copy - 1;
1127
0
            out_buffer[out_index] = '\0';
1128
0
            continue;
1129
0
        }
1130
1131
        /* Try to find current byte from in buffer in string escape
1132
         * match if it is there append '\', the corresponding byte
1133
         * from escaped bit, and a null byte to end of out buffer.
1134
         */
1135
0
        escape_ptr = strchr(escape_match, in_buffer[in_index]);
1136
0
        if (escape_ptr >= escape_match) {
1137
0
            out_buffer[out_index++] = '\\';
1138
0
            out_buffer[out_index++] = escaped_bit[escape_ptr - escape_match];
1139
0
            out_buffer[out_index] = 0;
1140
0
            continue;
1141
0
        }
1142
1143
        // Escape 0-31 and 127 if not previously handled (0-x01f,x7f)
1144
0
        if ('\x1f' >= in_buffer[in_index] || '\x7f' == in_buffer[in_index]) {
1145
0
            str_appendf(out_buffer, out_len, "\\u%04x",
1146
0
                        in_buffer[in_index] & 0x0ff);
1147
0
            out_index += 6;
1148
0
            continue;
1149
0
        }
1150
        // pass through everything not escaped.
1151
0
        out_buffer[out_index++] = in_buffer[in_index];
1152
0
        out_buffer[out_index] = '\0';
1153
0
    }
1154
0
    return out_buffer;
1155
0
}
1156
1157
// vim: set expandtab shiftwidth=4