networking · intermediate · ~20 min

Parse a TLS record header

Parse a fixed binary protocol header with a big-endian length field.

Challenge

A TLS record begins with a 5-byte header: content type (1 byte), protocol version (2 bytes — major then minor), and a record length (2 bytes, big-endian). Parse those four fields out of a fixed byte buffer. No network involved.

Task

Implement int tls_parse(const unsigned char *b, size_t n, int *type, int *major, int *minor, int *length) that reads the header from b and writes the four fields.

Layout: type = b[0], major = b[1], minor = b[2], length = (b[3] << 8) | b[4] (big-endian).

Input

  • b, n: the record bytes and how many are available.
  • type, major, minor, length: out-pointers for the four fields.

Output

Returns 0 on success (all four fields written), or -1 if fewer than 5 bytes are available (n < 5).

Example

{0x16,0x03,0x03,0x00,0x2f}   ->   0, type=22, major=3, minor=3, length=47
{0x17,0x03,0x03,0x01,0x00}   ->   0, type=23, length=256
n = 4                        ->   -1

Edge cases

  • Fewer than 5 bytes: return -1 without writing the outputs.
  • Read the length big-endian (high byte first).

Input format

Record bytes (b) and available length (n), plus out-pointers type, major, minor, length.

Output format

Returns 0 with the four fields written, or -1 if n < 5.

Constraints

Require at least 5 bytes; read the length field as big-endian (b[3] high byte, b[4] low byte).

Starter code

#include <stddef.h>

int tls_parse(const unsigned char *b, size_t n,
              int *type, int *major, int *minor, int *length) {
    /* TODO: need at least 5 bytes. type=b[0], version=b[1].b[2],
       length = big-endian b[3..4]. Return 0, or -1 if too short. */
    (void)b;(void)n;(void)type;(void)major;(void)minor;(void)length;
    return -1;
}

Common mistakes

Reading before the length check; little-endian length; sign-extending bytes.

Edge cases to handle

Exactly 5 bytes (minimum). Length 0x0100 = 256. Buffer shorter than 5.

Complexity

O(1).

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.