spamassassin_utils.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. """Inspired from
  2. https://github.com/petermat/spamassassin_client
  3. """
  4. import socket, select, re, logging
  5. from io import BytesIO
  6. divider_pattern = re.compile(br"^(.*?)\r?\n(.*?)\r?\n\r?\n", re.DOTALL)
  7. first_line_pattern = re.compile(br"^SPAMD/[^ ]+ 0 EX_OK$")
  8. class SpamAssassin(object):
  9. def __init__(self, message, timeout=20, host="127.0.0.1"):
  10. self.score = None
  11. self.symbols = None
  12. # Connecting
  13. client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  14. client.settimeout(timeout)
  15. client.connect((host, 783))
  16. # Sending
  17. client.sendall(self._build_message(message))
  18. client.shutdown(socket.SHUT_WR)
  19. # Reading
  20. resfp = BytesIO()
  21. while True:
  22. ready = select.select([client], [], [], timeout)
  23. if ready[0] is None:
  24. # Kill with Timeout!
  25. logging.info("[SpamAssassin] - Timeout ({0}s)!".format(str(timeout)))
  26. break
  27. data = client.recv(4096)
  28. if data == b"":
  29. break
  30. resfp.write(data)
  31. # Closing
  32. client.close()
  33. client = None
  34. self._parse_response(resfp.getvalue())
  35. def _build_message(self, message):
  36. reqfp = BytesIO()
  37. data_len = str(len(message)).encode()
  38. reqfp.write(b"REPORT SPAMC/1.2\r\n")
  39. reqfp.write(b"Content-Length: " + data_len + b"\r\n")
  40. reqfp.write(b"User: cx42\r\n\r\n")
  41. reqfp.write(message)
  42. return reqfp.getvalue()
  43. def _parse_response(self, response):
  44. if response == b"":
  45. logging.info("[SPAM ASSASSIN] Empty response")
  46. return None
  47. match = divider_pattern.match(response)
  48. if not match:
  49. logging.error("[SPAM ASSASSIN] Response error:")
  50. logging.error(response)
  51. return None
  52. first_line = match.group(1)
  53. headers = match.group(2)
  54. body = response[match.end(0) :]
  55. # Checking response is good
  56. match = first_line_pattern.match(first_line)
  57. if not match:
  58. logging.error("[SPAM ASSASSIN] invalid response:")
  59. logging.error(first_line)
  60. return None
  61. report_list = [s.strip() for s in body.decode("utf-8").strip().split("\n")]
  62. linebreak_num = report_list.index([s for s in report_list if "---" in s][0])
  63. tablelists = [s for s in report_list[linebreak_num + 1 :]]
  64. self.report_fulltext = "\n".join(report_list)
  65. # join line when current one is only wrap of previous
  66. tablelists_temp = []
  67. if tablelists:
  68. for counter, tablelist in enumerate(tablelists):
  69. if len(tablelist) > 1:
  70. if (tablelist[0].isnumeric() or tablelist[0] == "-") and (
  71. tablelist[1].isnumeric() or tablelist[1] == "."
  72. ):
  73. tablelists_temp.append(tablelist)
  74. else:
  75. if tablelists_temp:
  76. tablelists_temp[-1] += " " + tablelist
  77. tablelists = tablelists_temp
  78. # create final json
  79. self.report_json = dict()
  80. for tablelist in tablelists:
  81. wordlist = re.split("\s+", tablelist)
  82. self.report_json[wordlist[1]] = {
  83. "partscore": float(wordlist[0]),
  84. "description": " ".join(wordlist[1:]),
  85. }
  86. headers = (
  87. headers.decode("utf-8")
  88. .replace(" ", "")
  89. .replace(":", ";")
  90. .replace("/", ";")
  91. .split(";")
  92. )
  93. self.score = float(headers[2])
  94. def get_report_json(self):
  95. return self.report_json
  96. def get_score(self):
  97. return self.score
  98. def is_spam(self, level=5):
  99. return self.score is None or self.score > level
  100. def get_fulltext(self):
  101. return self.report_fulltext