Skip to content

Commit 2664f2f

Browse files
affan-archmichalvasko
authored andcommitted
parser cbor BUGFIX negative integers below INT64_MIN
1 parent 9ddf2d7 commit 2664f2f

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
@@ -408,6 +408,26 @@ test_invalid_input(void **state)
408408
CHECK_LOG_CTX("Value \"1000\" is out of type int8 min/max bounds.", "/cbor-test:lf-intg8", 0);
409409
}
410410

411+
static void
412+
test_negint(void **state)
413+
{
414+
struct lyd_node *tree;
415+
416+
/* {"cbor-test:lf-uintg8": -18446744073709551611} */
417+
const char data1[] = "\xa1\x73" "cbor-test:lf-uintg8" "\x3b\xff\xff\xff\xff\xff\xff\xff\xfa";
418+
419+
/* {"cbor-test:lf-uintg8": -18446744073709551616} */
420+
const char data2[] = "\xa1\x73" "cbor-test:lf-uintg8" "\x3b\xff\xff\xff\xff\xff\xff\xff\xff";
421+
422+
assert_int_equal(LY_EVALID, lyd_parse_data_mem_len(UTEST_LYCTX, data1, sizeof data1 - 1, LYD_CBOR, 0,
423+
LYD_VALIDATE_PRESENT, &tree));
424+
CHECK_LOG_CTX("Value \"-18446744073709551611\" is out of type uint8 min/max bounds.", "/cbor-test:lf-uintg8", 1);
425+
426+
assert_int_equal(LY_EVALID, lyd_parse_data_mem_len(UTEST_LYCTX, data2, sizeof data2 - 1, LYD_CBOR, 0,
427+
LYD_VALIDATE_PRESENT, &tree));
428+
CHECK_LOG_CTX("Invalid type uint8 value \"-18446744073709551616\".", "/cbor-test:lf-uintg8", 1);
429+
}
430+
411431
int
412432
main(void)
413433
{
@@ -419,6 +439,7 @@ main(void)
419439
UTEST(test_opaque, setup),
420440
UTEST(test_attributes, setup),
421441
UTEST(test_invalid_input, setup),
442+
UTEST(test_negint, setup),
422443
};
423444

424445
return cmocka_run_group_tests(tests, NULL, NULL);

0 commit comments

Comments
 (0)