#!/usr/bin/perl
#
# convert-ban-databases - convert ircd-hybrid's binary ban databases
# (kline.db, dline.db, xline.db, resv.db, used up to 8.2.46) to the JSON
# files read by 8.2.47 and later (kline.json, dline.json, xline.json,
# resv.json).
#
# Only uses Perl core features, so that it can run from a maintainer
# script with nothing but perl-base installed.
#
# The old format (src/conf_db.c in 8.2.46) is big-endian: a uint32
# version (1), a uint32 record count, then the records. A string is a
# uint32 length that includes the trailing NUL (0 meaning NULL) followed
# by that many bytes. The record layouts are:
#
#   kline.db  user, host, reason (strings), setat, until (uint64)
#   dline.db  host, reason (strings), setat, until (uint64)
#   xline.db  mask, reason (strings), setat, expire (uint64)
#   resv.db   mask, reason (strings), setat, expire (uint64)
#
# The new format (src/conf_db.c in 8.2.47) is read with jansson, which
# requires valid UTF-8, string values for every string field and integer
# timestamps, and skips any entry that doesn't fit.

use strict;
use warnings;

# This parses files that the IRC server writes, which contain data from
# its users, and needs no privileges beyond those of the irc user, so
# refuse to run as root at all, before doing anything else.
if ($> == 0 || $< == 0) {
    print STDERR "$0: refusing to run as root; run it as the irc user:\n"
               . "  runuser -u irc -- $0" . (@ARGV ? " @ARGV" : '') . "\n";
    exit 64;
}

my $DEFAULT_DIR = '/var/lib/ircd-hybrid';
my $NOREASON = '<No reason supplied>';   # CONF_NOREASON in src/defaults.h

my %DB = (
    kline => { key => 'k_lines',
               fields => [qw(user host reason)],
               masks => [qw(user host)] },
    dline => { key => 'd_lines',
               fields => [qw(host reason)],
               masks => [qw(host)] },
    xline => { key => 'x_lines',
               fields => [qw(mask reason)],
               masks => [qw(mask)] },
    resv  => { key => 'resv',
               fields => [qw(mask reason)],
               masks => [qw(mask)] },
);
my @ORDER = qw(kline dline xline resv);

sub usage {
    print STDERR <<"EOF";
Usage: runuser -u irc -- $0 [--force] [--dry-run] [DIRECTORY]

Converts kline.db, dline.db, xline.db and resv.db in DIRECTORY
(default $DEFAULT_DIR) to kline.json, dline.json, xline.json and
resv.json for ircd-hybrid 8.2.47 and later. Stop ircd-hybrid first:
a running 8.2.46 server only writes its .db files periodically and when
it exits.

Run it as the user ircd-hybrid runs as (irc); it refuses to run as root.

The .db files are left in place. An existing .json file is not
overwritten unless --force is given.

  --force          overwrite existing .json files
  --dry-run        report what would be converted, write nothing

Exit status: 0 if everything was converted, 1 if a database was left
alone because its .json file already exists, 2 if a database could not be
read completely or some entries could not be converted (the others are
still written; details are printed on standard error).
EOF
    exit 64;
}

my ($force, $dry_run) = (0, 0);
my @args;
while (@ARGV) {
    my $a = shift @ARGV;
    if    ($a eq '--force')   { $force = 1 }
    elsif ($a eq '--dry-run') { $dry_run = 1 }
    elsif ($a eq '--help' || $a eq '-h') { usage() }
    elsif ($a =~ /^-/)        { print STDERR "Unknown option $a\n"; usage() }
    else                      { push @args, $a }
}
usage() if @args > 1;
my $dir = $args[0] // $DEFAULT_DIR;

# Strict UTF-8 as jansson accepts it: no overlong forms, no surrogates,
# nothing above U+10FFFF.
my $UTF8 = qr/\A(?:
      [\x00-\x7F]
    | [\xC2-\xDF][\x80-\xBF]
    | \xE0[\xA0-\xBF][\x80-\xBF]
    | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}
    | \xED[\x80-\x9F][\x80-\xBF]
    | \xF0[\x90-\xBF][\x80-\xBF]{2}
    | [\xF1-\xF3][\x80-\xBF]{3}
    | \xF4[\x80-\x8F][\x80-\xBF]{2}
)*\z/x;

sub latin1_to_utf8 {
    my ($s) = @_;
    $s =~ s/([\x80-\xFF])/chr(0xC0 | (ord($1) >> 6)) . chr(0x80 | (ord($1) & 0x3F))/ge;
    return $s;
}

sub json_string {
    my ($s) = @_;   # bytes, already valid UTF-8
    $s =~ s/(["\\])/\\$1/g;
    $s =~ s/\n/\\n/g;
    $s =~ s/\r/\\r/g;
    $s =~ s/\t/\\t/g;
    $s =~ s/([\x00-\x1F\x7F])/sprintf('\\u%04x', ord($1))/ge;
    return qq("$s");
}

# Reads one old-format database. Returns (\@records, $error); on a
# truncated or corrupt file, the records read before the problem are
# returned along with the error, as ircd-hybrid 8.2.46 itself does.
sub read_db {
    my ($path, $spec) = @_;
    open(my $fh, '<:raw', $path) or return (undef, "cannot open: $!");
    local $/;
    my $data = <$fh>;
    close $fh;
    my $pos = 0;
    my $len = length $data;

    my $u32 = sub {
        return undef if $pos + 4 > $len;
        my $v = unpack('N', substr($data, $pos, 4));
        $pos += 4;
        return $v;
    };
    my $u64 = sub {
        return undef if $pos + 8 > $len;
        my ($hi, $lo) = unpack('N N', substr($data, $pos, 8));
        $pos += 8;
        # jansson stores integers as signed 64-bit; anything larger can't
        # be represented (and is no real timestamp).
        return -1 if $hi >= 0x80000000;
        return ($hi << 32) | $lo;
    };
    my $str = sub {
        my $n = $u32->();
        return (undef, 0) unless defined $n;
        return (undef, 1) if $n == 0;              # NULL
        return (undef, 0) if $pos + $n > $len;
        my $s = substr($data, $pos, $n);
        $pos += $n;
        $s =~ s/\x00.*\z//s;                       # C string: up to the first NUL
        return ($s, 1);
    };

    # A file we can't make sense of produces no .json at all, so that
    # nothing is lost and a later run (with a fixed file) still converts it.
    my $version = $u32->();
    return (undef, 'empty or truncated header, not converted') unless defined $version;
    return (undef, "unsupported version $version, not converted") unless $version == 1;
    my $count = $u32->();
    return (undef, 'missing record count, not converted') unless defined $count;

    my @records;
    for my $i (1 .. $count) {
        my %r;
        for my $f (@{ $spec->{fields} }) {
            my ($s, $ok) = $str->();
            return (\@records, "truncated in record $i of $count") unless $ok;
            $r{$f} = $s;
        }
        my $setat = $u64->();
        my $until = $u64->();
        return (\@records, "truncated in record $i of $count")
            unless defined $setat && defined $until;
        @r{qw(created_at expires_at)} = ($setat, $until);
        push @records, \%r;
    }
    my $extra = $len - $pos;
    return (\@records, $extra ? "$extra trailing bytes ignored" : undef);
}

my $status = 0;

for my $name (@ORDER) {
    my $spec = $DB{$name};
    my $old = "$dir/$name.db";
    my $new = "$dir/$name.json";
    next unless -e $old;

    if (-e $new && !$force) {
        print STDERR "$name: $new already exists, not converting $old"
                   . " (use --force to overwrite)\n";
        $status = 1 if $status == 0;
        next;
    }

    my ($records, $error) = read_db($old, $spec);
    if (!defined $records) {
        print STDERR "$name: $old: $error\n";
        $status = 2;
        next;
    }
    if (defined $error) {
        print STDERR "$name: $old: $error\n";
        $status = 2;
    }

    my (@entries, $skipped, $recoded);
    $skipped = $recoded = 0;
    REC: for my $r (@$records) {
        for my $m (@{ $spec->{masks} }) {
            if (!defined $r->{$m} || $r->{$m} eq '') {
                print STDERR "$name: skipping an entry with an empty $m\n";
                $skipped++;
                next REC;
            }
            if ($r->{$m} !~ $UTF8) {
                (my $shown = $r->{$m}) =~ s/([^\x20-\x7E])/sprintf('\\x%02X', ord($1))/ge;
                print STDERR "$name: skipping \"$shown\": the $m is not valid UTF-8,"
                           . " which ircd-hybrid 8.2.47 can't store\n";
                $skipped++;
                next REC;
            }
        }
        if ($r->{created_at} < 0 || $r->{expires_at} < 0) {
            print STDERR "$name: skipping \"$r->{$spec->{masks}[-1]}\": timestamp out of range\n";
            $skipped++;
            next REC;
        }
        my $reason = $r->{reason};
        $reason = $NOREASON if !defined $reason || $reason eq '';
        if ($reason !~ $UTF8) {
            $reason = latin1_to_utf8($reason);
            $recoded++;
        }
        my @kv = map { json_string($_) . ': ' . json_string($r->{$_}) }
                 grep { $_ ne 'reason' } @{ $spec->{fields} };
        push @kv, '"reason": ' . json_string($reason),
                  sprintf('"created_at": %d', $r->{created_at}),
                  sprintf('"expires_at": %d', $r->{expires_at});
        push @entries, "        {\n            " . join(",\n            ", @kv) . "\n        }";
    }

    my $summary = scalar(@entries) . " of " . scalar(@$records) . " entries";
    $summary .= ", $skipped skipped" if $skipped;
    $summary .= ", $recoded reason(s) converted from Latin-1" if $recoded;
    $status = 2 if $skipped && $status < 2;

    if ($dry_run) {
        print "$name: would write $new ($summary)\n";
        next;
    }

    my $json = "{\n    \"$spec->{key}\": [\n" . join(",\n", @entries)
             . (@entries ? "\n" : '') . "    ]\n}\n";

    my $tmp = "$new.tmp.$$";
    my $ok = eval {
        my $old_umask = umask 077;
        open(my $out, '>:raw', $tmp) or die "cannot create $tmp: $!\n";
        umask $old_umask;
        print $out $json or die "cannot write $tmp: $!\n";
        close $out or die "cannot write $tmp: $!\n";
        rename $tmp, $new or die "cannot rename $tmp to $new: $!\n";
        1;
    };
    if (!$ok) {
        print STDERR "$name: $@";
        unlink $tmp;
        $status = 2;
        next;
    }
    print "$name: wrote $new ($summary)\n";
}

exit $status;
