#   Copyright 2014-2018 PUNCH Cyber Analytics Group
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

"""
Overview
========

Identify file types from their TrID signature

"""

import os
import tempfile
from pathlib import Path
from subprocess import Popen, PIPE
from collections import defaultdict
from configparser import ConfigParser
from inspect import currentframe, getframeinfo
from typing import DefaultDict, Dict, Optional

from stoq.plugins import WorkerPlugin
from stoq.exceptions import StoqPluginException
from stoq import Payload, RequestMeta, WorkerResponse


class TridPlugin(WorkerPlugin):
    def __init__(self, config: ConfigParser, plugin_opts: Optional[Dict]) -> None:
        super().__init__(config, plugin_opts)

        self.trid_defs = 'triddefs.trd'
        self.bin_path = 'trid'
        filename = getframeinfo(currentframe()).filename
        parent = Path(filename).resolve().parent

        if plugin_opts and 'trid_defs' in plugin_opts:
            self.trid_defs = plugin_opts['trid_defs']
        elif config.has_option('options', 'trid_defs'):
            self.trid_defs = config.get('options', 'trid_defs')
        if not os.path.isabs(self.trid_defs) and self.trid_defs:
            self.trid_defs = os.path.join(parent, self.trid_defs)
        if not self.trid_defs or not os.path.isfile(self.trid_defs):
            raise StoqPluginException(
                f'TrID definitions do not exist at {self.trid_defs}'
            )

        if plugin_opts and 'bin_path' in plugin_opts:
            self.bin_path = plugin_opts['bin_path']
        elif config.has_option('options', 'bin_path'):
            self.bin_path = config.get('options', 'bin_path')

    def scan(self, payload: Payload, request_meta: RequestMeta) -> WorkerResponse:
        """
        Scan a payload using TRiD

        """
        results: DefaultDict = defaultdict(list)

        with tempfile.NamedTemporaryFile() as temp_file:
            temp_file.write(payload.content)
            temp_file.flush()
            p = Popen(
                [self.bin_path, f"-d:{self.trid_defs}", temp_file.name],
                stdout=PIPE,
                stderr=PIPE,
                env={'LC_ALL': 'C'},
                universal_newlines=True,
            )
            trid_results, err = p.communicate()
            errors = [err] if err else None

        unknown_ext = 0
        for line in trid_results.splitlines()[6:]:
            if line.startswith('Warning'):
                break
            line = line.split()
            if line:
                try:
                    ext = line[1].strip('(.)')
                    if not ext:
                        ext = f'UNK{unknown_ext}'
                        unknown_ext += 1
                    results[ext].append({'likely': line[0], 'type': ' '.join(line[2:])})
                except IndexError:
                    continue

        return WorkerResponse(results, errors=errors)

@@ -695,16 +695,26 @@
 port os%0A
+import re%0A
 import t
@@ -939,16 +939,22 @@
 t, Dict,
+ List,
  Optiona
@@ -2404,16 +2404,47 @@
 ct(list)
+%0A        errors: List%5Bstr%5D = %5B%5D
 %0A%0A      
@@ -2879,204 +2879,313 @@
     
-errors = %5Berr%5D if err else None%0A%0A        unknown_ext = 0%0A        for line in trid_results.splitlines()%5B6:%5D:%0A            if line.startswith('Warning'):%0A                break%0A            line = line
+if err:%0A                errors.append(err)%0A%0A        unknown_ext = 0%0A        matches = re.findall(r'%5E %5B0-9%5D.*%25.*$', trid_results, re.M)%0A        warnings = re.findall(r'%5EWarning: (.*$)', trid_results, re.M)%0A        errors.extend(%5Bw for w in warnings%5D)%0A        for match in matches:%0A            match = match
 .spl
@@ -3204,20 +3204,21 @@
      if 
-line
+match
 :%0A      
@@ -3258,20 +3258,21 @@
   ext = 
-line
+match
 %5B1%5D.stri
@@ -3443,16 +3443,41 @@
 .append(
+%0A                        
 %7B'likely
@@ -3479,20 +3479,21 @@
 ikely': 
-line
+match
 %5B0%5D, 'ty
@@ -3510,18 +3510,40 @@
 oin(
-line
+match
 %5B2:%5D)%7D
+%0A                    
 )%0A  
@@ -3604,17 +3604,16 @@
 ontinue%0A
-%0A
         

Handle output from trid better with regexes(#58)