#!/usr/bin/env perl
use Fcntl qw(:flock);
use Sys::Syslog;
use Tie::File;
use Getopt::Long;
use JSON qw(encode_json to_json);
use warnings;
use strict;
use Config::Merge('My::Config' => '/etc/firewall/conf');
use My::Config;
my $DEFAULT_LIMIT = 50;

my $runonce;

# Called several times to ensure that, even if this script is loaded as a
# library for a oneliner, another concurrent use of this script will fail.
sub runonce {
    return if defined $runonce;
    open $runonce, '<', $0 or die "Unable to open self for reading $0 : $!";
    flock $runonce, LOCK_EX | LOCK_NB
        or die "another outbound-throttle is already running";
}

sub help {
    my $msg = shift;
    print STDERR <<"USAGE";
Usage: $0 -u <USER> [-l <LIMIT>] [--config-only]

  Restricts outbound web traffic for USER with http-output-limits chain.
  
  Limited users fill a LIMIT-size bucket of tokens at a rate of 1/min, and
  spend a token to create a new outbound HTTP connection. When the bucket is
  empty, new outbound HTTP connections fail immediately with REJECT.
  
  This restriction is geared towards a very extreme outbounder, so LIMIT can
  fairly generous. The default is $DEFAULT_LIMIT.
  
  This restriction persists on firewall restart, but this script alters the
  http-output chains directly rather than restart the firewall.

Usage: $0 -u <USER> -r

  Removes USER from this restriction.

Usage: $0 --json

  Display current limits from config and firewall.

Options:
    -u, --user=USER
    -l, --limit=LIMIT
    -r, --remove
    -h, --help
    --config-only       # only update the firewall config
    --json

USAGE
    die $msg, "\n" if defined $msg;
    exit 1;
}

sub throttle_config {
    my ($user, $limit) = @_;
    runonce();
    my $config_dir = My::Config::object->{config_dir};
    tie my @conf, 'Tie::File', "$config_dir/http-output-limits.conf"
        or die "failed to tie $config_dir/http-output-limits.conf : $!";
    for my $i (0..$#conf) {
        next unless $conf[$i] =~ /^\Q$user\E=(\d+)$/;
        my $old = $1;
        if ($old == $limit) {
            untie @conf;
            print "[*] config: $user already had limit of $limit\n";
            return;
        }
        $conf[$i] =~ s/=\d+$/=$limit/;
        untie @conf;
        print "[*] config: $user limit changed from $old -> $limit\n";
        return;
    }
    push @conf, "$user=$limit";
    untie @conf;
    print "[*] config: $user limit set to $limit\n";
}

sub remove_config {
    my ($user) = @_;
    runonce();
    my $config_dir = My::Config::object->{config_dir};
    tie my @conf, 'Tie::File', "$config_dir/http-output-limits.conf"
        or die "failed to tie $config_dir/http-output-limits.conf : $!";
    for my $i (0..$#conf) {
        next unless $conf[$i] =~ /^\Q$user\E=(\d+)$/;
        my $old = $1;
        splice @conf, $i, 1;
        untie @conf;
        print "[*] config: removed $user limit of $old\n";
        return;
    }
    untie @conf;
    print "[!] config: no limit found for $user\n";
}

sub existing_rules {
    my ($uid) = @_;
    my ($outrule, $limit) = (0, 0);
    runonce();
    open my $p, '-|', qw(/sbin/iptables -n -L http-output --line-numbers)
        or die "failed to read http-output chain : $!";
    while (defined(my $line = <$p>)) {
        next unless $line =~ /http-output-limits.*owner UID match \Q$uid\E /;
        $outrule = 1;
        last;
    }
    close $p;
    open $p, '-|', qw(/sbin/iptables -n -L http-output-limits --line-numbers)
        or die "failed to read http-output-limits chain : $!";
    while (defined(my $line = <$p>)) {
        next unless $line =~ /RETURN.*owner UID match \Q$uid\E .*burst (\d+)/;
        $limit = $1;
        last;
    }
    close $p;
    return ($outrule, $limit);
}

sub throttle_live {
    my ($user, $uid, $limit) = @_;
    runonce();
    my ($outrule, $oldlimit) = existing_rules($uid);

    if ($outrule && $oldlimit == $limit) {
        print "[*] firewall: $user already had limit of $limit\n";
        return;
    }

    # if $oldlimit is 0, then add the new rule
    # if $oldlimit is the same as $limit, then there's nothing to do
    # otherwise, remove the old rule and add the new rule
    #
    # we do this before touching http-output. With the opposite order, if we
    # die here, then the user is 100% blocked
    if ($oldlimit != $limit) {
        if ($oldlimit) {
            system qw(iptables -D http-output-limits -m owner --uid-owner), $uid,
                    qw(-m limit --limit 1/min --limit-burst), $oldlimit, qw(-j RETURN)
                and die "[!] failed to remove $user (uid: $uid) limit of $oldlimit from http-output-limits chain";
        }
        system qw(iptables -I http-output-limits -m owner --uid-owner), $uid,
                qw(-m limit --limit 1/min --limit-burst), $limit, qw(-j RETURN)
            and die "[!] failed to limit $user to $limit in http-output-limits chain";
    }

    # if new rules are added that even throttled outbounding should hit, then
    # then rulenum (3) needs to be updated
    unless ($outrule) {
        system qw(iptables -I http-output 3 -p tcp -m state --state NEW -m owner --uid-owner),
                $uid, qw(-m comment --comment), "$user limited",
                qw(-j http-output-limits)
            and die "[!] failed to limit $user in http-output chain";
    }
    if ($oldlimit && $oldlimit != $limit) {
        print "[*] firewall: $user limit changed from $oldlimit -> $limit\n";
    } else {
        print "[*] firewall: $user limit set to $limit\n";
    }
}

sub remove_live {
    my ($user, $uid) = @_;
    runonce();
    my ($outrule, $oldlimit) = existing_rules($uid);

    if (!$outrule && !$oldlimit) {
        print "[!] firewall: no limit found for $user\n";
        return;
    }

    # we now update http-output first. With the opposite order, if we die here,
    # then the user is 100% blocked
    if ($outrule) {
        system qw(iptables -D http-output -p tcp -m state --state NEW -m owner --uid-owner),
                $uid, qw(-m comment --comment), "$user limited",
                qw(-j http-output-limits)
            and die "[!] failed to remove $user (uid: $uid) rule from http-output chain";
    }
    if ($oldlimit) {
        system qw(iptables -D http-output-limits -m owner --uid-owner), $uid,
                qw(-m limit --limit 1/min --limit-burst), $oldlimit, qw(-j RETURN)
            and die "[!] failed to remove $user (uid: $uid) limit of $oldlimit from http-output-limits chain";
    }
    print "[*] firewall: removed $user limit of $oldlimit\n";
}

sub dump_config() {
    runonce();
    my %report = (
        config => {}, # user=limit
        # firewall can miss 'user' if rule only in http-output-limits
        # firewall can miss 'limit' if rule only in http-output
        firewall => {}, # uid => {user => string(), limit => int()}
    );

    my $config_dir = My::Config::object->{config_dir};
    open my $conf, '<', "$config_dir/http-output-limits.conf"; # errors OK
    while (defined(my $line = <$conf>)) {
        next unless $line =~ /^([^=]+)=(\d+)$/;
        $report{config}{$1} = $2;
    }
    close $conf;

    open my $p, '-|', qw(/sbin/iptables -n -L http-output --line-numbers)
        or die "failed to read http-output chain : $!";
    while (defined(my $line = <$p>)) {
        next unless $line =~ /http-output-limits.*owner UID match (\d+).* (\S+) limited/;
        $report{firewall}{$1}{user} = $2;
    }
    close $p;

    open $p, '-|', qw(/sbin/iptables -n -L http-output-limits --line-numbers)
        or die "failed to read http-output-limits chain : $!";
    while (defined(my $line = <$p>)) {
        next unless $line =~ /RETURN.*owner UID match (\d+) .*burst (\d+)/;
        $report{firewall}{$1}{limit} = $2;
    }
    close $p;
    if (-t STDOUT) {
        print to_json(\%report, {pretty => 1});
    } else {
        print encode_json(\%report), "\n";
    }
}

sub main() {
    my ($user, $remove, $help, $config_only, $json);
    my $limit = $DEFAULT_LIMIT;
    GetOptions (
        'user|u=s' => \$user,
        'limit|l=s' => \$limit,
        'remove|r' => \$remove,
        'help|h' => \$help,
        'config-only' => \$config_only,
        'json' => \$json,
    ) or help();
    help() if $help;
    if ($json) {
        help("Err: --json incompatible with other flags")
            if $user || $remove || $config_only;
        dump_config();
        exit;
    }
    help("Err: --user required") unless $user;
    my $uid = getpwnam($user);
    help("Err: Won't limit a system user") if (defined($uid) && $uid < 500) || $user =~ /^cpanel/;
    help("Err: User doesn't exist") unless $uid && -f "/var/cpanel/users/$user";
    help("Err: Bad limit") unless $limit =~ /^[1-9]\d*$/;
    openlog 'HTTPOutboundThrottle', '', 'LOG_USER';
    $config_only = $config_only ? ' (config only)' : '';
    if ($remove) {
        remove_config($user);
        remove_live($user, $uid) unless $config_only;
        syslog 'notice', "$user limit removed".$config_only;
    } else {
        throttle_config($user, $limit);
        throttle_live($user, $uid, $limit) unless $config_only;
        syslog 'notice', "$user limited to $limit".$config_only;
    }
    closelog;
}

main() unless caller;
