A streaming MQTT 3.1.1 and MQTT 5.0 encoder and decoder in C99. You give it bytes from the network, and it calls your callbacks with what it finds. You describe a packet, and it writes the bytes. It checks every protocol rule that a codec can check. It has no dependencies and allocates no memory.
The codec covers every packet and property in both versions. Releases follow Semantic Versioning. The public API is the two headers in include/mqtt_codec.
The codec keeps these promises, so you can rely on them:
- Streaming. The decoder reads one byte at a time and keeps its place between calls. Bytes can arrive in chunks of any size.
- No allocation. The codec never allocates or copies. Callbacks get pointers into your input buffer. The encoder writes into a buffer that you supply.
- Callbacks in wire order. The decoder calls a callback for each string, binary field, payload, and property. Fixed-size fields, such as flags and Packet Identifiers, are in
codec->decoder.packetwhen the packet's end callback runs. - Strict. The codec rejects everything that the specification calls malformed or a protocol error, with the Reason Code that the specification names. The encoder checks outgoing packets the same way, so a strict peer accepts everything you send.
- Both versions. The CONNECT selects MQTT 3.1.1 or MQTT 5.0. MQTT 3.1 is out of scope.
- Aware of the connection. A codec is a client or a server. It tracks the connection state, and it enforces the limits that each side announces.
- Portable. The library is C99 and needs only the C standard library. The tests use C++, but a project that uses the codec never needs it.
- Traced to the specification. Each normative statement that a codec can check has a test with the statement ID in its name.
Your application owns everything else: sockets, TLS, keep alive timers, session storage, Packet Identifier allocation, the topic alias map, authentication methods, subscriptions, and the decision to accept a connection.
With CMake, fetch a release tag:
include(FetchContent)
FetchContent_Declare(mqtt_codec
GIT_REPOSITORY https://github.com/shaunpersad/mqtt-codec.git
GIT_TAG v1.0.0)
FetchContent_MakeAvailable(mqtt_codec)
target_link_libraries(my_app PRIVATE mqtt_codec::mqtt_codec)add_subdirectory works the same way with a copy of the repository. To install it system-wide instead:
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DMQTT_CODEC_BUILD_TESTS=OFF
cmake --build build
cmake --install buildThen use find_package(mqtt_codec 1.0 REQUIRED) in CMake, or pkg-config --cflags --libs mqtt_codec with any other build system.
Each connection gets its own mqtt_codec. The settings hold your callbacks, and they must outlive the codec. include/mqtt_codec/mqtt.h documents every type, setting, and callback.
The examples use two small helpers:
#include <mqtt_codec/mqtt_codec.h>
#include <string.h>
/* Encodes a message and writes it to the socket. Returns 0 when the message breaks a rule or is too large. */
static int send_message(mqtt_codec *codec, const mqtt_message *message) {
mqtt_byte out[1024];
size_t length = 0;
if (mqtt_codec_encode(codec, message, out, sizeof out, &length) != MQTT_RESULT_DONE) {
return 0;
}
return write_all(codec->context, out, length);
}
static mqtt_utf8_string text(const char *value) {
mqtt_utf8_string string;
string.length = (mqtt_int2)strlen(value);
string.data = (const mqtt_byte *)value;
return string;
}static mqtt_result on_connack_end(mqtt_codec *codec) {
/* After a refusal, mqtt_codec_decode returns MQTT_RESULT_CLOSE_CONNECTION. */
if (codec->decoder.packet.body.connack.reason_code == MQTT_REASON_CODE_SUCCESS) {
start_session(codec->context);
}
return MQTT_RESULT_DONE;
}
mqtt_codec_settings settings;
mqtt_codec_settings_init(&settings);
settings.on_connack_end = on_connack_end;
mqtt_codec codec;
mqtt_codec_init(&codec, MQTT_CODEC_MODE_CLIENT, &settings, c);
mqtt_properties properties = {0};
properties.present = MQTT_PROPERTY(MQTT_PROPERTY_IDENTIFIER_RECEIVE_MAXIMUM);
properties.receive_maximum = 16; /* The decoder now rejects a 17th unacknowledged QoS 1 or 2 PUBLISH. */
mqtt_message connect = {0};
connect.type = MQTT_PACKET_TYPE_CONNECT;
connect.body.connect.protocol_version = MQTT_PROTOCOL_VERSION_5;
connect.body.connect.clean_start = 1;
connect.body.connect.keep_alive = 60;
connect.body.connect.client_identifier = text("sensor-1");
connect.body.connect.properties = &properties;
send_message(&codec, &connect);A server checks the login in on_connect_end and answers right away. The codec has already applied the CONNECT, so the CONNACK encodes from inside the callback.
static mqtt_result on_connect_username(
mqtt_codec *codec, const mqtt_byte *at, mqtt_int2 length, mqtt_int2 total_length) {
connection *c = codec->context;
if (total_length > sizeof c->username) {
return mqtt_codec_fail(codec, MQTT_REASON_CODE_BAD_USERNAME_OR_PASSWORD, "user name too long");
}
memcpy(c->username + c->username_length, at, length); /* A field can arrive in several chunks. */
c->username_length += length;
return MQTT_RESULT_DONE;
}
static mqtt_result on_connect_end(mqtt_codec *codec) {
connection *c = codec->context;
mqtt_message connack = {0};
if (!check_login(c)) {
/* The decoder stops here, before any packet the client sent after its CONNECT. */
return mqtt_codec_fail(codec, MQTT_REASON_CODE_BAD_USERNAME_OR_PASSWORD, "login failed");
}
connack.type = MQTT_PACKET_TYPE_CONNACK;
return send_message(codec, &connack) ? MQTT_RESULT_DONE : MQTT_RESULT_ERROR;
}on_connect_password collects the password the same way. When a callback fails, mqtt_codec_error_reply builds the CONNACK that refuses the client, in the client's protocol version. An MQTT 5.0 client that sends an empty Client Identifier must get an Assigned Client Identifier property in the CONNACK, or the encoder refuses it.
The topic and payload arrive in chunks that point into your input buffer. Copy what you need to keep. The end callback has the fixed-size fields, so it is the place to act and to acknowledge.
static mqtt_result on_publish_begin(mqtt_codec *codec) {
connection *c = codec->context;
c->topic_length = 0;
c->payload_length = 0;
return MQTT_RESULT_DONE;
}
static mqtt_result on_publish_topic_name(
mqtt_codec *codec, const mqtt_byte *at, mqtt_int2 length, mqtt_int2 total_length) {
connection *c = codec->context;
if (total_length > sizeof c->topic) {
return mqtt_codec_fail(codec, MQTT_REASON_CODE_TOPIC_NAME_INVALID, "topic too long");
}
memcpy(c->topic + c->topic_length, at, length);
c->topic_length += length;
return MQTT_RESULT_DONE;
}
static mqtt_result on_publish_payload(mqtt_codec *codec, const mqtt_byte *at, size_t length, size_t total_length) {
connection *c = codec->context;
if (total_length > sizeof c->payload) {
return mqtt_codec_fail(codec, MQTT_REASON_CODE_PACKET_TOO_LARGE, "payload too large");
}
memcpy(c->payload + c->payload_length, at, length);
c->payload_length += length;
return MQTT_RESULT_DONE;
}
static mqtt_result on_publish_end(mqtt_codec *codec) {
connection *c = codec->context;
const mqtt_publish_packet *publish = &codec->decoder.packet.body.publish;
mqtt_message puback = {0};
deliver(c, c->topic, c->topic_length, c->payload, c->payload_length);
if (publish->flags.qos != 1) {
return MQTT_RESULT_DONE;
}
puback.type = MQTT_PACKET_TYPE_PUBACK;
puback.body.puback.packet_identifier = publish->packet_identifier;
return send_message(codec, &puback) ? MQTT_RESULT_DONE : MQTT_RESULT_ERROR;
}QoS 2 follows the same pattern: send a PUBREC from on_publish_end, then a PUBCOMP from on_pubrel_end.
Ask the encoder for the size first. To send a payload without copying it into the buffer, set payload.data to NULL. The encoder then writes everything except the payload, and you send the payload right after it.
mqtt_message publish = {0};
publish.type = MQTT_PACKET_TYPE_PUBLISH;
publish.body.publish.qos = 1;
publish.body.publish.packet_identifier = next_packet_identifier(c);
publish.body.publish.topic_name = text("backups/today");
publish.body.publish.payload.data = NULL;
publish.body.publish.payload.length = file_size;
size_t length = 0;
if (mqtt_codec_encode(&codec, &publish, NULL, 0, &length) == MQTT_RESULT_ERROR) {
return codec.encoder.reason_code; /* The message breaks a rule, or a limit the peer announced. */
}
mqtt_byte *header = malloc(length);
mqtt_codec_encode(&codec, &publish, header, length, &length);
write_all(c, header, length);
send_file(c, file, file_size);
free(header);The encoder refuses a QoS 1 or 2 PUBLISH when the peer's Receive Maximum is used up. codec.send_quota says how many more you can send. The codec updates its state on each successful encode, so encode each packet just before you send it.
Pass the bytes to the decoder as they arrive, in chunks of any size:
mqtt_result result = mqtt_codec_decode(&codec, buffer, received);
if (result == MQTT_RESULT_ERROR) {
mqtt_message reply;
if (mqtt_codec_error_reply(&codec, &reply)) {
send_message(&codec, &reply); /* A CONNACK or a DISCONNECT that tells the peer why. */
}
close_connection(c);
} else if (result == MQTT_RESULT_CLOSE_CONNECTION) {
close_connection(c); /* A DISCONNECT, or a CONNACK that refused the connection. */
}On an error, codec.decoder.reason_code and codec.decoder.reason_string say what went wrong. After an error or a close, every later call returns the same result.
codec.local_limits holds the limits this side announced, and the decoder enforces them. codec.peer_limits holds the limits the peer announced, and the encoder enforces them. To announce a limit, set it in the CONNECT or CONNACK you send. settings.maximum_packet_size caps the packet size that the decoder accepts.
The build needs CMake 3.21. The tests also need a C++17 compiler.
cmake --preset dev
cmake --build --preset dev
ctest --preset devThe dev preset builds with sanitizers. release builds optimized code, c-only builds without a C++ compiler, and libfuzzer builds the coverage-guided fuzz targets. Each preset treats warnings as errors.
Before a change merges, CI checks these things:
- The tests pass with gcc and clang, on Linux and macOS.
- The code matches
.clang-format. Runtools/format.sh check, ortools/format.sh fixto reformat. - Every normative statement has a test or a reason it does not apply. Run
python3 tests/spec/coverage/check.py. - Both fuzz targets run clean under libFuzzer. The
devbuild also has a standalone fuzz driver:./build/dev/mqtt_codec_fuzz --iterations 1000000.
A change to a protocol rule needs a test with the statement ID in its name. A change that breaks the public API needs a new major version. tests/spec/README.md explains how the spec tests are organized, and the choices made where the specification leaves room.
See LICENSE.