ggunzip - Unpicking the gzip header : Yr golygfa o Hescwm Uchaf, rhif 33

In the video we recorded a few days ago, Andy and I fumbled around for a couple of hours making a start on a version of gunzip, the venerable decompression program. This is one of those entirely unnecessary exercises in reproducing a piece of software that already exists and, in this case, is almost ubiquitious. I mean, there’s a good chance there was gzip compression involved in delivering this webpage to you.

As Andy has said many times though, it’s fun to make stuff that already exists, and we both have previous form[1] in this department.

In order to get going, we constructed the simplest possible gzip compressed file, then worked to read that back into plain text. gzip files are relatively simple, being quite a thin envelope around a stream of Deflate compressed data. There’s a little header at the front, the Deflate data in the middle, then a tiny footer at the end.

We ended the video in triumph, extracting a single byte payload.

Verifying The gzip Header

The gzip header is a short sequence of bytes at the start of the file. There are ten required bytes, followed by a number of optional fields. The bytes are arranged in little-endian order, that is the low byte arrives first.

gzip header
Field Size in bytes Description

ID1

1

First magic number. Must be 1F.

ID2

1

Second magic number. Must be 88.

CM

1

Compression method. Must be 8, indicating Deflate.

FLG

1

Flags.

MTIME

4

The file’s last modified time, in Unix time. 0 means no time is available.

XFL

1

Extra flags.

OS

1

Filesystem on which the compression was performed.

XLEN

0 or 2

The size in bytes of the extra field, which is present if FEXTRA (FLG bit 2) is set.

Extra field

0 or XLEN

The extra field data.

File name

0 or varies

Null terminated name of the compressed file. Only present if FNAME (FLG bit 3) is set.

File comment

0 or varies

Null terminated file comment. Present if FCOMMENT (FLG bit 4) is set.

CRC16

0 or 2

Two least significant bytes of the CRC-32 of all the bytes up to, but not including, this field. Present if FHCRC (FLG bit 1) is set.

For a complete description of the gzip file format, and the various header flags and fields see RFC 1952: GZIP file format specification version 4.3.

The gzip header we constructed was as minimal as it could be. We provided the bytes that were required - ID1 & ID2, CM, FLG, MTIME, XFL, and OS - but turned off all the flags, as we didn’t provide any of the optional elements.

Given that minimal header, we then wrote as little code as possible to verify it. This was not out of carelessness or laziness. We just wanted to get past it so we could get onto the meatier job of decompressing the data.

verify_gzip_header
fn verify_gzip_header<R: Read + ?Sized>(f: &mut R) -> Result<(), BadHeader> {
    let mut magic_buf = [0; 2];  (1)
    f.read_exact(&mut magic_buf).unwrap();

    if magic_buf != [0x1F, 0x8B] {
        return Err(BadHeader::BadMagicNumber);
    }

    let mut compression_buf = [0; 1]; (2)
    f.read_exact(&mut compression_buf).unwrap();

    if compression_buf != [0x08] {
        return Err(BadHeader::UnknownCompressionScheme);
    }

    let mut remaining_header_buf = [0; 7]; (3)
    f.read_exact(&mut remaining_header_buf).unwrap();

    Ok(()) (4)
}
  1. Read ID1 and ID2, confirming they are the two magic values we expect.

  2. Read CM, and check that it is 8.

  3. Read and discard the rest of the header.

  4. If we get this far, this looks like a file we can deal with.

A Header Struct

During our conversation, I said there’s a clear future direction for this function, which is to load the various headers into a little data structure. It could be, I said, "an exercise for the viewer".

Friends, I am that viewer.

Looking at the gzip header definition, you can probably cast it into code using the language of your choice. Here, of course, we’re using Rust.

struct Header
struct Header {
    flags: Flags,
    timestamp: Option<u32>,
    extra_flag: ExtraFlag,
    filesystem: Filesystem,
    extra_field: Option<Vec<u8>>,
    filename: Option<String>,
    comment: Option<String>,
    crc16: Option<u16>,
}

You can probably also see the general shape of the code to populate the header. Read the first few bytes to populate the flag members, then check those flags to determine which of the optional fields to populate.

And that’s just what I did.

In the minimal code above, we already have near repetition reading the bytes and checking their values. That was my initial hook. I extracted out a function verify_gzip_magic_number, followed by verify_compression_scheme. I then worried away at those to reduce them down. Kent Beck’s technique, which comes to me via Ron Jeffries, of making things more similar in order to enable duplication to be eliminated was my go-to here.

I’ll spare you the full ins and outs[2] but after a few rounds, I had these little helper functions.

fn verify_gzip_magic_number<R: Read + ?Sized>(
    f: &mut R,
) -> Result<(), BadHeader> {
    verify_byte_sequence(f, &[0x1F, 0x8B], BadHeader::BadMagicNumber)
}

fn verify_compression_scheme<R: Read + ?Sized>(
    f: &mut R,
) -> Result<(), BadHeader> {
    verify_byte_sequence(f, &[0x08], BadHeader::UnknownCompressionScheme)
}

fn verify_byte_sequence<R: Read + ?Sized>(
    f: &mut R,
    expected: &[u8],
    error: BadHeader,
) -> Result<(), BadHeader> {
    let cs_buf = read_bytes(f, expected.len())?;
    if cs_buf == expected {
        Ok(())
    } else {
        Err(error)
    }
}

fn read_bytes<R: Read + ?Sized>(
    f: &mut R,
    len: usize,
) -> Result<Vec<u8>, BadHeader> {
    let mut buf = vec![0u8; len]; (1)
    f.read_exact(&mut buf).or(Err(BadHeader::EndOfFile))?; (2)
    Ok(buf)
}
  1. The initial code used fixed sized buffers. This code uses a Vector, because we’re specifying the size at runtime.

  2. If read_exact fails, it returns an io::Error. We’re using or to instead return an error of our own.

You might well be thinking that looks like quite a lot more code. Well, yes it is, and no it isn’t. I’ve broken the code out into several functions, which always carries a certain amount of overhead. The code here also does more, covering error cases the original code ignores. But let’s have a look at where these functions are called from.

Compare verify_gzip_header before and after. Even when squashed down into a narrow column, after is easier on the eye. It’s shorter, has expressive names, and straight through control flow.

verify_gzip_header before and after
Before After
fn verify_gzip_header<R: Read + ?Sized>(f: &mut R) -> Result<(), BadHeader> {
    let mut magic_buf = [0; 2];
    f.read_exact(&mut magic_buf).unwrap();

    if magic_buf != [0x1F, 0x8B] {
        return Err(BadHeader::BadMagicNumber);
    }

    let mut compression_buf = [0; 1];
    f.read_exact(&mut compression_buf).unwrap();

    if compression_buf != [0x08] {
        return Err(BadHeader::UnknownCompressionScheme);
    }

    let mut remaining_header_buf = [0; 7];
    f.read_exact(&mut remaining_header_buf).unwrap();

    Ok(())
}
fn verify_gzip_header<R: Read + ?Sized>(
f: &mut R,
) -> Result<(), BadHeader> {
    verify_gzip_magic_number(f)?;
    verify_compression_scheme(f)?;

    let mut remaining_header_buf = [0; 7];
    f.read_exact(&mut remaining_header_buf).unwrap();

    Ok(())
}

Reading The Header

From there[3], I extended out a field at a time until I had pulled everything I could.

verify_gzip_header
fn verify_gzip_header<R: Read + ?Sized>(
    f: &mut R,
) -> Result<Header, BadHeader> {
    verify_gzip_magic_number(f)?;
    verify_compression_scheme(f)?;

    let flags = read_flags(f)?;
    let timestamp = read_timestamp(f)?;
    let extra_flag = read_extra_flag(f)?;
    let filesystem = read_filesystem(f)?;

    let extra_field =
        optional_field(flags.contains(&Flag::FEXTRA), f, read_extra)?;
    let filename =
        optional_field(flags.contains(&Flag::FNAME), f, read_string)?;
    let comment =
        optional_field(flags.contains(&Flag::FCOMMENT), f, read_string)?;
    let crc16 = optional_field(flags.contains(&Flag::FHCRC), f, read_crc16)?;

    Ok(Header {
        flags,
        timestamp,
        extra_flag,
        filesystem,
        extra_field,
        filename,
        comment,
        crc16,
    })
}

For each field, I used read_bytes to grab the raw input, then converted to the appropriate representation. For some, like timestamp that was simply converting the bytes to an integer of appropriate size. For others, it was little more involved. I’m still quite new to Rust, but my inclination is to try and go maximally Rust[4]. Where the specification has given a list of specific values, such as for the filesystem, I’m choosing to spell that out as an enumeration, for example. However, those are details hidden away in read_filesystem and friends. Here, in verify_gzip_header, we’re just stepping through one field at a time. We can map this directly back to the gzip header definition and see that it matches.

As little demonstration I whipped up a function to print out the header, and had fun pointing it at whatever gzip files I could find lying around on my laptop.

print_header
fn print_header(mut f: File) {
    let header = verify_gzip_header(&mut f).unwrap();

    header.filename.map(|n| println!("Filename:\t{}", n));
    header.comment.map(|c| println!("Comment:\t{}", c));
    println!("Filesystem:\t{}", header.filesystem);
    header.timestamp.map(|t| {
        let ts = Utc
            .timestamp_opt(t as i64, 0)
            .single()
            .unwrap()
            .format("%Y-%m-%d %H:%M:%S")
            .to_string();
        println!("Timestamp:\t{}", ts)
    });
    println!("Compression:\t{}", header.extra_flag);
}
jez@exmachina ~/w/a/ggunzip (main)> cargo run -- --header examples/uncompressed_a.gz
Filesystem:     Unknown
Compression:    Default

jez@exmachina ~/w/a/ggunzip (main)> cargo run -- --header ~/Downloads/cnijfilter2-6.70-1-deb.tar.gz
Filename:       cnijfilter2-6.70-1-deb.tar
Filesystem:     Unix
Timestamp:      2026-05-15 21:19:46
Compression:    Default

jez@exmachina ~/w/a/ggunzip (main)> cargo run -- --header ~/website-src/build/files/mango/mango-bin.tar.gz
Filesystem:     FAT
Compression:    Default

Same Bat-Time, Same Bat-Channel

Andy and I got together again earlier this week, in which we continued on in our mission to actually try and decompress some data. No spoilers, but let’s just say we’re not quite there yet 🙂


2. Although should you wish to reconstruct them, the code lives here.
3. Aka drawing the rest of the owl
4. While emphatically not Rustmaxxing.

Tagged rust, code, and ggunzip


Jez Higgins

Freelance software grandad
software created
extended or repaired


Jez Higgins

Freelance software grandad
software created
extended or repaired


Jez Higgins

Freelance software grandad
software created
extended or repaired



Jez Higgins

Freelance software grandad
software created
extended or repaired


Jez Higgins

Freelance software grandad
software created
extended or repaired


Jez Higgins

Freelance software grandad
software created
extended or repaired