#!/usr/bin/python2
# Copyright (C) 2018 Trever L. Adams
# Donated to the Samba Foundation to use in testing Samba and related open source products as they see fit
import os
import time
import socket
import sys
import re

import functools
import itertools

# From https://stackoverflow.com/questions/32774910/clean-way-to-read-a-null-terminated-c-style-string-from-a-file#32775270
def readcstr(f):
    toeof = iter(functools.partial(f.recv, 1), '')
    return ''.join(itertools.takewhile('\0'.__ne__, toeof))

def check_eicar(name):
   f = open(name, 'r')
   data = f.read(68)
   string1 = b'X5O!P%@AP[4\PZX54(P^)7CC)7}'
   string2 = b'$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*'
   if data == string1 + string2:
       return True
   else:
       return False

def check_bad_dog(name):
   p = re.compile('.*bad.dog.*')
   m = p.match(name)
   if m:
       return True
   else:
       return False

filename = "/var/run/clamav/clamd.ctl"

if os.path.exists(filename):
    os.remove(filename)

try:
    server = socket.socket( socket.AF_UNIX, socket.SOCK_STREAM )
    server.bind(filename)
    server.listen(1)
except:
    print server

while True:
    # Wait for a connection
    connection, client_address = server.accept()
    try:
        while 1:
           data = readcstr(connection)

           if data.find("zSCAN ") >= 0:
               file_name = data[6:]
               if check_eicar(file_name):
#               if check_bad_dog(file_name):
                  connection.sendall(file_name + ": EICAR TEST VIRUS FOUND\x00")
                  connection.close()
               else:
                  connection.sendall(file_name + ": OK\x00")
                  connection.close()
           elif data.find("SHUTDOWN") >= 0:
               connection.close()
               server.close()
               os.remove(filename)
               sys.exit()
    except Exception as e:
	print e.message
        pass
    finally:
        connection.close()

server.close()
os.remove(filename)

