#!/usr/bin/perl

# This is a SpamAssassin module that kills mail from newly-born domains.


package infanticide;
use Mail::SpamAssassin::Plugin;
use Sys::Syslog;
use Sys::Syslog qw(:standard :macros);
#use Time::Local;
use HTTP::Date;

our @ISA = qw(Mail::SpamAssassin::Plugin);
my $counter = 100;
sub new {
	my ($class, $mailsa) = @_;

	# the usual perlobj boilerplate to create a subclass object
	$class = ref($class) || $class;
	my $self = $class->SUPER::new($mailsa);
	bless ($self, $class);
 
	# syslog is fun
	syslog('info', 'Initializing INFANTICIDE for SpamAssassin (c) 2022-2023 by Art Cancro');

	# Register evaluation rules
	$self->register_eval_rule ("check_for_disposable_domain");

	# and return the new plugin object
	return $self;
}


sub trim {
	my $s = shift; $s =~ s/^\s+|\s+$//g; return $s
}


sub infanticide_get_creation_date {
	my $domain_to_test = $_[0];
	my $cDate = "";

	open my $fh, "-|", "whois", $domain_to_test	or return("");
	my @lines = <$fh>				or return("");
	close $fh					or return("");
	foreach(@lines) {
		if (index($_, "Creation Date:") != -1) {
			my @arr = split("Creation Date:", $_);
			$cDate = trim($arr[1]);
			# 2017-06-02T13:15:42Z
		}
	}
	return($cDate);
}


sub check_for_disposable_domain() {
	$counter = $counter + 1;

	my ($self, $pms) = @_;
	my $fromaddr = $pms->get("From:addr", undef);
	my @fromarr = split('@', $fromaddr);
	my $domain = $fromarr[1];
	my $creationDate = infanticide_get_creation_date($domain);
	if ($creationDate eq "") {
		syslog('debug', "infanticide: " . $counter . " no creation date for " . $domain);
		return(0);
	}
	my $dt = str2time($creationDate);
	my $daysAgo = (time() - $dt) / 86400;
	syslog("debug", "infanticide: " . $domain . " was created " . $daysAgo . " days ago");
	if ($daysAgo < 30) {
		return(1);
	}
	return(0);
}
