LCOV - code coverage report
Current view: top level - codec - Avp.cpp (source / functions) Coverage Total Hit
Test: final-coverage.info Lines: 92.0 % 685 630
Test Date: 2026-11-15 19:07:59 Functions: 98.0 % 51 50

            Line data    Source code
       1              : /*
       2              :  ________________________________________________________________________
       3              : |                                                                        |
       4              : |       _ _                      _                         _             |
       5              : |      | (_)                    | |                       | |            |
       6              : |    __| |_  __ _ _ __ ___   ___| |_ ___ _ __ ___ ___   __| | ___  ___   |
       7              : |   / _` | |/ _` | '_ ` _ \ / _ \ __/ _ \ '__/ __/ _ \ / _` |/ _ \/ __|  |
       8              : |  | (_| | | (_| | | | | | |  __/ ||  __/ | | (_| (_) | (_| |  __/ (__   |
       9              : |   \__,_|_|\__,_|_| |_| |_|\___|\__\___|_|  \___\___/ \__,_|\___|\___|  |
      10              : |                                                                        |
      11              : |________________________________________________________________________|
      12              : 
      13              : C++ CODEC FOR DIAMETER PROTOCOL (RFC 6733)
      14              : Version 0.0.z
      15              : https://github.com/testillano/diametercodec
      16              : 
      17              : Licensed under the MIT License <http://opensource.org/licenses/MIT>.
      18              : SPDX-License-Identifier: MIT
      19              : Copyright (c) 2021 Eduardo Ramos
      20              : 
      21              : Permission is hereby  granted, free of charge, to any  person obtaining a copy
      22              : of this software and associated  documentation files (the "Software"), to deal
      23              : in the Software  without restriction, including without  limitation the rights
      24              : to  use, copy,  modify, merge,  publish, distribute,  sublicense, and/or  sell
      25              : copies  of  the Software,  and  to  permit persons  to  whom  the Software  is
      26              : furnished to do so, subject to the following conditions:
      27              : 
      28              : The above copyright notice and this permission notice shall be included in all
      29              : copies or substantial portions of the Software.
      30              : 
      31              : THE SOFTWARE  IS PROVIDED "AS  IS", WITHOUT WARRANTY  OF ANY KIND,  EXPRESS OR
      32              : IMPLIED,  INCLUDING BUT  NOT  LIMITED TO  THE  WARRANTIES OF  MERCHANTABILITY,
      33              : FITNESS FOR  A PARTICULAR PURPOSE AND  NONINFRINGEMENT. IN NO EVENT  SHALL THE
      34              : AUTHORS  OR COPYRIGHT  HOLDERS  BE  LIABLE FOR  ANY  CLAIM,  DAMAGES OR  OTHER
      35              : LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      36              : OUT OF OR IN CONNECTION WITH THE SOFTWARE  OR THE USE OR OTHER DEALINGS IN THE
      37              : SOFTWARE.
      38              : */
      39              : 
      40              : // Standard
      41              : #include <arpa/inet.h>
      42              : 
      43              : #include <cctype>
      44              : #include <cstdio>
      45              : #include <cstring>
      46              : #include <iomanip>
      47              : #include <limits>
      48              : #include <sstream>
      49              : 
      50              : // Project
      51              : #include <algorithm>
      52              : #include <ert/diametercodec/codec/Avp.hpp>
      53              : #include <ert/diametercodec/stack/Avp.hpp>
      54              : #include <ert/diametercodec/stack/AvpRule.hpp>
      55              : #include <ert/diametercodec/stack/Dictionary.hpp>
      56              : #include <ert/diametercodec/stack/Format.hpp>
      57              : #include <ert/tracing/Logger.hpp>
      58              : 
      59              : namespace ert {
      60              : namespace diametercodec {
      61              : namespace codec {
      62              : 
      63              : // ============================================================================
      64              : // Helpers: network byte order encode/decode
      65              : // ============================================================================
      66              : 
      67              : namespace {
      68              : 
      69          129 : inline uint32_t decode4(const uint8_t* b) {
      70          129 :     return (uint32_t(b[0]) << 24) | (uint32_t(b[1]) << 16) | (uint32_t(b[2]) << 8) | uint32_t(b[3]);
      71              : }
      72              : 
      73          101 : inline uint32_t decode3(const uint8_t* b) { return (uint32_t(b[0]) << 16) | (uint32_t(b[1]) << 8) | uint32_t(b[2]); }
      74              : 
      75           10 : inline uint16_t decode2(const uint8_t* b) { return (uint16_t(b[0]) << 8) | uint16_t(b[1]); }
      76              : 
      77           10 : inline int32_t decodeSigned4(const uint8_t* b) {
      78           10 :     uint32_t u = decode4(b);
      79              :     int32_t v;
      80           10 :     std::memcpy(&v, &u, 4);
      81           10 :     return v;
      82              : }
      83              : 
      84            3 : inline int64_t decodeSigned8(const uint8_t* b) {
      85            3 :     uint64_t u = (uint64_t(b[0]) << 56) | (uint64_t(b[1]) << 48) | (uint64_t(b[2]) << 40) | (uint64_t(b[3]) << 32) |
      86            3 :                  (uint64_t(b[4]) << 24) | (uint64_t(b[5]) << 16) | (uint64_t(b[6]) << 8) | uint64_t(b[7]);
      87              :     int64_t v;
      88            3 :     std::memcpy(&v, &u, 8);
      89            3 :     return v;
      90              : }
      91              : 
      92            7 : inline uint64_t decodeUnsigned8(const uint8_t* b) {
      93            7 :     return (uint64_t(b[0]) << 56) | (uint64_t(b[1]) << 48) | (uint64_t(b[2]) << 40) | (uint64_t(b[3]) << 32) |
      94            7 :            (uint64_t(b[4]) << 24) | (uint64_t(b[5]) << 16) | (uint64_t(b[6]) << 8) | uint64_t(b[7]);
      95              : }
      96              : 
      97          122 : inline void encode4(core::Buffer& out, uint32_t v) {
      98          122 :     out.push_back(static_cast<uint8_t>(v >> 24));
      99          122 :     out.push_back(static_cast<uint8_t>(v >> 16));
     100          122 :     out.push_back(static_cast<uint8_t>(v >> 8));
     101          122 :     out.push_back(static_cast<uint8_t>(v));
     102          122 : }
     103              : 
     104              : inline void encode3(core::Buffer& out, uint32_t v) {
     105              :     out.push_back(static_cast<uint8_t>(v >> 16));
     106              :     out.push_back(static_cast<uint8_t>(v >> 8));
     107              :     out.push_back(static_cast<uint8_t>(v));
     108              : }
     109              : 
     110           10 : inline void encode2(core::Buffer& out, uint16_t v) {
     111           10 :     out.push_back(static_cast<uint8_t>(v >> 8));
     112           10 :     out.push_back(static_cast<uint8_t>(v));
     113           10 : }
     114              : 
     115            7 : inline void encode8(core::Buffer& out, uint64_t v) {
     116           63 :     for (int i = 56; i >= 0; i -= 8) out.push_back(static_cast<uint8_t>(v >> i));
     117            7 : }
     118              : 
     119           97 : inline void encodePadding(core::Buffer& out, size_t dataLen) {
     120           97 :     size_t pad = (4 - (dataLen % 4)) % 4;
     121          199 :     for (size_t i = 0; i < pad; ++i) out.push_back(0);
     122           97 : }
     123              : 
     124              : // Resolve the format type for an AVP using the dictionary.
     125              : // Returns the direct type (e.g., UTF8String, Address, Time) rather than
     126              : // recursing to the parent basic type. This allows the codec to handle
     127              : // derived types with specialized encode/decode/json logic.
     128          323 : stack::Format::Type::_v resolveFormatType(const core::AvpId& id, const stack::Dictionary& dict) {
     129          323 :     const stack::Avp* sa = dict.getAvp(id);
     130          323 :     if (!sa) return stack::Format::Type::Unknown;
     131          318 :     const stack::Format* fmt = sa->getFormat();
     132          318 :     if (!fmt || fmt->isReserved()) return stack::Format::Type::Unknown;
     133          318 :     return stack::Format::Type::asEnum(fmt->getName());
     134              : }
     135              : 
     136              : // Hex string helpers
     137           41 : std::string toHex(const uint8_t* data, size_t len) {
     138           41 :     std::ostringstream oss;
     139           41 :     oss << std::hex << std::setfill('0');
     140          234 :     for (size_t i = 0; i < len; ++i) oss << std::setw(2) << static_cast<unsigned>(data[i]);
     141           82 :     return oss.str();
     142           41 : }
     143              : 
     144           62 : core::Buffer fromHex(const std::string& hex) {
     145           62 :     if (hex.size() % 2 != 0) throw std::runtime_error("Invalid hex string (odd number of digits): '" + hex + "'");
     146           61 :     core::Buffer buf;
     147           61 :     buf.reserve(hex.size() / 2);
     148          338 :     for (size_t i = 0; i < hex.size(); i += 2) {
     149          555 :         if (!std::isxdigit(static_cast<unsigned char>(hex[i])) ||
     150          277 :             !std::isxdigit(static_cast<unsigned char>(hex[i + 1])))
     151            1 :             throw std::runtime_error("Invalid hex string (non-hex digit): '" + hex + "'");
     152          277 :         uint8_t byte = static_cast<uint8_t>(std::stoul(hex.substr(i, 2), nullptr, 16));
     153          277 :         buf.push_back(byte);
     154              :     }
     155           60 :     return buf;
     156            1 : }
     157              : 
     158              : // Address helpers
     159           10 : std::string decodeAddress(const uint8_t* buf, size_t len) {
     160           10 :     if (len < 2) throw std::runtime_error("Address AVP too short");
     161           10 :     uint16_t family = decode2(buf);
     162              :     char str[INET6_ADDRSTRLEN];
     163              : 
     164           10 :     if (family == 1 && len == 6) {  // IPv4
     165           21 :         if (inet_ntop(AF_INET, buf + 2, str, sizeof(str))) return str;
     166            0 :         throw std::runtime_error("Failed to decode IPv4 address");
     167              :     }
     168            3 :     if (family == 2 && len == 18) {  // IPv6
     169            9 :         if (inet_ntop(AF_INET6, buf + 2, str, sizeof(str))) return str;
     170            0 :         throw std::runtime_error("Failed to decode IPv6 address");
     171              :     }
     172              :     // Unknown family: return as hex
     173            0 :     return toHex(buf, len);
     174              : }
     175              : 
     176           10 : void encodeAddress(core::Buffer& out, const std::string& addr) {
     177              :     uint8_t buf4[4], buf6[16];
     178           10 :     if (inet_pton(AF_INET, addr.c_str(), buf4) == 1) {
     179            8 :         encode2(out, 1);  // IPv4 family
     180            8 :         out.insert(out.end(), buf4, buf4 + 4);
     181            2 :     } else if (inet_pton(AF_INET6, addr.c_str(), buf6) == 1) {
     182            2 :         encode2(out, 2);  // IPv6 family
     183            2 :         out.insert(out.end(), buf6, buf6 + 16);
     184              :     } else {
     185            0 :         throw std::runtime_error("Invalid IP address: " + addr);
     186              :     }
     187           10 : }
     188              : 
     189              : }  // anonymous namespace
     190              : 
     191              : namespace {
     192              : // Readable form of an OctetString value (defined below, with the encoders).
     193              : nlohmann::json readableOctets(const std::string& bytes, const std::string& form);
     194              : }  // anonymous namespace
     195              : 
     196              : // Forward declaration (defined below, before Avp::toJson)
     197              : static std::string avpValueTrace(const core::AvpId& id, const Avp::Data& data, const stack::Dictionary& dict);
     198              : 
     199              : // ============================================================================
     200              : // Avp::decode
     201              : // ============================================================================
     202          103 : size_t Avp::decode(const uint8_t* buf, size_t len, const stack::Dictionary& dict) {
     203          103 :     if (len < static_cast<size_t>(core::AvpHeaderLenWithoutVendor))
     204            2 :         throw std::runtime_error("Not enough bytes for AVP header");
     205              : 
     206              :     // AVP Code (4 bytes)
     207          101 :     uint32_t code = decode4(buf);
     208              :     // Flags (1 byte)
     209          101 :     flags_ = buf[4];
     210              :     // AVP Length (3 bytes) — includes header, excludes padding
     211          101 :     uint32_t avpLen = decode3(buf + 5);
     212              : 
     213              :     // Vendor-ID
     214          101 :     uint32_t vendorId = 0;
     215          101 :     int headerLen = core::AvpHeaderLenWithoutVendor;
     216          101 :     if (vendorBit()) {
     217            3 :         headerLen = core::AvpHeaderLenWithVendor;
     218            3 :         if (len < static_cast<size_t>(headerLen))
     219            1 :             throw std::runtime_error("Not enough bytes for AVP header with vendor");
     220            2 :         vendorId = decode4(buf + 8);
     221              :     }
     222              : 
     223          100 :     id_ = core::AvpId(static_cast<core::S32>(code), static_cast<core::S32>(vendorId));
     224              : 
     225          100 :     if (avpLen < static_cast<uint32_t>(headerLen)) throw std::runtime_error("AVP length smaller than header");
     226              : 
     227           99 :     uint32_t dataLen = avpLen - headerLen;
     228              : 
     229           99 :     if (len < avpLen) throw std::runtime_error("Not enough bytes for AVP data");
     230              : 
     231              :     // Decode data part
     232           98 :     decodeData(buf + headerLen, dataLen, dict);
     233              : 
     234              :     // Return total consumed bytes (padded to 4-byte boundary)
     235           92 :     return 4 * REQUIRED_WORDS(avpLen);
     236              : }
     237              : 
     238              : // ============================================================================
     239              : // Avp::decodeData
     240              : // ============================================================================
     241           98 : void Avp::decodeData(const uint8_t* buf, size_t dataLen, const stack::Dictionary& dict) {
     242           98 :     auto basicType = resolveFormatType(id_, dict);
     243              : 
     244           98 :     switch (basicType) {
     245           11 :         case stack::Format::Type::Integer32:
     246              :         case stack::Format::Type::Enumerated:
     247           11 :             if (dataLen != 4) throw std::runtime_error("Integer32/Enumerated must be 4 bytes");
     248           10 :             data_ = decodeSigned4(buf);
     249           10 :             break;
     250              : 
     251            3 :         case stack::Format::Type::Integer64:
     252            3 :             if (dataLen != 8) throw std::runtime_error("Integer64 must be 8 bytes");
     253            3 :             data_ = decodeSigned8(buf);
     254            3 :             break;
     255              : 
     256           10 :         case stack::Format::Type::Unsigned32:
     257           10 :             if (dataLen != 4) throw std::runtime_error("Unsigned32 must be 4 bytes");
     258            9 :             data_ = decode4(buf);
     259            9 :             break;
     260              : 
     261            4 :         case stack::Format::Type::Unsigned64:
     262            4 :             if (dataLen != 8) throw std::runtime_error("Unsigned64 must be 8 bytes");
     263            3 :             data_ = decodeUnsigned8(buf);
     264            3 :             break;
     265              : 
     266            5 :         case stack::Format::Type::Float32: {
     267            5 :             if (dataLen != 4) throw std::runtime_error("Float32 must be 4 bytes");
     268            4 :             uint32_t u = decode4(buf);
     269              :             float f;
     270            4 :             std::memcpy(&f, &u, 4);
     271            4 :             data_ = f;
     272            4 :             break;
     273              :         }
     274              : 
     275            5 :         case stack::Format::Type::Float64: {
     276            5 :             if (dataLen != 8) throw std::runtime_error("Float64 must be 8 bytes");
     277            4 :             uint64_t u = decodeUnsigned8(buf);
     278              :             double d;
     279            4 :             std::memcpy(&d, &u, 8);
     280            4 :             data_ = d;
     281            4 :             break;
     282              :         }
     283              : 
     284           10 :         case stack::Format::Type::Address:
     285           10 :             data_ = decodeAddress(buf, dataLen);
     286           10 :             break;
     287              : 
     288            4 :         case stack::Format::Type::Time:
     289            4 :             if (dataLen != 4) throw std::runtime_error("Time must be 4 bytes");
     290            3 :             data_ = decode4(buf);  // stored as uint32_t (NTP timestamp)
     291            3 :             break;
     292              : 
     293            3 :         case stack::Format::Type::Grouped: {
     294            3 :             std::vector<Avp> children;
     295            3 :             size_t pos = 0;
     296            9 :             while (pos < dataLen) {
     297            6 :                 Avp child;
     298            6 :                 size_t consumed = child.decode(buf + pos, dataLen - pos, dict);
     299            6 :                 children.push_back(std::move(child));
     300            6 :                 pos += consumed;
     301            6 :             }
     302            3 :             data_ = std::move(children);
     303            3 :             break;
     304            3 :         }
     305              : 
     306              :         // OctetString, UTF8String, DiameterIdentity, DiameterURI, IPFilterRule, QoSFilterRule, Unknown
     307           43 :         case stack::Format::Type::OctetString:
     308              :         case stack::Format::Type::UTF8String:
     309              :         case stack::Format::Type::DiameterIdentity:
     310              :         case stack::Format::Type::DiameterURI:
     311              :         case stack::Format::Type::IPFilterRule:
     312              :         case stack::Format::Type::QoSFilterRule:
     313              :         default:
     314           43 :             data_ = std::string(reinterpret_cast<const char*>(buf), dataLen);
     315           43 :             break;
     316              :     }
     317              : 
     318           92 :     LOGDEBUG(ert::tracing::Logger::debug(
     319              :         ert::tracing::Logger::asString("Diameter decode AVP '%s' (%s): 0x%s -> %s", getName(dict).c_str(),
     320              :                                        stack::Format::Type::asText(basicType), toHex(buf, dataLen).c_str(),
     321              :                                        avpValueTrace(id_, data_, dict).c_str()),
     322              :         ERT_FILE_LOCATION));
     323           92 : }
     324              : 
     325              : // ============================================================================
     326              : // Avp::encode
     327              : // ============================================================================
     328           97 : void Avp::encode(core::Buffer& out, const stack::Dictionary& dict) const {
     329              :     // AVP Code
     330           97 :     encode4(out, static_cast<uint32_t>(id_.first));
     331              : 
     332              :     // Flags
     333           97 :     out.push_back(flags_);
     334              : 
     335              :     // Length placeholder (3 bytes) — filled after encoding data
     336           97 :     size_t lenPos = out.size();
     337           97 :     out.push_back(0);
     338           97 :     out.push_back(0);
     339           97 :     out.push_back(0);
     340              : 
     341              :     // Vendor-ID
     342           97 :     if (vendorBit()) {
     343            2 :         encode4(out, static_cast<uint32_t>(id_.second));
     344              :     }
     345              : 
     346              :     // Data part
     347           97 :     size_t dataStart = out.size();
     348           97 :     encodeData(out, dict);
     349           97 :     size_t dataEnd = out.size();
     350              : 
     351              :     // Compute and write AVP length (header + data, no padding)
     352           97 :     int headerLen = vendorBit() ? core::AvpHeaderLenWithVendor : core::AvpHeaderLenWithoutVendor;
     353           97 :     uint32_t avpLen = headerLen + static_cast<uint32_t>(dataEnd - dataStart);
     354           97 :     out[lenPos] = static_cast<uint8_t>(avpLen >> 16);
     355           97 :     out[lenPos + 1] = static_cast<uint8_t>(avpLen >> 8);
     356           97 :     out[lenPos + 2] = static_cast<uint8_t>(avpLen);
     357              : 
     358              :     // Padding to 4-byte boundary
     359           97 :     encodePadding(out, avpLen);
     360           97 : }
     361              : 
     362              : // ============================================================================
     363              : // Avp::encodeData
     364              : // ============================================================================
     365           97 : size_t Avp::encodeData(core::Buffer& out, const stack::Dictionary& dict) const {
     366           97 :     size_t start = out.size();
     367           97 :     if (raw_) {
     368              :         // Negative testing: verbatim bytes, whatever the dictionary format.
     369            6 :         const auto& s = std::get<std::string>(data_);
     370            6 :         out.insert(out.end(), reinterpret_cast<const uint8_t*>(s.data()),
     371            6 :                    reinterpret_cast<const uint8_t*>(s.data()) + s.size());
     372            6 :         LOGDEBUG(ert::tracing::Logger::debug(
     373              :             ert::tracing::Logger::asString("Diameter encode AVP '%s' (raw): 0x%s", getName(dict).c_str(),
     374              :                                            toHex(out.data() + start, out.size() - start).c_str()),
     375              :             ERT_FILE_LOCATION));
     376            6 :         return out.size() - start;
     377              :     }
     378           91 :     auto basicType = resolveFormatType(id_, dict);
     379              : 
     380           91 :     switch (basicType) {
     381            8 :         case stack::Format::Type::Integer32:
     382              :         case stack::Format::Type::Enumerated: {
     383            8 :             int32_t v = std::get<int32_t>(data_);
     384              :             uint32_t u;
     385            8 :             std::memcpy(&u, &v, 4);
     386            8 :             encode4(out, u);
     387            8 :             break;
     388              :         }
     389              : 
     390            2 :         case stack::Format::Type::Integer64: {
     391            2 :             int64_t v = std::get<int64_t>(data_);
     392              :             uint64_t u;
     393            2 :             std::memcpy(&u, &v, 8);
     394            2 :             encode8(out, u);
     395            2 :             break;
     396              :         }
     397              : 
     398           10 :         case stack::Format::Type::Unsigned32:
     399           10 :             encode4(out, std::get<uint32_t>(data_));
     400           10 :             break;
     401              : 
     402            2 :         case stack::Format::Type::Unsigned64:
     403            2 :             encode8(out, std::get<uint64_t>(data_));
     404            2 :             break;
     405              : 
     406            3 :         case stack::Format::Type::Float32: {
     407            3 :             float f = std::get<float>(data_);
     408              :             uint32_t u;
     409            3 :             std::memcpy(&u, &f, 4);
     410            3 :             encode4(out, u);
     411            3 :             break;
     412              :         }
     413              : 
     414            3 :         case stack::Format::Type::Float64: {
     415            3 :             double d = std::get<double>(data_);
     416              :             uint64_t u;
     417            3 :             std::memcpy(&u, &d, 8);
     418            3 :             encode8(out, u);
     419            3 :             break;
     420              :         }
     421              : 
     422           10 :         case stack::Format::Type::Address:
     423           10 :             encodeAddress(out, std::get<std::string>(data_));
     424           10 :             break;
     425              : 
     426            2 :         case stack::Format::Type::Time:
     427            2 :             encode4(out, std::get<uint32_t>(data_));
     428            2 :             break;
     429              : 
     430            2 :         case stack::Format::Type::Grouped: {
     431            2 :             const auto& children = std::get<std::vector<Avp>>(data_);
     432            6 :             for (const auto& child : children) child.encode(out, dict);
     433            2 :             break;
     434              :         }
     435              : 
     436              :         // OctetString and all string-based types, including Unknown
     437           49 :         case stack::Format::Type::OctetString:
     438              :         case stack::Format::Type::UTF8String:
     439              :         case stack::Format::Type::DiameterIdentity:
     440              :         case stack::Format::Type::DiameterURI:
     441              :         case stack::Format::Type::IPFilterRule:
     442              :         case stack::Format::Type::QoSFilterRule:
     443              :         default: {
     444           49 :             const auto& s = std::get<std::string>(data_);
     445           49 :             out.insert(out.end(), reinterpret_cast<const uint8_t*>(s.data()),
     446           49 :                        reinterpret_cast<const uint8_t*>(s.data()) + s.size());
     447           49 :             break;
     448              :         }
     449              :     }
     450              : 
     451           91 :     LOGDEBUG(ert::tracing::Logger::debug(
     452              :         ert::tracing::Logger::asString("Diameter encode AVP '%s' (%s): %s -> 0x%s", getName(dict).c_str(),
     453              :                                        stack::Format::Type::asText(basicType), avpValueTrace(id_, data_, dict).c_str(),
     454              :                                        toHex(out.data() + start, out.size() - start).c_str()),
     455              :         ERT_FILE_LOCATION));
     456              : 
     457           91 :     return out.size() - start;
     458              : }
     459              : 
     460              : // ============================================================================
     461              : // Avp::getLength
     462              : // ============================================================================
     463           10 : size_t Avp::getLength(const stack::Dictionary& dict) const {
     464           10 :     int headerLen = vendorBit() ? core::AvpHeaderLenWithVendor : core::AvpHeaderLenWithoutVendor;
     465           10 :     if (raw_) return headerLen + std::get<std::string>(data_).size();
     466            9 :     auto basicType = resolveFormatType(id_, dict);
     467              : 
     468            9 :     switch (basicType) {
     469            2 :         case stack::Format::Type::Integer32:
     470              :         case stack::Format::Type::Enumerated:
     471              :         case stack::Format::Type::Unsigned32:
     472              :         case stack::Format::Type::Float32:
     473              :         case stack::Format::Type::Time:
     474            2 :             return headerLen + 4;
     475              : 
     476            0 :         case stack::Format::Type::Integer64:
     477              :         case stack::Format::Type::Unsigned64:
     478              :         case stack::Format::Type::Float64:
     479            0 :             return headerLen + 8;
     480              : 
     481            3 :         case stack::Format::Type::Address: {
     482            3 :             const auto& addr = std::get<std::string>(data_);
     483              :             uint8_t buf4[4];
     484            3 :             if (inet_pton(AF_INET, addr.c_str(), buf4) == 1) return headerLen + 6;  // 2 family + 4 addr
     485            1 :             return headerLen + 18;                                                  // 2 family + 16 addr
     486              :         }
     487              : 
     488            0 :         case stack::Format::Type::Grouped: {
     489            0 :             size_t total = headerLen;
     490            0 :             const auto& children = std::get<std::vector<Avp>>(data_);
     491            0 :             for (const auto& child : children) total += 4 * REQUIRED_WORDS(child.getLength(dict));
     492            0 :             return total;
     493              :         }
     494              : 
     495              :         // OctetString and all string-based types
     496            4 :         case stack::Format::Type::OctetString:
     497              :         case stack::Format::Type::UTF8String:
     498              :         case stack::Format::Type::DiameterIdentity:
     499              :         case stack::Format::Type::DiameterURI:
     500              :         case stack::Format::Type::IPFilterRule:
     501              :         case stack::Format::Type::QoSFilterRule:
     502              :         default:
     503            4 :             return headerLen + std::get<std::string>(data_).size();
     504              :     }
     505              : }
     506              : 
     507              : // ============================================================================
     508              : // Avp::getName
     509              : // ============================================================================
     510           63 : std::string Avp::getName(const stack::Dictionary& dict) const {
     511           63 :     const stack::Avp* sa = raw_ ? nullptr : dict.getAvp(id_);
     512           63 :     if (sa) return sa->getName();
     513              :     // Unknown AVP: use code-vendor format
     514            8 :     std::ostringstream oss;
     515            8 :     oss << "avp-" << id_.first;
     516            8 :     if (id_.second != 0) oss << "-" << id_.second;
     517            8 :     return oss.str();
     518            8 : }
     519              : 
     520              : // ============================================================================
     521              : // avpValueTrace: human-readable rendering of an AVP value for debug traces.
     522              : // For Enumerated it appends the dictionary alias/literal when available.
     523              : // ============================================================================
     524            0 : static std::string avpValueTrace(const core::AvpId& id, const Avp::Data& data, const stack::Dictionary& dict) {
     525            0 :     auto t = resolveFormatType(id, dict);
     526            0 :     switch (t) {
     527            0 :         case stack::Format::Type::Integer32:
     528            0 :             return std::to_string(std::get<int32_t>(data));
     529            0 :         case stack::Format::Type::Enumerated: {
     530            0 :             int32_t v = std::get<int32_t>(data);
     531            0 :             std::string s = std::to_string(v);
     532            0 :             const stack::Avp* sa = dict.getAvp(id);
     533            0 :             const char* alias = sa ? sa->getAlias(std::to_string(v)) : nullptr;
     534            0 :             if (alias) {
     535            0 :                 s += " (";
     536            0 :                 s += alias;
     537            0 :                 s += ")";
     538              :             }
     539            0 :             return s;
     540            0 :         }
     541            0 :         case stack::Format::Type::Integer64:
     542            0 :             return std::to_string(std::get<int64_t>(data));
     543            0 :         case stack::Format::Type::Unsigned32:
     544            0 :             return std::to_string(std::get<uint32_t>(data));
     545            0 :         case stack::Format::Type::Unsigned64:
     546            0 :             return std::to_string(std::get<uint64_t>(data));
     547            0 :         case stack::Format::Type::Float32:
     548            0 :             return std::to_string(std::get<float>(data));
     549            0 :         case stack::Format::Type::Float64:
     550            0 :             return std::to_string(std::get<double>(data));
     551            0 :         case stack::Format::Type::Address:
     552            0 :             return std::get<std::string>(data);
     553            0 :         case stack::Format::Type::Time:
     554            0 :             return std::to_string(std::get<uint32_t>(data) - core::NtpEpochOffset) + " (epoch)";
     555            0 :         case stack::Format::Type::Grouped:
     556            0 :             return "<grouped>";
     557            0 :         case stack::Format::Type::UTF8String:
     558              :         case stack::Format::Type::DiameterIdentity:
     559              :         case stack::Format::Type::DiameterURI:
     560              :         case stack::Format::Type::IPFilterRule:
     561              :         case stack::Format::Type::QoSFilterRule:
     562            0 :             return "\"" + std::get<std::string>(data) + "\"";
     563            0 :         default: {  // OctetString / Unknown
     564            0 :             const auto& s = std::get<std::string>(data);
     565            0 :             return "0x" + toHex(reinterpret_cast<const uint8_t*>(s.data()), s.size());
     566              :         }
     567              :     }
     568              : }
     569              : 
     570              : // ============================================================================
     571              : // Avp::toJson
     572              : // ============================================================================
     573           46 : nlohmann::json Avp::toJson(const stack::Dictionary& dict) const { return dataToJson(dict, nullptr); }
     574              : 
     575           73 : nlohmann::json Avp::toJson(const stack::Dictionary& dict, const DecodeOptions& options) const {
     576           73 :     return dataToJson(dict, options.empty() ? nullptr : &options);
     577              : }
     578              : 
     579          126 : nlohmann::json Avp::dataToJson(const stack::Dictionary& dict, const DecodeOptions* options) const {
     580          126 :     if (raw_) {
     581            1 :         const auto& s = std::get<std::string>(data_);
     582            1 :         return toHex(reinterpret_cast<const uint8_t*>(s.data()), s.size());
     583              :     }
     584          125 :     auto basicType = resolveFormatType(id_, dict);
     585              : 
     586          125 :     switch (basicType) {
     587            6 :         case stack::Format::Type::Integer32:
     588              :         case stack::Format::Type::Enumerated:
     589            6 :             return std::get<int32_t>(data_);
     590              : 
     591            2 :         case stack::Format::Type::Integer64:
     592            2 :             return std::get<int64_t>(data_);
     593              : 
     594            8 :         case stack::Format::Type::Unsigned32:
     595            8 :             return std::get<uint32_t>(data_);
     596              : 
     597            2 :         case stack::Format::Type::Unsigned64:
     598            2 :             return std::get<uint64_t>(data_);
     599              : 
     600            2 :         case stack::Format::Type::Float32:
     601            2 :             return std::get<float>(data_);
     602              : 
     603            2 :         case stack::Format::Type::Float64:
     604            2 :             return std::get<double>(data_);
     605              : 
     606           10 :         case stack::Format::Type::Address:
     607           10 :             return std::get<std::string>(data_);
     608              : 
     609            2 :         case stack::Format::Type::Time:
     610              :             // Convert NTP to UNIX epoch
     611            2 :             return std::get<uint32_t>(data_) - core::NtpEpochOffset;
     612              : 
     613            3 :         case stack::Format::Type::Grouped: {
     614            3 :             nlohmann::json obj = nlohmann::json::object();
     615            3 :             const auto& children = std::get<std::vector<Avp>>(data_);
     616           10 :             for (const auto& child : children) {
     617            7 :                 std::string name = child.getName(dict);
     618            7 :                 nlohmann::json val = child.dataToJson(dict, options);
     619            7 :                 if (obj.contains(name)) {
     620              :                     // Convert to array for repeated AVPs
     621            1 :                     if (!obj[name].is_array()) {
     622            1 :                         nlohmann::json arr = nlohmann::json::array();
     623            1 :                         arr.push_back(std::move(obj[name]));
     624            1 :                         obj[name] = std::move(arr);
     625            1 :                     }
     626            1 :                     obj[name].push_back(std::move(val));
     627              :                 } else {
     628            6 :                     obj[name] = std::move(val);
     629              :                 }
     630            7 :             }
     631            3 :             return obj;
     632            3 :         }
     633              : 
     634           31 :         case stack::Format::Type::UTF8String:
     635              :         case stack::Format::Type::DiameterIdentity:
     636              :         case stack::Format::Type::DiameterURI:
     637              :         case stack::Format::Type::IPFilterRule:
     638              :         case stack::Format::Type::QoSFilterRule:
     639           31 :             return std::get<std::string>(data_);
     640              : 
     641              :         // OctetString or unknown: hex representation, or the configured readable form
     642           57 :         default: {
     643           57 :             const auto& s = std::get<std::string>(data_);
     644           57 :             if (options) {
     645           40 :                 auto it = options->forms.find(id_);
     646           40 :                 if (it != options->forms.end()) return readableOctets(s, it->second);
     647              :             }
     648           18 :             return toHex(reinterpret_cast<const uint8_t*>(s.data()), s.size());
     649              :         }
     650              :     }
     651              : }
     652              : 
     653              : // ============================================================================
     654              : // Avp::fromJson
     655              : // ============================================================================
     656              : namespace {
     657              : 
     658              : // Parse a decimal component of a raw AVP key (strict: digits only, fits 32 bits).
     659           19 : bool parseRawKeyNumber(const std::string& s, uint32_t& out) {
     660           19 :     if (s.empty() || s.size() > 10) return false;
     661           16 :     uint64_t v = 0;
     662           61 :     for (char c : s) {
     663           46 :         if (!std::isdigit(static_cast<unsigned char>(c))) return false;
     664           45 :         v = v * 10 + static_cast<uint64_t>(c - '0');
     665              :     }
     666           15 :     if (v > 0xFFFFFFFFull) return false;
     667           15 :     out = static_cast<uint32_t>(v);
     668           15 :     return true;
     669              : }
     670              : 
     671              : // 'avp-<code>' or 'avp-<code>-<vendor>' -> (code, vendor). False if not that form.
     672           18 : bool parseRawAvpKey(const std::string& key, uint32_t& code, uint32_t& vendor) {
     673           20 :     static const std::string prefix = "avp-";
     674           18 :     if (key.compare(0, prefix.size(), prefix) != 0) return false;
     675           17 :     std::string rest = key.substr(prefix.size());
     676           17 :     vendor = 0;
     677           17 :     auto dash = rest.find('-');
     678           17 :     if (dash == std::string::npos) return parseRawKeyNumber(rest, code);
     679            2 :     return parseRawKeyNumber(rest.substr(0, dash), code) && parseRawKeyNumber(rest.substr(dash + 1), vendor);
     680           17 : }
     681              : 
     682              : // ----------------------------------------------------------------------------
     683              : // Readable forms of an OctetString (JSON -> bytes). The canonical JSON form of
     684              : // an OctetString is the hex of its bytes (the decoder always gives it back so);
     685              : // an object with ONE of these keys is another way to write the same bytes, so a
     686              : // provision can show "dnn_mbb.com" instead of "646e6e5f6d62622e636f6d". The key
     687              : // names how the bytes are built, never the AVP: which form suits an AVP is its
     688              : // 3GPP definition (the writer's knowledge, as the hex is today).
     689              : //   generic:    hex, text (UTF-8 bytes), ipv4 (4 bytes), ipv6 (16 bytes)
     690              : //   structured: ipv6Prefix (RFC 3162: reserved, length, prefix),
     691              : //               msTimeZone (TS 29.061 3GPP-MS-TimeZone: TS 24.008 zone + DST),
     692              : //               uli (TS 29.061 3GPP-User-Location-Info: TAI, ECGI, TAI+ECGI)
     693              : // ----------------------------------------------------------------------------
     694              : 
     695           17 : [[noreturn]] void formError(const std::string& avpName, const std::string& what) {
     696           17 :     throw std::runtime_error("OctetString AVP '" + avpName + "': " + what);
     697              : }
     698              : 
     699           42 : std::string formString(const nlohmann::json& v, const std::string& avpName, const std::string& key) {
     700           44 :     if (!v.is_string()) formError(avpName, "'" + key + "' must be a string");
     701           41 :     return v.get<std::string>();
     702              : }
     703              : 
     704              : // Decimal JSON integer, or a "0x..." hex string; checked against max.
     705           16 : uint32_t formNumber(const nlohmann::json& obj, const char* key, uint32_t max, const std::string& avpName) {
     706           16 :     auto it = obj.find(key);
     707           20 :     if (it == obj.end()) formError(avpName, std::string("uli needs '") + key + "'");
     708           15 :     uint64_t v = 0;
     709           15 :     if (it->is_number_unsigned() || (it->is_number_integer() && it->get<int64_t>() >= 0)) {
     710           13 :         v = it->get<uint64_t>();
     711            2 :     } else if (it->is_string()) {
     712            2 :         const std::string s = it->get<std::string>();
     713            3 :         if (s.size() < 3 || s.size() > 18 || s.compare(0, 2, "0x") != 0 ||
     714            1 :             s.find_first_not_of("0123456789abcdefABCDEF", 2) != std::string::npos)
     715            5 :             formError(avpName, std::string("uli '") + key + "' must be a decimal number or a \"0x...\" hex string");
     716            1 :         v = std::stoull(s.substr(2), nullptr, 16);
     717            2 :     } else {
     718            0 :         formError(avpName, std::string("uli '") + key + "' must be a decimal number or a \"0x...\" hex string");
     719              :     }
     720           22 :     if (v > max) formError(avpName, std::string("uli '") + key + "' out of range");
     721           12 :     return static_cast<uint32_t>(v);
     722              : }
     723              : 
     724              : // MCC (3 digits) + MNC (2 or 3 digits) -> 3 bytes BCD (TS 24.008 10.5.1.3).
     725           15 : std::string plmnBcd(const nlohmann::json& obj, const std::string& avpName) {
     726           29 :     auto digits = [&](const char* key, size_t minLen, size_t maxLen) {
     727           29 :         auto it = obj.find(key);
     728           29 :         if (it == obj.end() || !it->is_string())
     729            0 :             formError(avpName, std::string("uli needs '") + key + "' (string of digits)");
     730           29 :         std::string d = it->get<std::string>();
     731           29 :         if (d.size() < minLen || d.size() > maxLen || d.find_first_not_of("0123456789") != std::string::npos)
     732           11 :             formError(avpName, std::string("uli '") + key + "' must have " + std::to_string(minLen) +
     733            9 :                                    (minLen == maxLen ? "" : " or " + std::to_string(maxLen)) + " digits");
     734           56 :         return d;
     735            1 :     };
     736           15 :     const std::string mcc = digits("mcc", 3, 3), mnc = digits("mnc", 2, 3);
     737           72 :     auto n = [](char c) { return static_cast<uint8_t>(c - '0'); };
     738           14 :     const uint8_t mnc3 = mnc.size() == 3 ? n(mnc[2]) : 0x0F;
     739           14 :     std::string out;
     740           14 :     out.push_back(static_cast<char>(n(mcc[1]) << 4 | n(mcc[0])));
     741           14 :     out.push_back(static_cast<char>(mnc3 << 4 | n(mcc[2])));
     742           14 :     out.push_back(static_cast<char>(n(mnc[1]) << 4 | n(mnc[0])));
     743           28 :     return out;
     744           14 : }
     745              : 
     746           12 : void pushBigEndian(std::string& out, uint32_t v, int bytes) {
     747           46 :     for (int i = bytes - 1; i >= 0; --i) out.push_back(static_cast<char>((v >> (8 * i)) & 0xFF));
     748           12 : }
     749              : 
     750           15 : std::string uliBytes(const nlohmann::json& uli, const std::string& avpName) {
     751           15 :     if (!uli.is_object()) formError(avpName, "'uli' must be an object");
     752           15 :     auto itType = uli.find("type");
     753           15 :     if (itType == uli.end() || !itType->is_string()) formError(avpName, "uli needs 'type': tai|ecgi|tai-ecgi");
     754           15 :     const std::string type = itType->get<std::string>();
     755           15 :     const std::string plmn = plmnBcd(uli, avpName);
     756           14 :     std::string out;
     757           14 :     if (type == "tai") {
     758            6 :         out.push_back(static_cast<char>(128));
     759            6 :         out += plmn;
     760            6 :         pushBigEndian(out, formNumber(uli, "tac", 0xFFFF, avpName), 2);
     761            8 :     } else if (type == "ecgi") {
     762            4 :         out.push_back(static_cast<char>(129));
     763            4 :         out += plmn;
     764            4 :         pushBigEndian(out, formNumber(uli, "eci", 0x0FFFFFFF, avpName), 4);
     765            4 :     } else if (type == "tai-ecgi") {
     766            3 :         out.push_back(static_cast<char>(130));
     767            3 :         out += plmn;
     768            3 :         pushBigEndian(out, formNumber(uli, "tac", 0xFFFF, avpName), 2);
     769            3 :         out += plmn;
     770            3 :         pushBigEndian(out, formNumber(uli, "eci", 0x0FFFFFFF, avpName), 4);
     771              :     } else {
     772            2 :         formError(avpName, "uli 'type' must be tai|ecgi|tai-ecgi");
     773              :     }
     774           18 :     return out;
     775           25 : }
     776              : 
     777              : // "+-hh:mm[+dst]" -> 2 bytes: TS 24.008 10.5.3.8 time zone (quarters of an
     778              : // hour, BCD with swapped semi-octets, sign bit 0x08) + 10.5.3.12 DST (0..2).
     779           10 : std::string msTimeZoneBytes(const std::string& tz, const std::string& avpName) {
     780            2 :     auto bad = [&]() { formError(avpName, "msTimeZone must be +-hh:mm[+dst] (e.g. -08:00+1): " + tz); };
     781           10 :     if (tz.size() != 6 && tz.size() != 8) bad();
     782            9 :     if ((tz[0] != '+' && tz[0] != '-') || tz[3] != ':') bad();
     783           45 :     for (size_t i : {1u, 2u, 4u, 5u})
     784           36 :         if (!std::isdigit(static_cast<unsigned char>(tz[i]))) bad();
     785            9 :     int dst = 0;
     786            9 :     if (tz.size() == 8) {
     787            6 :         if (tz[6] != '+' || tz[7] < '0' || tz[7] > '2') bad();
     788            5 :         dst = tz[7] - '0';
     789              :     }
     790            8 :     const int minutes = ((tz[1] - '0') * 10 + (tz[2] - '0')) * 60 + (tz[4] - '0') * 10 + (tz[5] - '0');
     791            9 :     if (minutes % 15 != 0) formError(avpName, "msTimeZone goes in quarters of an hour: " + tz);
     792            7 :     const int q = minutes / 15;
     793            7 :     if (q > 79) formError(avpName, "msTimeZone out of range: " + tz);
     794            7 :     uint8_t zone = static_cast<uint8_t>((q % 10) << 4 | (q / 10));
     795            7 :     if (tz[0] == '-') zone |= 0x08;
     796            7 :     std::string out;
     797            7 :     out.push_back(static_cast<char>(zone));
     798            7 :     out.push_back(static_cast<char>(dst));
     799           14 :     return out;
     800            0 : }
     801              : 
     802              : // "addr/len" -> reserved (0) + prefix length + the first ceil(len/8) bytes of
     803              : // the address (bits beyond the length cleared), RFC 3162 Framed-IPv6-Prefix.
     804            9 : std::string ipv6PrefixBytes(const std::string& prefix, const std::string& avpName) {
     805            9 :     auto slash = prefix.find('/');
     806           10 :     if (slash == std::string::npos) formError(avpName, "ipv6Prefix must be <ipv6>/<length>: " + prefix);
     807            8 :     const std::string addr = prefix.substr(0, slash), lenText = prefix.substr(slash + 1);
     808            8 :     if (lenText.empty() || lenText.size() > 3 || lenText.find_first_not_of("0123456789") != std::string::npos)
     809            0 :         formError(avpName, "ipv6Prefix length must be 0..128: " + prefix);
     810            8 :     const int len = std::stoi(lenText);
     811            9 :     if (len > 128) formError(avpName, "ipv6Prefix length must be 0..128: " + prefix);
     812              :     uint8_t buf[16];
     813            7 :     if (inet_pton(AF_INET6, addr.c_str(), buf) != 1) formError(avpName, "ipv6Prefix address is not IPv6: " + prefix);
     814            7 :     std::string out;
     815            7 :     out.push_back(0);
     816            7 :     out.push_back(static_cast<char>(len));
     817            7 :     const int bytes = (len + 7) / 8;
     818           54 :     for (int i = 0; i < bytes; ++i) {
     819           47 :         uint8_t b = buf[i];
     820           47 :         const int bits = len - 8 * i;
     821           47 :         if (bits < 8) b &= static_cast<uint8_t>(0xFF << (8 - bits));
     822           47 :         out.push_back(static_cast<char>(b));
     823              :     }
     824           14 :     return out;
     825            9 : }
     826              : 
     827           60 : std::string octetsFromForm(const nlohmann::json& form, const std::string& avpName) {
     828           60 :     if (form.size() != 1)
     829            4 :         formError(avpName,
     830              :                   "a readable form is an object with exactly one key "
     831              :                   "(hex|text|ipv4|ipv6|ipv6Prefix|msTimeZone|uli)");
     832           58 :     const auto& [key, v] = *form.items().begin();
     833           58 :     if (key == "hex") {
     834            6 :         auto raw = fromHex(formString(v, avpName, key));
     835            6 :         return std::string(reinterpret_cast<const char*>(raw.data()), raw.size());
     836            6 :     }
     837           52 :     if (key == "text") return formString(v, avpName, key);
     838           45 :     if (key == "ipv4" || key == "ipv6") {
     839           10 :         const std::string addr = formString(v, avpName, key);
     840              :         uint8_t buf[16];
     841           10 :         const int family = key == "ipv4" ? AF_INET : AF_INET6;
     842           16 :         if (inet_pton(family, addr.c_str(), buf) != 1) formError(avpName, "'" + key + "' is not valid: " + addr);
     843            8 :         return std::string(reinterpret_cast<const char*>(buf), key == "ipv4" ? 4 : 16);
     844           10 :     }
     845           37 :     if (key == "ipv6Prefix") return ipv6PrefixBytes(formString(v, avpName, key), avpName);
     846           29 :     if (key == "msTimeZone") return msTimeZoneBytes(formString(v, avpName, key), avpName);
     847           16 :     if (key == "uli") return uliBytes(v, avpName);
     848            3 :     formError(avpName, "unknown readable form '" + key + "' (hex|text|ipv4|ipv6|ipv6Prefix|msTimeZone|uli)");
     849              : }
     850              : 
     851              : // ----------------------------------------------------------------------------
     852              : // Readable forms of an OctetString (bytes -> JSON): the inverse of the
     853              : // encoders above, for the AVPs configured in DecodeOptions. Each reader only
     854              : // proposes a value; readableOctets keeps it if encoding it back gives the same
     855              : // bytes (rejects what the encoders cannot express: spare bits, unsupported
     856              : // types, non canonical values) and otherwise falls back to {"hex": ...}.
     857              : // ----------------------------------------------------------------------------
     858              : 
     859              : // Strict UTF-8 (RFC 3629): no overlongs, no surrogates, <= U+10FFFF.
     860            7 : bool isUtf8(const std::string& s) {
     861            7 :     const auto* p = reinterpret_cast<const unsigned char*>(s.data());
     862            7 :     const size_t n = s.size();
     863            7 :     size_t i = 0;
     864           24 :     while (i < n) {
     865           20 :         const unsigned char c = p[i];
     866           20 :         if (c < 0x80) {
     867           16 :             ++i;
     868           16 :             continue;
     869              :         }
     870            4 :         size_t len = 0;
     871            4 :         uint32_t cp = 0, min = 0;
     872            4 :         if ((c & 0xE0) == 0xC0) {
     873            1 :             len = 2, cp = c & 0x1F, min = 0x80;
     874            3 :         } else if ((c & 0xF0) == 0xE0) {
     875            0 :             len = 3, cp = c & 0x0F, min = 0x800;
     876            3 :         } else if ((c & 0xF8) == 0xF0) {
     877            0 :             len = 4, cp = c & 0x07, min = 0x10000;
     878              :         } else {
     879            3 :             return false;
     880              :         }
     881            1 :         if (i + len > n) return false;
     882            2 :         for (size_t k = 1; k < len; ++k) {
     883            1 :             if ((p[i + k] & 0xC0) != 0x80) return false;
     884            1 :             cp = (cp << 6) | (p[i + k] & 0x3F);
     885              :         }
     886            1 :         if (cp < min || cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF)) return false;
     887            1 :         i += len;
     888              :     }
     889            4 :     return true;
     890              : }
     891              : 
     892            8 : std::string ipText(const uint8_t* buf, int family) {
     893              :     char text[INET6_ADDRSTRLEN];
     894           24 :     return inet_ntop(family, buf, text, sizeof(text)) ? std::string(text) : std::string();
     895              : }
     896              : 
     897            8 : uint32_t bigEndian(const uint8_t* p, int bytes) {
     898            8 :     uint32_t v = 0;
     899           32 :     for (int i = 0; i < bytes; ++i) v = (v << 8) | p[i];
     900            8 :     return v;
     901              : }
     902              : 
     903              : // 3 bytes BCD (TS 24.008 10.5.1.3) -> mcc/mnc into 'uli'. False on a non digit.
     904            7 : bool readPlmn(const uint8_t* p, nlohmann::json& uli) {
     905           32 :     auto digit = [](uint8_t d, std::string& out) {
     906           32 :         if (d > 9) return false;
     907           31 :         out.push_back(static_cast<char>('0' + d));
     908           31 :         return true;
     909              :     };
     910            7 :     std::string mcc, mnc;
     911            7 :     if (!digit(p[0] & 0x0F, mcc) || !digit(p[0] >> 4, mcc) || !digit(p[1] & 0x0F, mcc)) return false;
     912            6 :     if (!digit(p[2] & 0x0F, mnc) || !digit(p[2] >> 4, mnc)) return false;
     913            6 :     if ((p[1] >> 4) != 0x0F && !digit(p[1] >> 4, mnc)) return false;  // F: 2-digit MNC
     914            6 :     uli["mcc"] = mcc;
     915            6 :     uli["mnc"] = mnc;
     916            6 :     return true;
     917            7 : }
     918              : 
     919              : // Candidate readable value of 'bytes' for 'form'; null when it does not fit.
     920           39 : nlohmann::json readForm(const std::string& bytes, const std::string& form) {
     921           39 :     const auto* p = reinterpret_cast<const uint8_t*>(bytes.data());
     922           39 :     const size_t n = bytes.size();
     923           39 :     if (form == "text") {
     924            8 :         if (bytes.find('\0') != std::string::npos || !isUtf8(bytes)) return nullptr;
     925            4 :         return bytes;
     926              :     }
     927           31 :     if (form == "ipv4" || form == "ipv6") {
     928            7 :         if (n != (form == "ipv4" ? 4u : 16u)) return nullptr;
     929            4 :         std::string text = ipText(p, form == "ipv4" ? AF_INET : AF_INET6);
     930            4 :         return text.empty() ? nlohmann::json() : nlohmann::json(text);
     931            4 :     }
     932           24 :     if (form == "ipv6Prefix") {
     933            7 :         if (n < 2 || p[0] != 0 || p[1] > 128 || n != 2u + (p[1] + 7u) / 8u) return nullptr;
     934            4 :         uint8_t addr[16] = {0};
     935            4 :         std::memcpy(addr, p + 2, n - 2);
     936            4 :         std::string text = ipText(addr, AF_INET6);
     937            4 :         return text.empty() ? nlohmann::json() : nlohmann::json(text + "/" + std::to_string(p[1]));
     938            4 :     }
     939           17 :     if (form == "msTimeZone") {
     940            6 :         if (n != 2 || (p[0] >> 4) > 9 || p[1] > 2) return nullptr;
     941            3 :         const int minutes = ((p[0] & 0x07) * 10 + (p[0] >> 4)) * 15;
     942              :         char text[16];
     943            3 :         std::snprintf(text, sizeof(text), "%c%02d:%02d", (p[0] & 0x08) ? '-' : '+', minutes / 60, minutes % 60);
     944            3 :         std::string tz(text);
     945            3 :         if (p[1] != 0) tz += "+" + std::to_string(p[1]);
     946            3 :         return tz;
     947            3 :     }
     948           11 :     if (form == "uli") {
     949           11 :         nlohmann::json uli = nlohmann::json::object();
     950           11 :         if (n == 6 && p[0] == 128) {
     951            3 :             uli["type"] = "tai";
     952            3 :             if (!readPlmn(p + 1, uli)) return nullptr;
     953            2 :             uli["tac"] = bigEndian(p + 4, 2);
     954            8 :         } else if (n == 8 && p[0] == 129) {
     955            2 :             uli["type"] = "ecgi";
     956            2 :             if (!readPlmn(p + 1, uli)) return nullptr;
     957            2 :             uli["eci"] = bigEndian(p + 4, 4);
     958            6 :         } else if (n == 13 && p[0] == 130) {
     959            2 :             uli["type"] = "tai-ecgi";
     960            2 :             if (!readPlmn(p + 1, uli)) return nullptr;  // the ECGI PLMN must be the same one (round trip)
     961            2 :             uli["tac"] = bigEndian(p + 4, 2);
     962            2 :             uli["eci"] = bigEndian(p + 9, 4);
     963              :         } else {
     964            4 :             return nullptr;  // other types (CGI, SAI, RAI, 5GS...): not supported by the encoder
     965              :         }
     966            6 :         return uli;
     967           11 :     }
     968            0 :     return nullptr;
     969              : }
     970              : 
     971           39 : nlohmann::json readableOctets(const std::string& bytes, const std::string& form) {
     972           39 :     nlohmann::json value = readForm(bytes, form);
     973           39 :     if (!value.is_null()) {
     974           84 :         nlohmann::json candidate = {{form, value}};
     975              :         try {
     976           42 :             if (octetsFromForm(candidate, "") == bytes) return candidate;
     977            1 :         } catch (const std::exception&) {
     978              :             // the encoder cannot express it: fall back to hex
     979            1 :         }
     980           21 :     }
     981           22 :     LOGDEBUG(ert::tracing::Logger::debug(
     982              :         ert::tracing::Logger::asString("OctetString does not fit readable form '%s': decoded as hex", form.c_str()),
     983              :         ERT_FILE_LOCATION));
     984          132 :     return {{"hex", toHex(reinterpret_cast<const uint8_t*>(bytes.data()), bytes.size())}};
     985          233 : }
     986              : 
     987              : }  // anonymous namespace
     988              : 
     989              : // ============================================================================
     990              : // DecodeOptions
     991              : // ============================================================================
     992           10 : bool DecodeOptions::isForm(const std::string& form) {
     993           15 :     return form == "text" || form == "ipv4" || form == "ipv6" || form == "ipv6Prefix" || form == "msTimeZone" ||
     994           15 :            form == "uli";
     995              : }
     996              : 
     997              : // ============================================================================
     998              : // Avp::sortByRules
     999              : // ============================================================================
    1000           22 : void Avp::sortByRules(std::vector<Avp>& avps, const std::map<int, stack::AvpRule>& rules) {
    1001           22 :     if (rules.empty() || avps.size() < 2) return;
    1002          102 :     auto rank = [&rules](const core::AvpId& id) {
    1003          351 :         for (const auto& kv : rules)
    1004          348 :             if (kv.second.getId() == id) return kv.first;
    1005            3 :         return std::numeric_limits<int>::max();  // not in the rules: last
    1006           22 :     };
    1007           22 :     std::vector<std::pair<int, Avp>> keyed;
    1008           22 :     keyed.reserve(avps.size());
    1009          126 :     for (auto& a : avps) {
    1010          104 :         int r = a.raw_ ? std::numeric_limits<int>::max() : rank(a.id_);
    1011          104 :         keyed.emplace_back(r, std::move(a));
    1012              :     }
    1013          175 :     std::stable_sort(keyed.begin(), keyed.end(), [](const auto& x, const auto& y) { return x.first < y.first; });
    1014          126 :     for (size_t i = 0; i < keyed.size(); ++i) avps[i] = std::move(keyed[i].second);
    1015           22 : }
    1016              : 
    1017              : // ============================================================================
    1018              : // Avp::fromJson
    1019              : // ============================================================================
    1020          242 : Avp Avp::fromJson(const std::string& avpName, const nlohmann::json& value, const stack::Dictionary& dict) {
    1021          242 :     Avp avp;
    1022              : 
    1023              :     // Resolve AVP id from name
    1024          242 :     const stack::Avp* sa = dict.getAvp(avpName);
    1025          242 :     if (!sa) {
    1026           18 :         uint32_t code = 0, vendor = 0;
    1027           18 :         if (!parseRawAvpKey(avpName, code, vendor)) throw std::runtime_error("Unknown AVP name: " + avpName);
    1028              : 
    1029              :         // Raw AVP (negative testing): verbatim data, explicit or default flags.
    1030           13 :         avp.raw_ = true;
    1031           13 :         avp.id_ = core::AvpId(static_cast<core::S32>(code), static_cast<core::S32>(vendor));
    1032           13 :         avp.flags_ = vendor != 0 ? core::AvpFlagVendor : 0;
    1033           13 :         std::string hex;
    1034           13 :         if (value.is_string()) {
    1035            7 :             hex = value.get<std::string>();
    1036            6 :         } else if (value.is_object()) {
    1037            5 :             auto itHex = value.find("hex");
    1038            5 :             if (itHex == value.end() || !itHex->is_string())
    1039            1 :                 throw std::runtime_error("Raw AVP '" + avpName + "' object requires a 'hex' string");
    1040            4 :             hex = itHex->get<std::string>();
    1041            4 :             auto itFlags = value.find("flags");
    1042            4 :             if (itFlags != value.end()) {
    1043              :                 // Signed or unsigned JSON integer (parsed literals are unsigned,
    1044              :                 // programmatic ones signed); reject floats and out of range.
    1045            4 :                 if (!itFlags->is_number_integer() || itFlags->get<int64_t>() < 0 || itFlags->get<int64_t>() > 0xFF)
    1046            2 :                     throw std::runtime_error("Raw AVP '" + avpName + "' flags must be 0..255");
    1047            2 :                 avp.flags_ = static_cast<uint8_t>(itFlags->get<int64_t>());
    1048              :             }
    1049              :         } else {
    1050            1 :             throw std::runtime_error("Raw AVP '" + avpName + "' value must be a hex string or {hex, flags}");
    1051              :         }
    1052            9 :         auto raw = fromHex(hex);
    1053            7 :         avp.data_ = std::string(reinterpret_cast<const char*>(raw.data()), raw.size());
    1054            7 :         return avp;
    1055           13 :     }
    1056              : 
    1057          224 :     avp.id_ = sa->getId();
    1058              : 
    1059              :     // Set flags from dictionary
    1060          224 :     avp.flags_ = 0;
    1061          224 :     if (sa->vBit()) avp.flags_ |= core::AvpFlagVendor;
    1062          224 :     if (sa->mBit()) avp.flags_ |= core::AvpFlagMandatory;
    1063              : 
    1064          224 :     const stack::Format* fmt = sa->getFormat();
    1065          224 :     if (!fmt || fmt->isReserved()) throw std::runtime_error("No format for AVP: " + avpName);
    1066              : 
    1067          224 :     auto basicType = stack::Format::Type::asEnum(fmt->getName());
    1068              : 
    1069          224 :     switch (basicType) {
    1070            7 :         case stack::Format::Type::Integer32:
    1071              :         case stack::Format::Type::Enumerated:
    1072            7 :             avp.data_ = value.get<int32_t>();
    1073            7 :             break;
    1074              : 
    1075            2 :         case stack::Format::Type::Integer64:
    1076            2 :             avp.data_ = value.get<int64_t>();
    1077            2 :             break;
    1078              : 
    1079           24 :         case stack::Format::Type::Unsigned32:
    1080           24 :             avp.data_ = value.get<uint32_t>();
    1081           24 :             break;
    1082              : 
    1083            2 :         case stack::Format::Type::Unsigned64:
    1084            2 :             avp.data_ = value.get<uint64_t>();
    1085            2 :             break;
    1086              : 
    1087            2 :         case stack::Format::Type::Float32:
    1088            2 :             avp.data_ = value.get<float>();
    1089            2 :             break;
    1090              : 
    1091            2 :         case stack::Format::Type::Float64:
    1092            2 :             avp.data_ = value.get<double>();
    1093            2 :             break;
    1094              : 
    1095           22 :         case stack::Format::Type::Address:
    1096           22 :             avp.data_ = value.get<std::string>();
    1097           22 :             break;
    1098              : 
    1099            2 :         case stack::Format::Type::Time:
    1100              :             // JSON has UNIX epoch, convert to NTP
    1101            2 :             avp.data_ = value.get<uint32_t>() + core::NtpEpochOffset;
    1102            2 :             break;
    1103              : 
    1104            4 :         case stack::Format::Type::Grouped: {
    1105            4 :             std::vector<Avp> children;
    1106           13 :             for (auto& [key, val] : value.items()) {
    1107            9 :                 if (val.is_array()) {
    1108            3 :                     for (const auto& elem : val) children.push_back(Avp::fromJson(key, elem, dict));
    1109              :                 } else {
    1110            8 :                     children.push_back(Avp::fromJson(key, val, dict));
    1111              :                 }
    1112            4 :             }
    1113            4 :             sortByRules(children, sa->avprules());
    1114            4 :             avp.data_ = std::move(children);
    1115            4 :             break;
    1116            4 :         }
    1117              : 
    1118           71 :         case stack::Format::Type::UTF8String:
    1119              :         case stack::Format::Type::DiameterIdentity:
    1120              :         case stack::Format::Type::DiameterURI:
    1121              :         case stack::Format::Type::IPFilterRule:
    1122              :         case stack::Format::Type::QoSFilterRule:
    1123           71 :             avp.data_ = value.get<std::string>();
    1124           71 :             break;
    1125              : 
    1126              :         // OctetString: hex string -> raw bytes, or a readable form (object)
    1127           86 :         default: {
    1128           86 :             if (value.is_object()) {
    1129           39 :                 avp.data_ = octetsFromForm(value, avpName);
    1130           23 :                 break;
    1131              :             }
    1132           47 :             auto hex = value.get<std::string>();
    1133           47 :             auto raw = fromHex(hex);
    1134           47 :             avp.data_ = std::string(reinterpret_cast<const char*>(raw.data()), raw.size());
    1135           47 :             break;
    1136           47 :         }
    1137              :     }
    1138              : 
    1139          208 :     return avp;
    1140           27 : }
    1141              : 
    1142              : }  // namespace codec
    1143              : }  // namespace diametercodec
    1144              : }  // namespace ert
        

Generated by: LCOV version 2.0-1