'''
qsf module, version 0.1

(c) 2003 Jan ONDREJ (SAL) <ondrejj(at)salstar.sk>
                                                                                
 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

'''

from avlib import *
import re

__all__=['qsf']

class qsf(ascanner):
  '''
  Quick Spam Filter scanner.

  This scanner scans for spams. If a spam is returned, a string
  SPAM is returned as virus name. It uses Quick Spam Filter.
  
  Usage: qsf(['/usr/bin/qsf','-r'],SPAMSTRING='',MAX_FILE_SIZE=500000)
  
  Where: in [] is a path and argumets of qsf binary
         SPAMSTRING is a string, which define a report string,
           which is checked. If it is found, mail is assigned as 'SPAM'
         MAX_FILE_SIZE is a number, which defines maximum file size,
           which can be tested. If a mail (with header) is larger,
           it is not checked (by default 500000).
  '''
  is_spamscan=1
  name='qsf()'
  def __init__(self,arg,spamstring='',max_file_size=500000):
      self.arg=arg
      self.SPAMSTRING=spamstring
      self.MAX_FILE_SIZE=max_file_size
  def scanbuffer(self,buffer,args={}):
      exitstatus=''
      if len(buffer)>self.MAX_FILE_SIZE:
        return 0.0,'',['File too long to test it. Size: '+str(len(buffer))]
      pf=popen(self.arg)
      pf.write(buffer)
      pf.tocmd.close()
      detected=''
      ret=[]
      level=0.0
      for line in pf.readlines():
        if line.rstrip=="":
          break
        reg1=re.search("^X-Spam: YES$",line,re.IGNORECASE)
        if reg1:
          detected='SPAM'
          mail.addheader(line)
          ret.append(line)
        else:
          reg2=re.search("^X-Spam-Rating: (.*)$",line)
          if reg2:
            if detected:
              detected+=":"+reg2.group(1)
            level=float(reg2.group(1))
            mail.addheader(line)
            ret.append(line)
      pf.wait()
      debug.echo(4,"qsf: ",ret)
      return level,detected,ret
