repository

BlowfishCMS

A small content management system for OpenBSD

version 0.45.6 · ISC · 2026-12-03 · releases

159 lines · 7.6 KB · download this file

package BlowfishCMS::MMDB;
# A reader for MaxMind DB files (the open MMDB format, version 2), enough to
# look an address up in a city database such as DB-IP's IP to City Lite.
# It reads only the bytes a lookup needs, so a large file isn't loaded into
# memory. No packages beyond Perl's own.
#
#   my $db=BlowfishCMS::MMDB->load($file) or die;   # undef if it isn't one
#   my $record=$db->lookup('192.0.2.1');             # a hash, or undef
#
# Format: https://maxmind.github.io/MaxMind-DB/ (a binary search tree over
# the address's bits, then a data section of typed values).
use v5.36;
use Socket qw(inet_pton AF_INET AF_INET6);

# How an MMDB file is laid out:
#   1. a search tree: each node holds two "records" (where to go for a 0 bit
#      and for a 1 bit). A lookup starts at node 0 and follows the address's
#      bits one by one. A record smaller than the node count is another node;
#      equal to it means "not in the database"; larger points into the data.
#   2. 16 zero bytes, then the data section: typed values (maps, strings,
#      numbers...), which can point to shared values elsewhere in it.
#   3. the marker below, then the metadata (itself a map in the data format):
#      the number of nodes, the size of a record (24, 28 or 32 bits), and so on.
my $marker="\xAB\xCD\xEFMaxMind.com";

# Opens a database file: finds the metadata after the last marker (within
# the file's last 128 KB), checks it's format version 2 with a known record
# size, and works out where the data section starts. Returns undef for
# anything else, so a bad download is refused before it's used.
sub load ($class,$file) {
    sysopen(my $fh,$file,0) or return undef;
    binmode $fh;
    my $size=-s $fh or return undef;
    # The metadata follows the last marker, within the file's last 128 KiB.
    my $tail=$size>131072 ? 131072 : $size;
    sysseek($fh,$size-$tail,0);sysread($fh,my $buf,$tail)==$tail or return undef;
    my $at=rindex($buf,$marker);return undef if $at<0;
    my $self=bless {fh=>$fh,size=>$size,pages=>{}},$class;
    my $meta_start=$size-$tail+$at+length $marker;
    my ($meta)=eval {$self->decode($meta_start,$meta_start)} or return undef;
    return undef unless ref $meta eq 'HASH' && ($meta->{binary_format_major_version}//0)==2;
    my ($nodes,$bits)=@$meta{qw(node_count record_size)};
    return undef unless $nodes && ($bits//0) =~ /\A(?:24|28|32)\z/;
    @$self{qw(meta nodes bits)}=($meta,$nodes,$bits);
    $self->{node_bytes}=$bits/4;
    $self->{data}=$nodes*$self->{node_bytes}+16;
    return undef if $self->{data}>$size;
    return $self;
}
# The database's metadata (type, build date, node count...).
sub metadata ($self) { return $self->{meta} }

# Bytes of the file, read 4 KiB at a time and kept (a lookup reads a few dozen).
# Reads bytes from the file through a small cache of 4 KB pages (up to 256),
# so repeated lookups mostly don't touch the disk.
sub bytes ($self,$off,$len) {
    my $out='';
    while ($len>0) {
        my $page=int($off/4096);
        my $p=$self->{pages}{$page} //= do {
            %{$self->{pages}}=() if keys %{$self->{pages}}>256;
            sysseek($self->{fh},$page*4096,0);sysread($self->{fh},my $b,4096);$b//'';
        };
        my $start=$off-$page*4096;my $take=length($p)-$start;
        die "MMDB: read past the end\n" if $take<=0;
        $take=$len if $take>$len;
        $out.=substr($p,$start,$take);$off+=$take;$len-=$take;
    }
    return $out;
}
# Bytes as an unsigned big-endian number.
sub uint ($bytes) { my $n=0;$n=$n*256+$_ for unpack 'C*',$bytes;return $n }

# A node's two records.
# A node's two records. 24- and 32-bit records are plain; with 28-bit
# records the middle byte's two halves belong to the left and right record.
sub node ($self,$n) {
    my $b=$self->bytes($n*$self->{node_bytes},$self->{node_bytes});
    return (uint(substr($b,0,3)),uint(substr($b,3,3))) if $self->{bits}==24;
    return (unpack 'N2',$b) if $self->{bits}==32;
    my @c=unpack 'C7',$b;   # 28 bits: the middle byte's halves go with each side
    return ((($c[3]>>4)<<24)|($c[0]<<16)|($c[1]<<8)|$c[2],(($c[3]&15)<<24)|($c[4]<<16)|($c[5]<<8)|$c[6]);
}

# Looks an address up: IPv4 or IPv6 (an IPv4 address written as IPv6,
# ::ffff:1.2.3.4, is treated as IPv4). In an IPv6 database the IPv4
# addresses are under ::/96, so a lookup for IPv4 first walks 96 zero bits
# (and remembers where that ends). Then it follows the address's bits and
# decodes the record it reaches. undef when the address isn't in it.
sub lookup ($self,$address) {
    $address=$1 if ($address//'') =~ /\A::ffff:(\d{1,3}(?:\.\d{1,3}){3})\z/i;   # IPv4, written as IPv6
    my $packed=($address//'') =~ /:/ ? inet_pton(AF_INET6,$address) : inet_pton(AF_INET,$address//'');
    return undef unless defined $packed;
    my @bits=split //,unpack 'B*',$packed;
    my $node=0;
    if (@bits==32 && ($self->{meta}{ip_version}//4)==6) {
        # IPv4 addresses sit under ::/96 in an IPv6 tree.
        $self->{v4} //= do {my $n=0;for (1..96) {last if $n>=$self->{nodes};$n=($self->node($n))[0]}$n};
        $node=$self->{v4};
    }
    for my $bit (@bits) {
        last if $node>=$self->{nodes};
        $node=($self->node($node))[$bit];
    }
    return undef if $node<=$self->{nodes};   # == nodes: not in the database
    my $off=$self->{data}+$node-$self->{nodes}-16;
    return undef if $off>=$self->{size};
    my ($value)=$self->decode($off,$self->{data});
    return $value;
}

# The value at $off (with $base the start of the data section, for pointers);
# returns the value and the offset after it.
# Decodes one value from the data section. Each value starts with a control
# byte: its top three bits are the type (0 means "extended": the next byte
# gives the type) and the low five bits the size (29-31 mean the size
# continues in 1-3 more bytes). Types: 1 pointer (to a value elsewhere),
# 2 text, 3 double, 4 bytes, 5/6/9/10 unsigned numbers, 7 map, 8 signed
# 32-bit number, 11 list, 14 true/false, 15 float. Maps and lists decode
# their contents one after another. Returns (value, where the next value starts).
sub decode ($self,$off,$base) {
    my $ctrl=ord $self->bytes($off++,1);
    my $type=$ctrl>>5;
    if ($type==1) {   # a pointer, into the data section
        my $ss=($ctrl>>3)&3;my $v=$ctrl&7;
        my $p=$ss==0 ? ($v<<8)|uint($self->bytes($off,1))
            : $ss==1 ? (($v<<16)|uint($self->bytes($off,2)))+2048
            : $ss==2 ? (($v<<24)|uint($self->bytes($off,3)))+526336
            : uint($self->bytes($off,4));
        my ($value)=$self->decode($base+$p,$base);
        return ($value,$off+$ss+1);
    }
    if ($type==0) {$type=7+ord $self->bytes($off++,1)}
    my $size=$ctrl&31;
    if ($size>=29) {
        my $n=$size-28;my $x=uint($self->bytes($off,$n));$off+=$n;
        $size=$n==1 ? 29+$x : $n==2 ? 285+$x : 65821+$x;
    }
    if ($type==2) {my $s=$self->bytes($off,$size);utf8::decode($s);return ($s,$off+$size)}
    if ($type==3) {return (unpack('d>',$self->bytes($off,8)),$off+8)}
    if ($type==4) {return ($self->bytes($off,$size),$off+$size)}
    if ($type==5 || $type==6 || $type==9 || $type==10) {return ($size ? uint($self->bytes($off,$size)) : 0,$off+$size)}
    if ($type==8) {my $n=$size ? uint($self->bytes($off,$size)) : 0;$n-=2**($size*8) if $size==4 && $n>=2**31;return ($n,$off+$size)}
    if ($type==7) {
        my %map;
        for (1..$size) {my $k;($k,$off)=$self->decode($off,$base);($map{$k},$off)=$self->decode($off,$base)}
        return (\%map,$off);
    }
    if ($type==11) {
        my @list;
        for (1..$size) {my $v;($v,$off)=$self->decode($off,$base);push @list,$v}
        return (\@list,$off);
    }
    if ($type==14) {return ($size ? 1 : 0,$off)}
    if ($type==15) {return (unpack('f>',$self->bytes($off,4)),$off+4)}
    die "MMDB: unknown data type $type\n";
}

1;