blob: e8d743b3177feb741c1a65d77a706497b4f37688 [file] [log] [blame]
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01001#!/usr/bin/python3
2
3import smtplib
4import os
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +02005import sys
Matthias Andreas Benkard9dabdab2024-03-06 13:12:09 +01006import MySQLdb
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +01007from email.mime.multipart import MIMEMultipart
8from email.mime.text import MIMEText
9from email.utils import COMMASPACE, formatdate
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +010010import jinja2
11from jinja2 import Template
12import json
13import redis
14import time
15import html2text
16import socket
17
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +020018pid = str(os.getpid())
19pidfile = "/tmp/quarantine_notify.pid"
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +010020
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +020021if os.path.isfile(pidfile):
22 print("%s already exists, exiting" % (pidfile))
23 sys.exit()
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +010024
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +020025pid = str(os.getpid())
26f = open(pidfile, 'w')
27f.write(pid)
28f.close()
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +010029
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +020030try:
31
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +010032 while True:
33 try:
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +020034 r = redis.StrictRedis(host='redis', decode_responses=True, port=6379, db=0)
35 r.ping()
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +010036 except Exception as ex:
37 print('%s - trying again...' % (ex))
38 time.sleep(3)
39 else:
40 break
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +010041
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +020042 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 Benkard9dabdab2024-03-06 13:12:09 +010052 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 Benkard8f915942021-08-16 10:57:25 +020053 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 Benkard4edeb9f2021-01-02 15:32:21 +010091 with open('/templates/quarantine.tpl') as file_:
92 template = Template(file_.read())
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +020093 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 Benkard4edeb9f2021-01-02 15:32:21 +0100145 try:
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200146 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 Benkard4edeb9f2021-01-02 15:32:21 +0100150 except Exception as ex:
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200151 print('Could not determine last notification for %s, assuming never' % (record['rcpt']))
Matthias Andreas Benkard4edeb9f2021-01-02 15:32:21 +0100152 last_notification = 0
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200153 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 Benkard3c18a082022-12-27 17:32:58 +0100163 if last_notification == 0 or (last_notification + time_trans[attrs['quarantine_notification']]) <= time_now:
Matthias Andreas Benkard8f915942021-08-16 10:57:25 +0200164 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
167finally:
Matthias Andreas Benkard3c18a082022-12-27 17:32:58 +0100168 os.unlink(pidfile)