You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
2.0 KiB

  1. import asyncore
  2. import email
  3. import re
  4. from smtpd import SMTPServer
  5. from django.core.management.base import BaseCommand
  6. from hc.api.models import Check
  7. RE_UUID = re.compile("^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[8|9|aA|bB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$")
  8. class Listener(SMTPServer):
  9. def __init__(self, localaddr, stdout):
  10. self.stdout = stdout
  11. super(Listener, self).__init__(localaddr, None)
  12. def process_message(self, peer, mailfrom, rcpttos, data, mail_options=None, rcpt_options=None):
  13. to_parts = rcpttos[0].split("@")
  14. code = to_parts[0]
  15. try:
  16. data = data.decode()
  17. except UnicodeError:
  18. data = "[binary data]"
  19. if not RE_UUID.match(code):
  20. self.stdout.write("Not an UUID: %s" % code)
  21. return
  22. try:
  23. check = Check.objects.get(code=code)
  24. except Check.DoesNotExist:
  25. self.stdout.write("Check not found: %s" % code)
  26. return
  27. action = "success"
  28. if check.subject:
  29. parsed = email.message_from_string(data)
  30. received_subject = parsed.get("subject", "")
  31. if check.subject not in received_subject:
  32. action = "ign"
  33. ua = "Email from %s" % mailfrom
  34. check.ping(peer[0], "email", "", ua, data, action)
  35. self.stdout.write("Processed ping for %s" % code)
  36. class Command(BaseCommand):
  37. help = "Listen for ping emails"
  38. def add_arguments(self, parser):
  39. parser.add_argument("--host",
  40. help="ip address to listen on, default 0.0.0.0",
  41. default="0.0.0.0")
  42. parser.add_argument('--port',
  43. help="port to listen on, default 25",
  44. type=int,
  45. default=25)
  46. def handle(self, host, port, *args, **options):
  47. listener = Listener((host, port), self.stdout)
  48. print("Starting SMTP listener on %s:%d ..." % (host, port))
  49. asyncore.loop()