package Iodef::Pb::Simple::Plugin::Malware;
use base 'Iodef::Pb::Simple::Plugin';

use strict;
use warnings;

use MIME::Base64;
use Compress::Snappy;
use Digest::SHA qw(sha1_hex);
use Digest::MD5 qw(md5_hex);

sub process {
    my $self = shift;
    my $data = shift;
    my $iodef = shift;
       
    return unless($data->{'malware_md5'} || $data->{'malware_sha1'} || $data->{'Malware'});
    
    my $ad = [];
    
   if(my $f = $data->{'Malware'}){
        my $stream;
        if($f =~ /^(\/\S+|[a-zA-Z]+\/\S+)/){
            # we got a file
            # 1Meg.
            return ('file too large') unless((-s $f) < 1048576);
            open(F,$f) or return('unable to open '.$f.': '.$!);
            $f = <F>;
            close(F);
        }
        $data->{'malware_sha1'} = sha1_hex($f);
        $data->{'malware_md5'} = md5_hex($f);
        $f = encode_base64(Compress::Snappy::compress($f));
        push(@$ad,
            ExtensionType->new({
                meaning     => 'binary',
                formatid    => 'base64+snappy',
                content     => $f,
                dtype       => ExtensionType::DtypeType::dtype_type_string(),
            })
        );
    }
    if($data->{'malware_md5'}){
        push(@$ad, 
            ExtensionType->new({
                meaning     => 'malware hash',
                formatid    => 'md5',
                content     => $data->{'malware_md5'},
                dtype       => ExtensionType::DtypeType::dtype_type_string(),
            })
        );
    }
    
    if($data->{'malware_sha1'}){
        push(@$ad, 
            ExtensionType->new({
                meaning     => 'malware hash',
                formatid    => 'sha1',
                content     => $data->{'malware_sha1'},
                dtype       => ExtensionType::DtypeType::dtype_type_string(),
            })
        );
    }

    my $incident = @{$iodef->get_Incident()}[0];
    push(@{$incident->{'AdditionalData'}},@$ad);  

}

1;
