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