Skip to content

Commit 9228315

Browse files
committed
parser cbor BUGFIX negative integers below INT64_MIN
1 parent f7e0cc1 commit 9228315

2 files changed

Lines changed: 33 additions & 3 deletions

File tree

‎src/parser_cbor.c‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -381,15 +381,24 @@ lydcbor_item_to_string(const cbor_item_t *item, char **str_val, size_t *str_len)
381381
break;
382382
}
383383
case CBOR_TYPE_NEGINT: {
384-
int64_t val = -1 - (int64_t)cbor_get_int(item);
385-
int len = snprintf(NULL, 0, "%" PRId64, val);
384+
/* the value is -1 - val, which does not fit into int64_t for val > INT64_MAX */
385+
uint64_t val = cbor_get_int(item);
386+
int len;
387+
388+
if (val == UINT64_MAX) {
389+
*str_val = strdup("-18446744073709551616");
390+
LY_CHECK_ERR_RET(!*str_val, LOGMEM(NULL), LY_EMEM);
391+
*str_len = strlen(*str_val);
392+
break;
393+
}
386394

395+
len = snprintf(NULL, 0, "-%" PRIu64, val + 1);
387396
if (len < 0) {
388397
return LY_ESYS;
389398
}
390399
*str_val = malloc(len + 1);
391400
LY_CHECK_ERR_RET(!*str_val, LOGMEM(NULL), LY_EMEM);
392-
sprintf(*str_val, "%" PRId64, val);
401+
sprintf(*str_val, "-%" PRIu64, val + 1);
393402
*str_len = len;
394403
break;
395404
}

‎tests/utests/data/test_cbor.c‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -395,6 +395,26 @@ test_attributes(void **state)
395395
lyd_free_all(tree);
396396
}
397397

398+
static void
399+
test_negint(void **state)
400+
{
401+
struct lyd_node *tree;
402+
403+
/* {"cbor-test:lf-uintg8": -18446744073709551611} */
404+
const char data1[] = "\xa1\x73" "cbor-test:lf-uintg8" "\x3b\xff\xff\xff\xff\xff\xff\xff\xfa";
405+
406+
/* {"cbor-test:lf-uintg8": -18446744073709551616} */
407+
const char data2[] = "\xa1\x73" "cbor-test:lf-uintg8" "\x3b\xff\xff\xff\xff\xff\xff\xff\xff";
408+
409+
assert_int_equal(LY_EVALID, lyd_parse_data_mem_len(UTEST_LYCTX, data1, sizeof data1 - 1, LYD_CBOR, 0,
410+
LYD_VALIDATE_PRESENT, &tree));
411+
CHECK_LOG_CTX("Value \"-18446744073709551611\" is out of type uint8 min/max bounds.", "/cbor-test:lf-uintg8", 1);
412+
413+
assert_int_equal(LY_EVALID, lyd_parse_data_mem_len(UTEST_LYCTX, data2, sizeof data2 - 1, LYD_CBOR, 0,
414+
LYD_VALIDATE_PRESENT, &tree));
415+
CHECK_LOG_CTX("Invalid type uint8 value \"-18446744073709551616\".", "/cbor-test:lf-uintg8", 1);
416+
}
417+
398418
int
399419
main(void)
400420
{
@@ -405,6 +425,7 @@ main(void)
405425
UTEST(test_schema_mount, setup),
406426
UTEST(test_opaque, setup),
407427
UTEST(test_attributes, setup),
428+
UTEST(test_negint, setup),
408429
};
409430

410431
return cmocka_run_group_tests(tests, NULL, NULL);

0 commit comments

Comments
 (0)