#!/usr/bin/perl
#
# KLMS integration script for IMS
# Copyright (C) Kaspersky Lab 2003-2012
#

use strict;
$| = 1;

BEGIN {
    unshift @INC, "/opt/kaspersky/klms/lib/perl";
}

use KL::Utils qw(execute);
use IO::Socket;
use File::Temp qw(tempdir);
use Sys::Syslog qw(:standard :macros);

use constant LMS_SERVER_SOCKET => '/var/run/klms/rds_av';
use constant SCAN_TIMEOUT => 600;
use constant IMSMSGED => '/usr/local/bin/imsmsged';
use constant SKIP_ON_ERROR => 1;
use constant TMPDIR => '/tmp/klms_filter';

sub get_section_types
{
	my $msg_file = shift;
	my ($ret, $sect_info) = KL::Utils::execute(IMSMSGED, 'list', '--sect-info', $msg_file);
	if ($ret != 0)
	{
		syslog(LOG_WARNING, "imsmsged error: $sect_info");
		return ();
	}
	$sect_info =~ s/^\s+//;	
	return split(/\s+/, $sect_info);
}

sub export_message
{
	my ($msg_file, $out_dir) = @_;
	my @sections = get_section_types($msg_file);
	for my $i(0 .. $#sections)
	{
		my $out_file = "$out_dir/file_$i";
		my ($ret, $err_msg) = KL::Utils::execute(IMSMSGED, 'export', '--sect-file='.($i + 1), $msg_file, $out_file);
		if ($ret != 0)
		{
			syslog(LOG_WARNING, "imsmsged error: $err_msg");
			next;
		}
		print "i=$i, type=$sections[$i]\n";
		if($sections[$i] eq '')
		{
			my $msg_subdir = "$out_dir/message_$i";
			mkdir $msg_subdir;
			export_message($out_file, $msg_subdir);
			unlink $out_file;
		}
	}
}

sub check_directory
{
    my $dir_path = shift;
    my $sock = new IO::Socket::UNIX(Peer => LMS_SERVER_SOCKET, Type => SOCK_STREAM);
    die "Could not create socket: $!\n" unless $sock;
    my $found = 0;
    print $sock "nSCAN $dir_path\n";
    while(<$sock>)
    {
		syslog(LOG_DEBUG, "recv: $_");
        $found = 1 if($_ =~ /FOUND$/);
    }
    close($sock);
    return $found;
}

openlog("klms", "ndelay,pid", "mail");
my $dir = File::Temp::tempdir(TMPDIR.'/XXXXXX', CLEANUP => 1);
if (!defined($dir))
{
	syslog(LOG_WARNING, "failed to create temp dir: $!");
	exit(SKIP_ON_ERROR ? 0 : 1);
}
chmod 0750, $dir;
my $msg_file = shift;
export_message($msg_file, $dir);

my $malware_found = eval {
    local $SIG{ALRM} = sub { die "Timed Out" };
    alarm SCAN_TIMEOUT;
    my $ret = check_directory($dir);
    alarm 0;
    return $ret;
};
if (!defined($malware_found))
{
    syslog(LOG_WARNING, "message scan failed: $@");
    exit(SKIP_ON_ERROR ? 0 : 1);
} elsif ($malware_found) {
    syslog(LOG_WARNING, "threat detected");
    exit(1);
} else {
    syslog(LOG_DEBUG, "message clean");
    exit(0);
}

