#!/usr/bin/perl -w
#################################################################
# emi.pl - Michael Karr
# Exim Message Info
# Gathers information about a specified Exim ID.
#
# Git: http://git.toolbox.hostgator.com/emi/emi
# Wiki: https://gatorwiki.hostgator.com/Security/EMI
# Wiki: https://gatorwiki.hostgator.com/Security/SpamReportsDashboard
# 
# Please submit all bug reports at http://bugs.hostgator.com
#
# (c) 2012 - HostGator.com, LLC.
#################################################################

BEGIN { # begin package EMI::Config
package EMI::Config;

use strict;
use warnings;

our $log_directory = '/var/log'; # Exim log directory
our $log_pattern = 'exim_mainlog((-\d{8})|(\.\d))?(\.gz)?'; # Exim log file name pattern

1;
} # end package EMI::Config


{ # start main package
package EMI;

use strict;
use warnings;

use FileHandle;
use File::stat;

sub main {
    print "emi.pl - Michael Karr\n\n"; 

    my %search_ids;

    while (my $arg = shift @ARGV) {
        if (($arg eq '-h') || ($arg eq '--help') || ($arg eq '-u') || ($arg eq '--usage') | ($arg eq '-?')) {
            usage();
            exit 0;
        } elsif (($arg eq '-f') || ($arg eq '--file')) {
            my $file = shift @ARGV;
            map {$search_ids{$_} = undef} @{read_file_list($file)};
        } else {
            if ($arg =~ /(\w{6}-\w{6}-\w{2})/) {
                $search_ids{$arg} = undef;
            }
        }

    }

    if (scalar keys %search_ids) {
        search_logs(%search_ids);        
    } else {
        print STDERR "It does not appear that you supplied me with a valid Exim ID or filename.\n";
        exit 1;
    }

    exit 0;
}

sub read_file_list {
    my ($file) = @_;
    if (open(my $fh, $file)) {
        my @ids = map {/(\w{6}-\w{6}-\w{2})/ ? $1 : ()} <$fh>;
        close($fh);
        return \@ids;
    } else {
        print STDERR "Failed to open file '$file': $!\n";
        return [];
    }
}

sub display_entry {
    my ($entry) = @_;
    print $entry->TO_TEXT;
}

sub usage {
    print "Usage:\n\n";
    print "emi.pl [options] <1st eximid> <2nd eximid> ... <nth eximid>\n\n";
    print "Options:\n\n";
    print "--usage\n-?\n\nDisplay this help message.\n\n";
    print "--file <filename>\n-f <filename>\n\nProcess list of eximids contained in a file.\n\n";
}

sub search_logs {
    my (%search_ids) = @_;

    print "Searching for ".scalar(keys %search_ids)." Exim IDs.\n\n";

    my $log_list = MK::Utility::LogList->new(
        directory => $EMI::Config::log_directory,
        pattern => $EMI::Config::log_pattern,
        chrono => 1,
    );

    my @logs = @{$log_list->get_list};
    my @found_ids;

    while (scalar(@logs) && scalar(keys %search_ids)) { # do we still have an ids to search for and logs to search for them in?
        my $log = shift @logs;
        print "Checking log: $log\n";

        my $found = process_log($log, \%search_ids);

        if (scalar(@{$found})) {
            print 'Found '.scalar(@{$found})." ID(s) in log file.\n";
        }

        push(@found_ids, @{$found});
    }

    print "\n";

    if (@found_ids) {
        print 'Found '.scalar(@found_ids)." IDs in total.\n";
    }

    if (scalar keys %search_ids) {
        print 'There were '.scalar(keys %search_ids)." IDs not found.\n";
    }

    print "\n";

    for my $found (@found_ids) {
        display_entry($found);
    }
}

sub process_log {
    my ($log, $search_ids_r) = @_;

    my ($fh, $fs, $gz, $br);

    if ($log =~ /^.*?\.gz$/) {
        $gz = 1;
        open($fh, "-|", "zcat " . $log) or die "Failed to open compressed file 'log'.";
        my $gziplist=`gzip -l $log`;
        
        if ($gziplist =~ /.\n\s*\d*\s*(\d*)/) {
            $fs=$1;
        } else {
            die "Failed to get gzip header for '$log'.";
        }
    } else {
        $gz = 0;
        $fh = FileHandle->new($log, '<') or die "Failed to open file '$log'.";
        $fs = stat($log)->size;
    }

    $br = 0;
    
    my ($p_val, $p_end, $p_per, $p_cnt) = (0, $fs, 0, 0);
    $|++;

    my (@found_ids, $exit_early);

    while (<$fh>) {
        $br += length($_);

        if (/(\w{6}-\w{6}-\w{2})\s<=/) {
            if (exists($search_ids_r->{"$1"})) {
                my $entry = EMI::LogEntry->new(entry => $_);
                push (@found_ids, $entry);

                delete($search_ids_r->{"$1"});

                unless(scalar(keys %{$search_ids_r})) { # don't bother checking rest of log if no more id's
                    print "\nNo more IDs to look for.\n";
                    $exit_early = 1;
                    last;
                }
            }
        }

        if ($p_cnt <= 0) {
            $p_val = $gz ? $br : tell($fh);
            my $per = int(($p_val / $p_end) * 100);
            if ($per != $p_per) {
                print "\r               \rProgress: $per%"; #replace prev line with new progress
                $p_per = $per;
            }
            $p_cnt = 1000;
        } else {
            $p_cnt--;
        }
    }

    unless($exit_early) {
        $p_val = $gz ? $br : tell($fh);
        my $per = int(($p_val / $p_end) * 100);
        print "\r               \rProgress: $per%\n"; #replace prev line with new progress
    }

    return \@found_ids;
}

__PACKAGE__->main unless caller; # call main function unless we were included as module

1;    
} # end main package


BEGIN { # begin package EMI::LogEntry
package EMI::LogEntry;

use strict;
use warnings;
use Carp;

use Time::Local;
use Date::Format;

my @time = localtime(time);
my $offset = timegm(@time) - timelocal(@time);

sub new {
    my ($class, %params) = @_;
    $params{entry} or croak "No file specified.";

    my $self = build_entry($params{entry});

    bless($self, $class);
    return $self;
}

sub build_entry {
    my ($entry) = @_;
    my $parsed = {entry => $entry};

    if ($entry =~ /<=/) { # is this an outbound email?
        $parsed->{direction} = 'outbound';

        if ($entry =~ /^(\d{4})\-(\d{2})\-(\d{2})\s(\d{2}):(\d{2}):(\d{2})\s(\[\d{1,8}\]\s)?(\w{6}\-\w{6}\-\w{2})\s<=\s/gc) { # grab time and id
            $parsed->{time} = timegm($6, $5, $4, $3, $2 - 1, $1) - $offset;      
            $parsed->{id} = $8;
            
            if ($entry =~ /\G((?:[^\s]*[\+@][^\s]*)|(?:<>))\s/gc) { # do we have a sender?
                $parsed->{sender} = $1;
                
                if ($entry =~ /\G(H=([^\s]*\s)?((\([^\(]*\)\s)?\[([^\]]*)\]))(:\d{1,5})?\s/gc) { # is this a remote user?
                    $parsed->{helo} = $1;
                    $parsed->{ip} = $5;
                    
                    if ($entry =~ /(A=(fixed|courier|dovecot)_(login|plain):(([^\+@\s]*)|([^\+@\s]*[\+@]([^\+@\s]*))))\s/) { # do we have a valid authenticator?
                        $parsed->{auth} = $1;
                    } 
                } elsif ($entry =~ /\G(U=([^\s]*))\s/gc) { # is this a local user?
                    $parsed->{auth} = $1;
                } elsif ($entry =~ /\GR=(\w{6}\-\w{6}\-\w{2})\s/gc) { # is this a returned mail?
                    $parsed->{bounce_id} = $1;
                }                   
            }
        }

        $entry =~ /^(?:.*(?:(?:from\s<[^>]*>)|(?:T=\".*?\"))\sfor\s)(.*)$/;
        my @emails = split(/\s/, $1);
        $parsed->{recipients} = \@emails;

        if ($entry =~ /(T=\"([^\"]*)\")/) {
            $parsed->{subject} = $1;
        } else {
            $parsed->{subject} = 'Blank Subject';
        }
    }

    return $parsed;
}

sub TO_TEXT {
    my $self = shift;
    return join ('', map {
        $self->{id}.': '.time2str("%a %b %e %T %Y", $self->{time}).' - '.$self->{sender}.' ('.($self->{auth} ? $self->{auth}: 'no auth').') -> '.$_."\n"
    } @{$self->{recipients}});
}

1;
} # end package EMI::LogEntry


BEGIN { ## begin class MK::Utility::LogList
package MK::Utility::LogList;

use strict;
use warnings;
use Carp;

use File::Spec;
use File::stat;

sub new {
    my ($class, %params) = @_;
    
    $params{directory} or croak "No directory specified.";
    $params{pattern} or croak "No pattern specified.";
    
    my $self = {
        directory => $params{directory},
        pattern => $params{pattern},
        chrono => exists ($params{chrono}) ? $params{chrono} : 1,
        files => [],
    };
    
    opendir(my $dh, $self->{directory}) or croak "Failed to open directory: $self->{directory}";
    
    while(my $file = readdir($dh)) {
        if ($file =~ /$self->{pattern}/) {
            push (@{$self->{files}}, File::Spec->rel2abs($file, $self->{directory}));
        }
    }
    
    closedir($dh);
    
    if ($self->{chrono}) {
        @{$self->{files}} = sort {stat($b)->mtime <=> stat($a)->mtime} @{$self->{files}};
    }
    
    bless($self, $class);
    return $self;
}

sub get_list {
    my $self = shift;
    return $self->{files};
}

1;
} ## end class MK::Utility::LogList