package frame import ( "encoding/binary" "fmt" ) // ControlEnvelopeMagic is the 4-byte prefix marking a v2 control message multiplexed through the // PacketConnection's send_packet path. An IPv4 packet's first byte is 0x4X and an IPv6 packet's // first byte is 0x6X, so this magic (starting with 0xAA) never collides with a real IP packet. var ControlEnvelopeMagic = [4]byte{0xAA, 0xAA, 0xC0, 0x01} // ControlKind is the on-wire byte selector inside a control envelope. type ControlKind byte // Known control kinds (must match crates/aura-proto/src/frame.rs ControlKind). const ( ControlCrlPush ControlKind = 0x01 ControlCrlAck ControlKind = 0x02 ControlExtendBridge ControlKind = 0x03 ControlCircuitReady ControlKind = 0x04 ControlCircuitFailed ControlKind = 0x05 ) // EncodeControlEnvelope wraps (kind, payload) as // // MAGIC(4) || kind(u8) || u32_be(payload_len) || payload // // suitable for shipping through PacketConnection.SendPacket. func EncodeControlEnvelope(kind ControlKind, payload []byte) []byte { out := make([]byte, 0, len(ControlEnvelopeMagic)+1+4+len(payload)) out = append(out, ControlEnvelopeMagic[:]...) out = append(out, byte(kind)) var lb [4]byte binary.BigEndian.PutUint32(lb[:], uint32(len(payload))) out = append(out, lb[:]...) out = append(out, payload...) return out } // DecodeControlEnvelope returns (kind, payload, true, nil) if buf starts with the magic and // parses cleanly. If buf does NOT start with the magic (i.e. it is a normal IP packet) the third // return is false and the error is nil. A malformed envelope (truncated) returns an error. func DecodeControlEnvelope(buf []byte) (ControlKind, []byte, bool, error) { if len(buf) < len(ControlEnvelopeMagic) { return 0, nil, false, nil } for i, b := range ControlEnvelopeMagic { if buf[i] != b { return 0, nil, false, nil } } rest := buf[len(ControlEnvelopeMagic):] if len(rest) < 1 { return 0, nil, true, fmt.Errorf("%w: control envelope: missing kind", ErrMalformedFrame) } kind := ControlKind(rest[0]) if len(rest) < 5 { return 0, nil, true, fmt.Errorf("%w: control envelope: missing payload length", ErrMalformedFrame) } plen := int(binary.BigEndian.Uint32(rest[1:5])) if len(rest) < 5+plen { return 0, nil, true, fmt.Errorf("%w: control envelope: truncated payload", ErrMalformedFrame) } payload := make([]byte, plen) copy(payload, rest[5:5+plen]) return kind, payload, true, nil }