quarantine_notify.py 6.0 KB

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