#!/usr/bin/perl -w
# /*---------------------------------------------------------------------------
#  * Copyright (C) 2008-2012 Igor Daniloff
#  *
#  * Following source code is the property of Doctor Web, Ltd.
#  * Use is subject to license terms.
#  * The reproduction in any form without written permission of
#  * Doctor Web, Ltd. and proper attribution is strongly prohibited.
#  ----------------------------------------------------------------------------*/

# interface:

# return: OK "filename" "new_filename" YYYY-MM-DD HH:MM:SS [remove] or ERROR text
# and envelope save to new_filename.envelope if $ProcessMail = 1
# remove - if need remove new created temp files
# at end return ""

use strict;
use Getopt::Long;
use IO::Handle qw();
use Fcntl qw(:DEFAULT :flock);
use Errno qw(EAGAIN);
use POSIX ":sys_wait_h";
use Sys::Syslog;
use DBI;
use File::Temp;

my $QUIET =0;
my $ERR = 1;
my $WARN = 2;
my $INFO = 3;
my $DEBUG = 4;
my $ALL = 5;

my %log_levels=('QUIET' => $QUIET,
                'ERR' =>   $ERR,
                'WARN'  => $WARN,
                'INFO'  => $INFO,
                'DEBUG' => $DEBUG,
                'ALL'   => $ALL
);

my $help = 0;
my $StoredTime = 24*60*60; #24h
my $DBISettings = undef;
my $DBIUsername = undef;
my $DBIPassword = undef;
my $SQLInsertCommand = "";
my $SQLRemoveCommand = "";
my $SQLSelectCommand = "";
my $BaseDir;
my $QuarantineDir;
my $SyslogFacility = 'Mail';
my $Level = 'INFO';
my $LogFileName = '';
my $MDClient='.*';#regex with top list directory name

my $dbh;
my $insert_stm;
my $remove_stm;
my $select_stm;
my $curr_log_level=$log_levels{$Level};

######################################################################
sub DwLog{
    return if $curr_log_level == $QUIET;
    my $level = uc(shift @_);
    my $num = $log_levels{$level};
    die "Unknown log level: $level" unless $num;
    return if $curr_log_level<$num;

    if(length($LogFileName)>0){
        printf LOG_FILE scalar(localtime)." drweb-qp ".
            ($level eq 'ERR'?"ERROR":"$level")." @_\n";
    }else{
        syslog($level, ($level eq 'ERR'?'ERROR':$level)." @_");
    }
}


#######################################################################
sub DwDie
{
    my $message = shift;

    DwLog('ERR', $message);
    die $message;
}


######################################################################
sub InitDBI()
{
    eval {
        $dbh=DBI->connect($DBISettings,
                          $DBIUsername,
                          $DBIPassword,
                          { AutoCommit => 1})
    };
    DwDie "connect to DB $DBISettings: $@" if $@;
    DwDie "connect to DB $DBISettings: " . DBI::errstr() unless $dbh;

    if(length $SQLSelectCommand){
        $select_stm = $dbh->prepare($SQLSelectCommand) or DwDie $dbh->errstr;
    }
    if(length $SQLInsertCommand){
        $insert_stm = $dbh->prepare($SQLInsertCommand) or DwDie $dbh->errstr;
    }
    if(length $SQLRemoveCommand){
        $remove_stm = $dbh->prepare($SQLRemoveCommand) or DwDie $dbh->errstr;
    }
}
######################################################################
sub DwReadPascalString
{
    my ($file) = @_;
    my $num;
    if(read($file,$num,4)!=4){
        DwLog('err',"Can`t read 4 bytes for string length: $!");
        return undef;
    }
    $num = unpack("N",$num);
    my $data;
    if(read($file,$data,$num)!=$num){
        DwLog('err',"Can`t read $num bytes: $!");
        return undef
    }
    return $data;
}
######################################################################
sub DwWritePascalString
{
    my ($file,$data) = @_;
    print $file pack("N/a*",$data);
}
######################################################################
sub DwLoadEnvelope
{
    my ($filename,$from,$to) = @_;
    unless (open(DRWEBFILE,"$filename") ){
        DwLog('err',"can`t open file $filename: $!\n");
        close DRWEBFILE;
        return undef;
    }
    $$from = DwReadPascalString(\*DRWEBFILE);
    unless ($$from){
        close DRWEBFILE;
        return undef;
    }
    my $rcpts_num;
    if(read(DRWEBFILE,$rcpts_num,4)!=4){
        DwLog('err',"Can`t read number of rcpts in envelope file: $!");
        close DRWEBFILE;
        return undef;
    }
    $rcpts_num = unpack("N",$rcpts_num);

    $$to = "";

    while($rcpts_num--){
        my $rcpt = DwReadPascalString(\*DRWEBFILE);
        unless($rcpt){
            close DRWEBFILE;
            return undef;
        }
        $$to.="$rcpt";
        $$to.="," if $rcpts_num;
    }
    close DRWEBFILE;
    return 1;
}
######################################################################
sub DwSaveEnvelope
{
    my ($filename,$from,$to) = @_;
    unless (open(DRWEBFILE,">$filename") ){
        DwLog('err',"can`t open file $filename for writing: $!\n");
        return undef;
    }
    unless(DwWritePascalString(\*DRWEBFILE,$from)){
        unlink("$filename");
        close DRWEBFILE;
        return undef;
    }
    my @rcpts = split ',', $to;
    my $rcpts_num = pack("N",scalar(@rcpts));
    unless(print DRWEBFILE $rcpts_num){
        DwLog('err',"Can`t write number of rcpts in envelope file: $!");
        unlink("$filename");
        close DRWEBFILE;
        return undef;
    }
    foreach my $rcpt(@rcpts){
        unless(DwWritePascalString(\*DRWEBFILE,$rcpt)){
            unlink("$filename");
            close DRWEBFILE;
            return undef;
        }
    }
    close DRWEBFILE;
    return 1;
}
######################################################################
sub DwGetSQLTime
{
    my ($curr) = @_;
    $curr = time() unless $curr;
    my ($sec,$min,$hour,$mday,$mon,$year) = localtime($curr);
    $year+=1900;
    $mon+=1;

    ($sec,$min,$hour,$mday,$mon) =
        map {$_ < 10 ? "0$_" : $_} $sec,$min,$hour,$mday,$mon;

#'YYYY-MM-DD HH:MM:SS'
    return "$year-$mon-$mday $hour:$min:$sec";
}
######################################################################
sub DwLoadFile
{
    my $name = shift @_;
    unless (open(DRWEBFILE,"$name")) {
        DwLog('err',"can`t open file $name: $!\n");
        return undef;
    }
    local $/;
    undef $/;
    my $file = <DRWEBFILE>;
    close DRWEBFILE;
    return $file;
}
######################################################################
sub Remove
{
    my $file = shift @_;
    unless(unlink($file)){
        DwLog('err',"Error in unlink file $file: $!");
        return undef;
    }
    unless(unlink("$file.envelope")){
        DwLog('err',"Error in unlink file $file.envelope: $!");
        return undef;
    }
    DwLog('debug',"Success unlink $file and $file.envelope");
    return 1;
}
######################################################################
sub IsLikeType
{
    my $string = shift @_;
    return $string =~ /[%_]/;
}
######################################################################
sub TranslateToRegex
{
    my $string = shift @_;
    $string =~ s/([\\\|\)\(\{\^\*\=\?\.\$\[])/\\$1/g;
    $string =~ s/%/\.\*/g;
    $string =~ s/_/\./g;
    return $string;
}
######################################################################
sub print_help()
{
    printf "Dr.Web (R) Quarantine Processing Tool\n";
    exit(0);
}


######################################################################
sub ForEachFile
{
    my ($func,$process_dir_name) =@_;

    my $DIR;
    unless(opendir($DIR,$process_dir_name)){
        DwLog('err', "error in open dir $process_dir_name: $!");
        return;
    }

    my @allfiles = grep {$_ ne '.' and $_ ne '..' } readdir $DIR;
    DwLog('debug', "ForEachFile ($process_dir_name): found = ".scalar(@allfiles));
    foreach my $file(@allfiles){
        $file = "$process_dir_name/$file";
        if(-f $file && $file !~ /\.envelope$/ ){
            $func->($file);
        }elsif(-d $file){
            ForEachFile($func,$file);
        }
    }

    unless(closedir($DIR)) {
        DwLog('err', "error in close dir $process_dir_name: $!");
        return undef;
    }

    return 1;
}
######################################################################
# select:
#  0 - mag-number
#  1 - put time
#  2 - body
#  3 - from
#  4 - to
#  5 - filename
sub DwLoadFromDBI
{
    my ($file) = @_;
    if(!$select_stm->execute($file)){
        print "ERROR Error in select $file from $DBISettings: ".$dbh->errstr."\n";
        return undef;
    }
    my $found = 0;
    while( my $record = $select_stm->fetchrow_hashref ) {
        my $log_str = sprintf("Success fetch mail %08X; put_time=%s; filename=%s",
                              $record->{id}, $record->{put_time}, $record->{filename});
        $log_str.=sprintf("; sender=%s; rcpts=%s", $record->{sender}, $record->{rcpts});
        DwLog('info',$log_str );
        eval{
            DwDie "Can`t find filename from request $SQLSelectCommand" unless $record->{filename};
            my ($leaf) = $record->{filename} =~ /\/([^\/]+)$/;
            $leaf = "?" unless $leaf;
            my ($fh, $filename) = File::Temp::tempfile( ".dbi_${leaf}_XXXXXX", DIR => $BaseDir);
            if(!defined($fh) || !($filename)){
                print "ERROR can`t create tempfile for new mail from $DBISettings\n";
                $select_stm->finish;
                return undef;
            }
            unless(DwSaveEnvelope("$filename.envelope",$record->{sender},$record->{rcpts})){
                print "ERROR can`t save envelope to $filename.envelope: $!\n";
                unlink $filename;
                $select_stm->finish;
                return undef;
            }
            if(!(print $fh $record->{body}) || !(close $fh)){
                print "ERROR can`t save body to $filename with length ".length($record->{body}).
                    ": $!\n";
                unlink $filename;
                unlink "$filename.envelope";
                $select_stm->finish;
                return undef
            }
            print "OK \"".$record->{filename}."\" \"$filename\" ".$record->{put_time}." remove\n";
            $found = 1;
        };
        if($@){
            print "ERROR in create e-mail files: $@\n";
            $select_stm->finish;
            return undef;
        }
    }

    if(!$found && !IsLikeType($file)){#no escaping
        print "ERROR can`t find object $file in DBI $DBISettings\n";
        return undef;
    }
    return 1;
}
######################################################################
sub ForEachClientDir
{
    my ($func,$is_template_filename) = @_;

    unless(opendir(Q_DIR,$QuarantineDir)){
        DwDie "error in open dir $QuarantineDir: $!";
    }
    my @all_top_dirs = grep { $_ ne '.'
                                  and $_ ne '..'
                                  and ($is_template_filename || $_ =~ /$MDClient/)
                                  and -d "$QuarantineDir/$_" } readdir Q_DIR;
    closedir(Q_DIR);

    $func->(\@all_top_dirs);
}
######################################################################
sub DwProcessObjectFromFile
{
    my ($file,$output,$action_on_found,$action_on_fail) = @_;

    my $regex_filename;

    my $proc_file = sub{
        my ($absolute_file,$output) = @_;

        my $relative_file = substr($absolute_file,length($QuarantineDir)+1);

        return undef if $regex_filename and $relative_file !~ /$regex_filename/;

        if(-f $absolute_file && ( -f "$absolute_file.envelope" ) ){
            return $action_on_found->($relative_file,$absolute_file);
        }else{
            return $action_on_fail->($relative_file,$absolute_file,$output);
        }
    };

    my $proc_dir = sub{
        my $dirs  = shift @_;

        foreach my $process_dir_name (@$dirs){
            ForEachFile($proc_file,"$QuarantineDir/$process_dir_name");
        }
    };

    if(IsLikeType($file)){
        $regex_filename =  TranslateToRegex($file);
        ForEachClientDir($proc_dir,$file);
        return undef;
    }else{
        return $proc_file->("$QuarantineDir/$file",$output);
    }
}
######################################################################
sub DwGetObject
{
    my ($file) = @_;
    DwLog('debug',"Call get for $file ...");

    my $action_on_found = sub{
        my ($relative_file,$absolute_file) = @_;
        printf "OK \"".$relative_file."\" \"$absolute_file\" ".
            DwGetSQLTime((stat($absolute_file))[9])."\n";
        return 1;
    };

    my $action_on_fail = sub{
        my ($relative_file,$absolute_file,$output) = @_;
        printf "ERROR can`t find absolute_files $absolute_file or $absolute_file.envelope\n"
            if $output;
        return undef;
    };

    #все еще на диске
    return 1 if DwProcessObjectFromFile($file,0,$action_on_found,$action_on_fail);

    #уже успели переместить в DBI
    InitDBI();
    DwDie 'You must specify SQLSelectCommand options' unless($select_stm);
    DwLoadFromDBI($file);#лок внешний
}
######################################################################
sub ProcessFileAtPuls
{
    my ($file) = @_;

    return unless -f "$file.envelope";

    #ok - загружаем это письмо в DBI
    my $number = -1;
    my ($leaf) = $file =~ /\/([^\/]+)$/;
    if($leaf =~ /^([0-9a-fA-F]+)./){
        $number = hex($1);
    }

    my ($from,$to)=("","");
    unless(DwLoadEnvelope("$file.envelope",\$from,\$to)){
        DwLog('err',"Error in loading envelope from $file.envelope: $!");
        return;
    }
    DwLog('debug',"load envelope from $file.envelope: from=$from; to=$to for inserting");

    my $body = DwLoadFile($file);
    return unless $body;

    unless($insert_stm->execute($number,
                                ($file=~/^$QuarantineDir/ ?
                                 substr($file,length($QuarantineDir)+1) :
                                 $file),
                                DwGetSQLTime((stat($file))[9]),
                                $from,
                                $to,
                                $body)){
        DwLog('err',"Error in moving $file to $DBISettings: ".$dbh->errstr);
        return;
    }

    Remove($file);
}
######################################################################
sub DwProcessPulsWithLock
{
    my $dirs  = shift @_;

    InitDBI();
    DwDie 'You must specify SQLInsertCommand options' unless $insert_stm;

    foreach my $process_dir_name (@$dirs){
        #блокировка
        my $LockFileName = "$QuarantineDir/$process_dir_name/.drweb-qp.lock";
        sysopen(FH, $LockFileName, O_RDWR | O_CREAT)
            or DwDie "can`t open file $LockFileName: $!";
        my $num_try = 0;
      NEXT_TRY:
        unless(flock( FH, LOCK_EX | LOCK_NB )){
            if(++$num_try<=3){
                sleep 1;
                goto NEXT_TRY;
            }
            close(FH);
            DwLog('debug',"Skip checking: file $LockFileName already locked: $!");
            exit(1);
        }
        DwLog('debug',"Success lock $LockFileName");

        #удаляем старые либо перемещаем в DBI
        ForEachFile(\&ProcessFileAtPuls,"$QuarantineDir/$process_dir_name");

        # удалим устаревшие из БД
        if(  $StoredTime>0 && length $SQLRemoveCommand ){
            my $time = DwGetSQLTime(time()-$StoredTime);
            my $res = $remove_stm->execute($time);
            unless($res){
            DwLog('err',"Error in removing old objects from $DBISettings: ".$dbh->errstr);
            }else{
                DwLog('info',"Call remove for date '$time': remove $res records");
            }
        }

        #разблокировка
        close(FH)
            or DwDie "can`t close file $LockFileName: $!";
        DwLog('debug',"Success unlock $LockFileName");
    }
}
######################################################################
sub RemoveFromDBIByFilename
{
    my ($file) = @_;

    my $res = $remove_stm->execute($file);
    if($res && (IsLikeType($file) || $res ne '0E0')){
        DwLog('debug',"Call remove for '$file': remove $res records");
    }else{
        my $str = ($res && ($res eq '0E0')) ? 'no record' : $dbh->errstr;
        DwDie "remove error for $file from $DBISettings: ".$str.".";
    }
}
######################################################################
sub RemoveByFilename
{
    my ($file) = @_;
    DwLog('debug',"Call remove for $file ...");

    my $action_on_found = sub{
        my ($relative_file,$absolute_file) = @_;
        Remove("$absolute_file") or DwDie "Error in remove $absolute_file object";
        return 1;
    };

    my $action_on_fail = sub{
        my ($relative_file,$absolute_file,$output) = @_;
        DwLog('err',"Error in remove $absolute_file file") if $output;
        return undef;
    };

    #все еще на диске
    return 1 if DwProcessObjectFromFile($file,0,$action_on_found,$action_on_fail);

    #уже успели переместить в DBI
    InitDBI();
    DwDie 'You must specify SQLRemoveCommand options' unless($remove_stm);
    RemoveFromDBIByFilename($file);#лок внешний
}

#start
######################################################################
my $check_filename; # относительное имя файла, запрашиваемого из хранилища
my $remove_filename; # имя файла для удаления

my @COPY = @ARGV;

GetOptions(
    'help|?' => \$help,
    'StoredTime=i' => \$StoredTime,
    'DBISettings=s' => \$DBISettings,
    'DBIUsername=s' => \$DBIUsername,
    'DBIPassword:s' => \$DBIPassword,
    'SQLInsertCommand=s' => \$SQLInsertCommand,
    'SQLRemoveCommand=s' => \$SQLRemoveCommand,
    'SQLSelectCommand=s' => \$SQLSelectCommand,
    'BaseDir=s' => \$BaseDir,
    'Level=s' => \$Level,
    'SyslogFacility=s' => \$SyslogFacility,
    'LogFileName=s' => \$LogFileName,
    'MDClient=s' => \$MDClient,

    'f=s' => \$check_filename,
    'r=s' => \$remove_filename
)
    or die "Wrong input options!";

print_help() if $help || !$BaseDir; #для блокировки запуска без параметров

$QuarantineDir = "$BaseDir/infected";
$Level = 'WARN' if lc($Level) eq 'alert';
$Level = 'ERR' if lc($Level) eq 'error';
$Level = uc($Level);
$curr_log_level = $log_levels{$Level};

#инициализируем лог
if(length($LogFileName)>0){
    unless(open(LOG_FILE,">> $LogFileName")){
        exit 78;
    }
    LOG_FILE->autoflush();
}else{
    unless(openlog('drweb-qp', "ndelay,pid", $SyslogFacility)){
        exit 77;
    }
}

#производим обработку
if( $check_filename ){
    DwGetObject($check_filename);
    printf "\n";#конец передачи
}elsif( $remove_filename ){
    RemoveByFilename($remove_filename);
}elsif( $StoredTime != 0 ){#без этих настроек вообще работать нет смысла
    ForEachClientDir(\&DwProcessPulsWithLock);#делаем лок
}

#закрываем соединение с БД
if($dbh){
    $dbh->disconnect or DwDie $dbh->errstr;
}

#закрываем дескриптор лога
if(length($LogFileName)>0){
    close LOG_FILE;
}else{
    closelog;
}
