IoT Bricks Try challenge Blog Sign in

Free stage 3 of 3: runs on your computer.

This is one piece of the broker that keeps a greenhouse of a thousand sensors talking to its grower.

Stage 3: Parse and validate CONNECT

Until now a broker that answers CONNACK to anything shaped like a CONNECT passed. From now on you read every field, and you reject what the specification forbids.

Why it matters

One misconfigured sensor in the greenhouse, with a wrong protocol level or a malformed packet, will eventually connect. The broker must refuse it cleanly. If a single bad device can crash the broker, it takes down the other 999 sensors with it. Validating every field is how one broken device stays one broken device.

The CONNECT packet

fixed header     10 <remaining length>
protocol name    00 04 "MQTT"
protocol level   04
connect flags    1 byte (see below)
keep-alive       2 bytes, seconds
payload          client ID, then (if flagged) will topic, will message, username, password

Strings and binary fields are a 2-byte big-endian length followed by that many bytes.

Connect flags, from the high bit to the low bit:

bit 7  username      bit 6  password     bit 5  will retain
bits 4-3  will QoS   bit 2  will flag    bit 1  clean session     bit 0  reserved (must be 0)

Your task

Close the connection without replying when the packet is malformed:

Two cases get an answer instead:

Run the tests

iotbricks test local --stage 3 --run ./iotbricks-mqtt-go

Hints

Hint 1: no panics on short input

Every one of these tests feeds you a packet that is too short, too long, or lying about its fields. Reading with an unchecked index or slice is how brokers crash. Write one small reader that reports "not enough bytes" instead of panicking, and use it for every field.

Hint 2: read in the order of the payload

The flags decide which payload fields exist, and the order is fixed: client ID, will topic, will message, username, password. Parse them in that order, then check that nothing is left.

Hint 3: a shape for the parser
parseConnect(body) -> returnCode, or "malformed"
    name   = readString();  must be "MQTT"
    level  = readByte();    if != 4 -> return 0x01
    flags  = readByte();    reject reserved bit, password-without-username
    skip 2 bytes (keep-alive)
    clientID = readString()
    if will flag: readString(), readBinary()
    if username:  readString()
    if password:  readBinary()
    if bytes remain: malformed
    if clientID is empty and clean session is off: return 0x02
    return 0x00

1Run the tests on your broker

iotbricks test local --stage 3 --run ./iotbricks-mqtt-go

--run is the command that starts your broker, for example --run "go run .". The broker must listen on the port in the MQTT_PORT environment variable (default 1883).

Previous stage

That was the last free stage

The next stages are tested on the platform. Sign in to continue.

Access is invitation-only during the preview.

Sign in with GitHub