From b8b8ca87b36c24a07b9bd450d85c67f7b493a572 Mon Sep 17 00:00:00 2001 From: Maxim Prokhorov Date: Wed, 9 Sep 2020 17:55:26 +0300 Subject: [PATCH] util: do not ignore zeroes in hex input Provide safe fallback *only* when char is out-of-range As it is, numeric 0 was equal to else { ... }, so 00 was never parsed. Previously, it was assumed that we never try to parse leading / trailing zeroes, but in turn we also ignored zeroes in the middle of the number... --- code/espurna/utils.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/code/espurna/utils.cpp b/code/espurna/utils.cpp index a7ace737..28257052 100644 --- a/code/espurna/utils.cpp +++ b/code/espurna/utils.cpp @@ -818,6 +818,9 @@ size_t hexDecode(const char* in, size_t in_size, uint8_t* out, size_t out_size) return 0; } + // We can only return small values + constexpr uint8_t InvalidByte { 255u }; + auto char2byte = [](char ch) -> uint8_t { if ((ch >= '0') && (ch <= '9')) { return (ch - '0'); @@ -826,7 +829,7 @@ size_t hexDecode(const char* in, size_t in_size, uint8_t* out, size_t out_size) } else if ((ch >= 'A') && (ch <= 'F')) { return 10 + (ch - 'A'); } else { - return 0; + return InvalidByte; } }; @@ -836,7 +839,7 @@ size_t hexDecode(const char* in, size_t in_size, uint8_t* out, size_t out_size) while (index < in_size) { const uint8_t lhs = char2byte(in[index]) << 4; const uint8_t rhs = char2byte(in[index + 1]); - if (lhs || rhs) { + if ((InvalidByte != lhs) && (InvalidByte != rhs)) { out[out_index++] = lhs | rhs; index += 2; continue;