quarantine_notify.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. #!/usr/bin/python3
  2. import smtplib
  3. import os
  4. import sys
  5. import MySQLdb
  6. from email.mime.multipart import MIMEMultipart
  7. from email.mime.text import MIMEText
  8. from email.utils import COMMASPACE, formatdate
  9. import jinja2
  10. from jinja2 import Template
  11. import json
  12. import redis
  13. import time
  14. import html2text
  15. import socket
  16. pid = str(os.getpid())
  17. pidfile = "/tmp/quarantine_notify.pid"
  18. if os.path.isfile(pidfile):
  19. print("%s already exists, exiting" % (pidfile))
  20. sys.exit()
  21. pid = str(os.getpid())
  22. f = open(pidfile, 'w')
  23. f.write(pid)
  24. f.close()
  25. try:
  26. while True:
  27. try:
  28. r = redis.StrictRedis(host='redis', decode_responses=True, port=6379, db=0)
  29. r.ping()
  30. except Exception as ex:
  31. print('%s - trying again...' % (ex))
  32. time.sleep(3)
  33. else:
  34. break
  35. time_now = int(time.time())
  36. mailcow_hostname = os.environ.get('MAILCOW_HOSTNAME')
  37. max_score = float(r.get('Q_MAX_SCORE') or "9999.0")
  38. if max_score == "":
  39. max_score = 9999.0
  40. def query_mysql(query, headers = True, update = False):
  41. while True:
  42. try:
  43. cnx = MySQLdb.connect(user=os.environ.get('DBUSER'), password=os.environ.get('DBPASS'), database=os.environ.get('DBNAME'), charset="utf8mb4", collation="utf8mb4_general_ci")
  44. except Exception as ex:
  45. print('%s - trying again...' % (ex))
  46. time.sleep(3)
  47. else:
  48. break
  49. cur = cnx.cursor()
  50. cur.execute(query)
  51. if not update:
  52. result = []
  53. columns = tuple( [d[0] for d in cur.description] )
  54. for row in cur:
  55. if headers:
  56. result.append(dict(list(zip(columns, row))))
  57. else:
  58. result.append(row)
  59. cur.close()
  60. cnx.close()
  61. return result
  62. else:
  63. cnx.commit()
  64. cur.close()
  65. cnx.close()
  66. def notify_rcpt(rcpt, msg_count, quarantine_acl, category):
  67. if category == "add_header": category = "add header"
  68. meta_query = query_mysql('SELECT SHA2(CONCAT(id, qid), 256) AS qhash, id, subject, score, sender, created, action FROM quarantine WHERE notified = 0 AND rcpt = "%s" AND score < %f AND (action = "%s" OR "all" = "%s")' % (rcpt, max_score, category, category))
  69. print("%s: %d of %d messages qualify for notification" % (rcpt, len(meta_query), msg_count))
  70. if len(meta_query) == 0:
  71. return
  72. msg_count = len(meta_query)
  73. if r.get('Q_HTML'):
  74. try:
  75. template = Template(r.get('Q_HTML'))
  76. except:
  77. print("Error: Cannot parse quarantine template, falling back to default template.")
  78. with open('/templates/quarantine.tpl') as file_:
  79. template = Template(file_.read())
  80. else:
  81. with open('/templates/quarantine.tpl') as file_:
  82. template = Template(file_.read())
  83. html = template.render(meta=meta_query, username=rcpt, counter=msg_count, hostname=mailcow_hostname, quarantine_acl=quarantine_acl)
  84. text = html2text.html2text(html)
  85. count = 0
  86. while count < 15:
  87. count += 1
  88. try:
  89. server = smtplib.SMTP('postfix', 590, 'quarantine')
  90. server.ehlo()
  91. msg = MIMEMultipart('alternative')
  92. msg_from = r.get('Q_SENDER') or "quarantine@localhost"
  93. # Remove non-ascii chars from field
  94. msg['From'] = ''.join([i if ord(i) < 128 else '' for i in msg_from])
  95. msg['Subject'] = r.get('Q_SUBJ') or "Spam Quarantine Notification"
  96. msg['Date'] = formatdate(localtime = True)
  97. text_part = MIMEText(text, 'plain', 'utf-8')
  98. html_part = MIMEText(html, 'html', 'utf-8')
  99. msg.attach(text_part)
  100. msg.attach(html_part)
  101. msg['To'] = str(rcpt)
  102. bcc = r.get('Q_BCC') or ""
  103. redirect = r.get('Q_REDIRECT') or ""
  104. text = msg.as_string()
  105. if bcc == '':
  106. if redirect == '':
  107. server.sendmail(msg['From'], str(rcpt), text)
  108. else:
  109. server.sendmail(msg['From'], str(redirect), text)
  110. else:
  111. if redirect == '':
  112. server.sendmail(msg['From'], [str(rcpt)] + [str(bcc)], text)
  113. else:
  114. server.sendmail(msg['From'], [str(redirect)] + [str(bcc)], text)
  115. server.quit()
  116. for res in meta_query:
  117. query_mysql('UPDATE quarantine SET notified = 1 WHERE id = "%d"' % (res['id']), update = True)
  118. r.hset('Q_LAST_NOTIFIED', record['rcpt'], time_now)
  119. break
  120. except Exception as ex:
  121. server.quit()
  122. print('%s' % (ex))
  123. time.sleep(3)
  124. records = query_mysql('SELECT IFNULL(user_acl.quarantine, 0) AS quarantine_acl, count(id) AS counter, rcpt FROM quarantine LEFT OUTER JOIN user_acl ON user_acl.username = rcpt WHERE notified = 0 AND score < %f AND rcpt in (SELECT username FROM mailbox) GROUP BY rcpt' % (max_score))
  125. for record in records:
  126. attrs = ''
  127. attrs_json = ''
  128. time_trans = {
  129. "hourly": 3600,
  130. "daily": 86400,
  131. "weekly": 604800
  132. }
  133. try:
  134. last_notification = int(r.hget('Q_LAST_NOTIFIED', record['rcpt']))
  135. if last_notification > time_now:
  136. print('Last notification is > time now, assuming never')
  137. last_notification = 0
  138. except Exception as ex:
  139. print('Could not determine last notification for %s, assuming never' % (record['rcpt']))
  140. last_notification = 0
  141. attrs_json = query_mysql('SELECT attributes FROM mailbox WHERE username = "%s"' % (record['rcpt']))
  142. attrs = attrs_json[0]['attributes']
  143. if isinstance(attrs, str):
  144. # if attr is str then just load it
  145. attrs = json.loads(attrs)
  146. else:
  147. # if it's bytes then decode and load it
  148. attrs = json.loads(attrs.decode('utf-8'))
  149. if attrs['quarantine_notification'] not in ('hourly', 'daily', 'weekly'):
  150. continue
  151. if last_notification == 0 or (last_notification + time_trans[attrs['quarantine_notification']]) <= time_now:
  152. print("Notifying %s: Considering %d new items in quarantine (policy: %s)" % (record['rcpt'], record['counter'], attrs['quarantine_notification']))
  153. notify_rcpt(record['rcpt'], record['counter'], record['quarantine_acl'], attrs['quarantine_category'])
  154. finally:
  155. os.unlink(pidfile)