blob: 10265d15f35c2bde2ae4fb3866c4640a85e163c8 [file] [log] [blame]
Matthias Andreas Benkardb382b102021-01-02 15:32:21 +01001<?php
2// File size is limited by Nginx site to 10M
3// To speed things up, we do not include prerequisites
4header('Content-Type: text/plain');
5require_once "vars.inc.php";
6// Do not show errors, we log to using error_log
7ini_set('error_reporting', 0);
8// Init database
9//$dsn = $database_type . ':host=' . $database_host . ';dbname=' . $database_name;
10$dsn = $database_type . ":unix_socket=" . $database_sock . ";dbname=" . $database_name;
11$opt = [
12 PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
13 PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
14 PDO::ATTR_EMULATE_PREPARES => false,
15];
16try {
17 $pdo = new PDO($dsn, $database_user, $database_pass, $opt);
18}
19catch (PDOException $e) {
20 error_log("NOTIFY: " . $e . PHP_EOL);
21 http_response_code(501);
22 exit;
23}
24// Init Redis
25$redis = new Redis();
26$redis->connect('redis-mailcow', 6379);
27
28// Functions
29function parse_email($email) {
30 if(!filter_var($email, FILTER_VALIDATE_EMAIL)) return false;
31 $a = strrpos($email, '@');
32 return array('local' => substr($email, 0, $a), 'domain' => substr(substr($email, $a), 1));
33}
34if (!function_exists('getallheaders')) {
35 function getallheaders() {
36 if (!is_array($_SERVER)) {
37 return array();
38 }
39 $headers = array();
40 foreach ($_SERVER as $name => $value) {
41 if (substr($name, 0, 5) == 'HTTP_') {
42 $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
43 }
44 }
45 return $headers;
46 }
47}
48
49$headers = getallheaders();
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +010050$json_body = json_decode(file_get_contents('php://input'));
Matthias Andreas Benkardb382b102021-01-02 15:32:21 +010051
52$qid = $headers['X-Rspamd-Qid'];
53$rcpts = $headers['X-Rspamd-Rcpt'];
54$sender = $headers['X-Rspamd-From'];
55$ip = $headers['X-Rspamd-Ip'];
56$subject = $headers['X-Rspamd-Subject'];
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +010057$messageid= $json_body->message_id;
Matthias Andreas Benkardb382b102021-01-02 15:32:21 +010058$priority = 0;
59
60$symbols_array = json_decode($headers['X-Rspamd-Symbols'], true);
61if (is_array($symbols_array)) {
62 foreach ($symbols_array as $symbol) {
63 if ($symbol['name'] == 'HAS_X_PRIO_ONE') {
64 $priority = 1;
65 break;
66 }
67 }
68}
69
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +010070$sender_address = $json_body->header_from[0];
71$sender_name = '-';
72if (preg_match('/(?<name>.*?)<(?<address>.*?)>/i', $sender_address, $matches)) {
73 $sender_address = $matches['address'];
74 $sender_name = trim($matches['name'], '"\' ');
75}
76
77$to_address = $json_body->header_to[0];
78$to_name = '-';
79if (preg_match('/(?<name>.*?)<(?<address>.*?)>/i', $to_address, $matches)) {
80 $to_address = $matches['address'];
81 $to_name = trim($matches['name'], '"\' ');
82}
83
Matthias Andreas Benkardb382b102021-01-02 15:32:21 +010084$rcpt_final_mailboxes = array();
85
86// Loop through all rcpts
87foreach (json_decode($rcpts, true) as $rcpt) {
88 // Remove tag
89 $rcpt = preg_replace('/^(.*?)\+.*(@.*)$/', '$1$2', $rcpt);
90
91 // Break rcpt into local part and domain part
92 $parsed_rcpt = parse_email($rcpt);
93
94 // Skip if not a mailcow handled domain
95 try {
96 if (!$redis->hGet('DOMAIN_MAP', $parsed_rcpt['domain'])) {
97 continue;
98 }
99 }
100 catch (RedisException $e) {
101 error_log("NOTIFY: " . $e . PHP_EOL);
102 http_response_code(504);
103 exit;
104 }
105
106 // Always assume rcpt is not a final mailbox but an alias for a mailbox or further aliases
107 //
108 // rcpt
109 // |
110 // mailbox <-- goto ---> alias1, alias2, mailbox2
111 // | |
112 // mailbox3 |
113 // |
114 // alias3 ---> mailbox4
115 //
116 try {
117 $stmt = $pdo->prepare("SELECT `goto` FROM `alias` WHERE `address` = :rcpt AND `active` = '1'");
118 $stmt->execute(array(
119 ':rcpt' => $rcpt
120 ));
121 $gotos = $stmt->fetch(PDO::FETCH_ASSOC)['goto'];
122 if (empty($gotos)) {
123 $stmt = $pdo->prepare("SELECT `goto` FROM `alias` WHERE `address` = :rcpt AND `active` = '1'");
124 $stmt->execute(array(
125 ':rcpt' => '@' . $parsed_rcpt['domain']
126 ));
127 $gotos = $stmt->fetch(PDO::FETCH_ASSOC)['goto'];
128 }
129 if (empty($gotos)) {
130 $stmt = $pdo->prepare("SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :rcpt AND `active` = '1'");
131 $stmt->execute(array(':rcpt' => $parsed_rcpt['domain']));
132 $goto_branch = $stmt->fetch(PDO::FETCH_ASSOC)['target_domain'];
133 if ($goto_branch) {
134 $gotos = $parsed_rcpt['local'] . '@' . $goto_branch;
135 }
136 }
137 $gotos_array = explode(',', $gotos);
138
139 $loop_c = 0;
140
141 while (count($gotos_array) != 0 && $loop_c <= 20) {
142
143 // Loop through all found gotos
144 foreach ($gotos_array as $index => &$goto) {
145 error_log("RCPT RESOVLER: http pipe: query " . $goto . " as username from mailbox" . PHP_EOL);
146 $stmt = $pdo->prepare("SELECT `username` FROM `mailbox` WHERE `username` = :goto AND (`active`= '1' OR `active`= '2');");
147 $stmt->execute(array(':goto' => $goto));
148 $username = $stmt->fetch(PDO::FETCH_ASSOC)['username'];
149 if (!empty($username)) {
150 error_log("RCPT RESOVLER: http pipe: mailbox found: " . $username . PHP_EOL);
151 // Current goto is a mailbox, save to rcpt_final_mailboxes if not a duplicate
152 if (!in_array($username, $rcpt_final_mailboxes)) {
153 $rcpt_final_mailboxes[] = $username;
154 }
155 }
156 else {
157 $parsed_goto = parse_email($goto);
158 if (!$redis->hGet('DOMAIN_MAP', $parsed_goto['domain'])) {
159 error_log("RCPT RESOVLER:" . $goto . " is not a mailcow handled mailbox or alias address" . PHP_EOL);
160 }
161 else {
162 $stmt = $pdo->prepare("SELECT `goto` FROM `alias` WHERE `address` = :goto AND `active` = '1'");
163 $stmt->execute(array(':goto' => $goto));
164 $goto_branch = $stmt->fetch(PDO::FETCH_ASSOC)['goto'];
165 if ($goto_branch) {
166 error_log("RCPT RESOVLER: http pipe: goto address " . $goto . " is an alias branch for " . $goto_branch . PHP_EOL);
167 $goto_branch_array = explode(',', $goto_branch);
168 } else {
169 $stmt = $pdo->prepare("SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :domain AND `active` AND '1'");
170 $stmt->execute(array(':domain' => $parsed_goto['domain']));
171 $goto_branch = $stmt->fetch(PDO::FETCH_ASSOC)['target_domain'];
172 if ($goto_branch) {
173 error_log("RCPT RESOVLER: http pipe: goto domain " . $parsed_goto['domain'] . " is a domain alias branch for " . $goto_branch . PHP_EOL);
174 $goto_branch_array = array($parsed_goto['local'] . '@' . $goto_branch);
175 }
176 }
177 }
178 }
179 // goto item was processed, unset
180 unset($gotos_array[$index]);
181 }
182
183 // Merge goto branch array derived from previous loop (if any), filter duplicates and unset goto branch array
184 if (!empty($goto_branch_array)) {
185 $gotos_array = array_unique(array_merge($gotos_array, $goto_branch_array));
186 unset($goto_branch_array);
187 }
188
189 // Reindex array
190 $gotos_array = array_values($gotos_array);
191
192 // Force exit if loop cannot be solved
193 // Postfix does not allow for alias loops, so this should never happen.
194 $loop_c++;
195 error_log("RCPT RESOVLER: http pipe: goto array count on loop #". $loop_c . " is " . count($gotos_array) . PHP_EOL);
196 }
197 }
198 catch (PDOException $e) {
199 error_log("RCPT RESOVLER: " . $e->getMessage() . PHP_EOL);
200 http_response_code(502);
201 exit;
202 }
203}
204
205
206foreach ($rcpt_final_mailboxes as $rcpt_final) {
207 error_log("NOTIFY: pushover pipe: processing pushover message for rcpt " . $rcpt_final . PHP_EOL);
208 $stmt = $pdo->prepare("SELECT * FROM `pushover`
209 WHERE `username` = :username AND `active` = '1'");
210 $stmt->execute(array(
211 ':username' => $rcpt_final
212 ));
213 $api_data = $stmt->fetch(PDO::FETCH_ASSOC);
214 if (isset($api_data['key']) && isset($api_data['token'])) {
215 $title = (!empty($api_data['title'])) ? $api_data['title'] : 'Mail';
216 $text = (!empty($api_data['text'])) ? $api_data['text'] : 'You\'ve got mail 📧';
217 $attributes = json_decode($api_data['attributes'], true);
218 $senders = explode(',', $api_data['senders']);
219 $senders = array_filter($senders);
220 $senders_regex = $api_data['senders_regex'];
221 $sender_validated = false;
222 if (empty($senders) && empty($senders_regex)) {
223 $sender_validated = true;
224 }
225 else {
226 if (!empty($senders)) {
227 if (in_array($sender, $senders)) {
228 $sender_validated = true;
229 }
230 }
231 if (!empty($senders_regex) && $sender_validated !== true) {
232 if (preg_match($senders_regex, $sender)) {
233 $sender_validated = true;
234 }
235 }
236 }
237 if ($sender_validated === false) {
238 error_log("NOTIFY: pushover pipe: skipping unwanted sender " . $sender);
239 continue;
240 }
241 if ($attributes['only_x_prio'] == "1" && $priority == 0) {
242 error_log("NOTIFY: pushover pipe: mail has no X-Priority: 1 header, skipping");
243 continue;
244 }
245 $post_fields = array(
246 "token" => $api_data['token'],
247 "user" => $api_data['key'],
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +0100248 "title" => sprintf("%s", str_replace(
249 array('{SUBJECT}', '{SENDER}', '{SENDER_NAME}', '{SENDER_ADDRESS}', '{TO_NAME}', '{TO_ADDRESS}', '{MSG_ID}'),
250 array($subject, $sender, $sender_name, $sender_address, $to_name, $to_address, $messageid), $title)
251 ),
Matthias Andreas Benkardb382b102021-01-02 15:32:21 +0100252 "priority" => $priority,
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +0100253 "message" => sprintf("%s", str_replace(
254 array('{SUBJECT}', '{SENDER}', '{SENDER_NAME}', '{SENDER_ADDRESS}', '{TO_NAME}', '{TO_ADDRESS}', '{MSG_ID}', '\n'),
255 array($subject, $sender, $sender_name, $sender_address, $to_name, $to_address, $messageid, PHP_EOL), $text)
256 ),
257 "sound" => $attributes['sound'] ?? "pushover"
Matthias Andreas Benkardb382b102021-01-02 15:32:21 +0100258 );
259 if ($attributes['evaluate_x_prio'] == "1" && $priority == 1) {
260 $post_fields['expire'] = 600;
261 $post_fields['retry'] = 120;
262 $post_fields['priority'] = 2;
263 }
264 curl_setopt_array($ch = curl_init(), array(
265 CURLOPT_URL => "https://api.pushover.net/1/messages.json",
266 CURLOPT_POSTFIELDS => $post_fields,
267 CURLOPT_SAFE_UPLOAD => true,
268 CURLOPT_RETURNTRANSFER => true,
269 ));
270 $result = curl_exec($ch);
271 $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
272 curl_close($ch);
273 error_log("NOTIFY: result: " . $httpcode . PHP_EOL);
274 }
275}