©Code by Samnoon
Blog
← All posts

cpp

Parsing binary protocols in C++ without copying: a Q.931 decoder

std::span, explicit byte order, a bounds-checked IE walker and a fuzzer, with Q.931 as the running example.

6 min read

The quickest way to parse a binary protocol in C or C++ is to cast the buffer to a packed struct and read the fields. It works the first time you try it. It's also wrong in at least three ways that only show up later, usually on a different machine.

This post builds a small Q.931 decoder the other way: a non-owning view of the bytes, explicit byte order, a bounds check before every read, and a fuzzer to confirm the bounds checks are where they should be. Q.931 is a good example because it's so typical of telecom protocols: a header that's almost fixed, followed by a list of type-length-value elements. If you haven't seen Q.931 before, the previous post explains the message format.

What's wrong with the struct cast

#pragma pack(push, 1)
struct Q931Header {
    uint8_t  protocol;
    uint8_t  cr_len;
    uint16_t call_ref;
    uint8_t  type;
};
#pragma pack(pop)
 
auto* h = reinterpret_cast<const Q931Header*>(buf);

The layout isn't actually fixed. The call reference is 0, 1 or 2 bytes long, as cr_len says. The struct assumes 2. Hand it a basic-rate message and every field after cr_len is read from the wrong offset.

The byte order is backwards. call_ref is big-endian on the wire, and on x86 or little-endian ARM, reading it as a uint16_t swaps the bytes. You can fix that with ntohs everywhere, right up until someone forgets one.

It's undefined behavior. Reading a uint16_t through a pointer to bytes breaks the strict aliasing rules, and packed members can be misaligned. x86 shrugs off misaligned reads. Some embedded CPUs fault on them, and the optimizer is allowed to assume they never happen.

And nothing checks the length. If the buffer is three bytes long, the cast reads past the end anyway.

A view, not a copy

C++20's std::span is a pointer plus a length that knows it doesn't own anything. Slicing it costs nothing, and every slice carries its own length, which makes it hard to walk off the end without noticing.

q931.hpp
#pragma once
 
#include <cstddef>
#include <cstdint>
#include <optional>
#include <span>
 
namespace q931 {
 
using Bytes = std::span<const std::uint8_t>;
 
struct Message {
    std::uint8_t protocol;       // 0x08 for Q.931
    std::uint16_t call_ref;      // value with the flag bit removed
    bool from_destination;       // the call reference flag
    std::uint8_t type;
    Bytes ies;                   // everything after the message type, unparsed
};
 
struct Ie {
    std::uint8_t id;
    Bytes body;                  // empty for single-byte IEs
};
 
std::optional<Message> parse(Bytes buf);
 
class IeReader {
public:
    explicit IeReader(Bytes area) : rest_(area) {}
    std::optional<Ie> next();
    bool malformed() const { return malformed_; }
 
private:
    Bytes rest_;
    bool malformed_ = false;
};
 
std::optional<std::uint8_t> cause_value(const Ie& ie);
 
}  // namespace q931

Two choices in that header need defending.

Message keeps the IEs as an unparsed span instead of decoding them all into a vector of structs. Most code that handles a message cares about one or two IEs, so walking the list lazily means nobody pays for the rest.

Errors are std::optional, not exceptions. A malformed message from the far end of a link isn't exceptional. It's Tuesday. Rejecting it should be cheap, and counting rejections should be easy.

There's a catch with spans: they point into the caller's buffer. Free or reuse that buffer and every Message and Ie made from it is dangling. That's the price of not copying, so keep decoded messages short-lived: decode, act, drop.

The header

q931.cpp
#include "q931.hpp"
 
namespace q931 {
 
std::optional<Message> parse(Bytes buf) {
    // Protocol discriminator, call reference length, then at least a message type
    if (buf.size() < 3) return std::nullopt;
 
    const std::size_t cr_len = buf[1] & 0x0F;
    if (cr_len > 2 || buf.size() < 3 + cr_len) return std::nullopt;
 
    // Big-endian on the wire. Shifting the bytes in gives the same result on any host.
    std::uint16_t cr = 0;
    for (std::size_t i = 0; i < cr_len; ++i) {
        cr = static_cast<std::uint16_t>((cr << 8) | buf[2 + i]);
    }
 
    const bool flag = cr_len > 0 && (buf[2] & 0x80) != 0;
    const std::uint16_t mask = cr_len == 2 ? 0x7FFF : 0x7F;
 
    return Message{
        .protocol = buf[0],
        .call_ref = static_cast<std::uint16_t>(cr & mask),
        .from_destination = flag,
        .type = buf[2 + cr_len],
        .ies = buf.subspan(3 + cr_len),
    };
}

The length check comes before any read that depends on it. That ordering is most of the discipline: never index the buffer with a number you haven't compared against size() first.

Byte order is handled by building the value with shifts, most significant byte first. That gives the same answer on every CPU, so there's no ntohs to forget and nothing to revisit when the code moves to different hardware.

The parser doesn't reject a protocol discriminator other than 08. That's policy, and it belongs to the caller. Keeping it out makes the parser easier to reuse and easier to fuzz.

Walking the IEs

q931.cpp (continued)
std::optional<Ie> IeReader::next() {
    if (rest_.empty() || malformed_) return std::nullopt;
 
    const std::uint8_t id = rest_[0];
 
    // Top bit set: a single-byte IE (Shift, Sending complete). No length, no body.
    if (id & 0x80) {
        rest_ = rest_.subspan(1);
        return Ie{id, {}};
    }
 
    // Identifier, length, then exactly `length` bytes of contents
    if (rest_.size() < 2 || rest_.size() < 2u + rest_[1]) {
        malformed_ = true;
        return std::nullopt;
    }
 
    const std::size_t len = rest_[1];
    Ie ie{id, rest_.subspan(2, len)};
    rest_ = rest_.subspan(2 + len);
    return ie;
}
 
std::optional<std::uint8_t> cause_value(const Ie& ie) {
    if (ie.id != 0x08 || ie.body.empty()) return std::nullopt;
 
    // Byte 3 holds the coding standard and location. If its extension bit is clear,
    // an optional byte 3a follows and the cause value moves one byte later.
    const std::size_t i = (ie.body[0] & 0x80) ? 1 : 2;
    if (i >= ie.body.size()) return std::nullopt;
    return ie.body[i] & 0x7F;
}
 
}  // namespace q931

next() returns nullopt both at the clean end of the list and when the list is broken, and malformed() tells you which one you got. A length byte that claims more than what's left stops the walk instead of reading whatever happens to follow the buffer in memory.

It doesn't track the current codeset, though. After a Shift IE, identifiers mean something else, and a real decoder needs to know that before it looks up names. That's a few more lines plus a table of the extra IEs, and it doesn't change the technique, so it's left out here.

Trying it

main.cpp
#include <array>
#include <cstdio>
 
#include "q931.hpp"
 
int main() {
    // The SETUP from the Q.931 post
    constexpr std::array<std::uint8_t, 28> setup{
        0x08, 0x02, 0x00, 0x01, 0x05,
        0x04, 0x03, 0x80, 0x90, 0xA3,
        0x18, 0x03, 0xA9, 0x83, 0x81,
        0x70, 0x0B, 0x81, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x30, 0x31, 0x30, 0x30,
    };
 
    const auto msg = q931::parse(setup);
    if (!msg) return 1;
 
    std::printf("type 0x%02x, call ref %u%s\n", unsigned{msg->type}, unsigned{msg->call_ref},
                msg->from_destination ? " (from destination)" : "");
 
    q931::IeReader reader{msg->ies};
    while (const auto ie = reader.next()) {
        std::printf("  IE 0x%02x, %zu bytes\n", unsigned{ie->id}, ie->body.size());
    }
    return reader.malformed() ? 2 : 0;
}
g++ -std=c++20 -Wall -Wextra -O2 q931.cpp main.cpp -o q931demo && ./q931demo
type 0x05, call ref 1
  IE 0x04, 3 bytes
  IE 0x18, 3 bytes
  IE 0x70, 11 bytes

Bearer capability, channel identification, called party number, exactly as decoded by hand in the last post.

Fuzz it

Bounds checks are only as good as the cases you thought of. A fuzzer thinks of the rest. With clang and libFuzzer the harness is a few lines:

fuzz.cpp
#include <cstddef>
#include <cstdint>
 
#include "q931.hpp"
 
extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t* data, std::size_t size) {
    const auto msg = q931::parse({data, size});
    if (!msg) return 0;
 
    q931::IeReader reader{msg->ies};
    while (const auto ie = reader.next()) {
        (void)q931::cause_value(*ie);
    }
    return 0;
}
clang++ -std=c++20 -g -O1 -fsanitize=fuzzer,address,undefined q931.cpp fuzz.cpp -o q931-fuzz
mkdir -p corpus
printf '\x08\x02\x00\x01\x45\x08\x02\x80\x90' > corpus/disconnect
./q931-fuzz corpus -max_total_time=300

AddressSanitizer turns any out-of-bounds read into an immediate crash with a stack trace, and UBSan catches the shifts and conversions that would otherwise go quietly wrong. Seed the corpus with a few real messages (the one above is a DISCONNECT with cause 16) and let it mutate outward from there.

Was it worth it?

"Zero-copy" sounds like a performance claim, and it is one, but speed isn't the main reason to write parsers this way. The main reason is that every read has an obvious bounds check right next to it, and a fuzzer can confirm there's no path that skips one. A packed-struct parser can be made safe as well. It's just much harder to look at one and know that it is.

References

#cpp #q931 #parsing