pipe.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. <?php
  2. // File size is limited by Nginx site to 10M
  3. // To speed things up, we do not include prerequisites
  4. header('Content-Type: text/plain');
  5. require_once "vars.inc.php";
  6. // Do not show errors, we log to using error_log
  7. ini_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. ];
  16. try {
  17. $pdo = new PDO($dsn, $database_user, $database_pass, $opt);
  18. }
  19. catch (PDOException $e) {
  20. error_log("QUARANTINE: " . $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. $redis->auth(getenv("REDISPASS"));
  28. // Functions
  29. function 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. }
  34. if (!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. $raw_data_content = file_get_contents('php://input');
  49. $raw_data = mb_convert_encoding($raw_data_content, 'HTML-ENTITIES', "UTF-8");
  50. $headers = getallheaders();
  51. $qid = $headers['X-Rspamd-Qid'];
  52. $fuzzy = $headers['X-Rspamd-Fuzzy'];
  53. $subject = iconv_mime_decode($headers['X-Rspamd-Subject']);
  54. $score = $headers['X-Rspamd-Score'];
  55. $rcpts = $headers['X-Rspamd-Rcpt'];
  56. $user = $headers['X-Rspamd-User'];
  57. $ip = $headers['X-Rspamd-Ip'];
  58. $action = $headers['X-Rspamd-Action'];
  59. $sender = $headers['X-Rspamd-From'];
  60. $symbols = $headers['X-Rspamd-Symbols'];
  61. $raw_size = (int)$_SERVER['CONTENT_LENGTH'];
  62. if (empty($sender)) {
  63. error_log("QUARANTINE: Unknown sender, assuming empty-env-from@localhost" . PHP_EOL);
  64. $sender = 'empty-env-from@localhost';
  65. }
  66. if ($fuzzy == 'unknown') {
  67. $fuzzy = '[]';
  68. }
  69. try {
  70. $max_size = (int)$redis->Get('Q_MAX_SIZE');
  71. if (($max_size * 1048576) < $raw_size) {
  72. error_log(sprintf("QUARANTINE: Message too large: %d b exceeds %d b", $raw_size, ($max_size * 1048576)) . PHP_EOL);
  73. http_response_code(505);
  74. exit;
  75. }
  76. if ($exclude_domains = $redis->Get('Q_EXCLUDE_DOMAINS')) {
  77. $exclude_domains = json_decode($exclude_domains, true);
  78. }
  79. $retention_size = (int)$redis->Get('Q_RETENTION_SIZE');
  80. }
  81. catch (RedisException $e) {
  82. error_log("QUARANTINE: " . $e . PHP_EOL);
  83. http_response_code(504);
  84. exit;
  85. }
  86. $rcpt_final_mailboxes = array();
  87. // Loop through all rcpts
  88. foreach (json_decode($rcpts, true) as $rcpt) {
  89. // Remove tag
  90. $rcpt = preg_replace('/^(.*?)\+.*(@.*)$/', '$1$2', $rcpt);
  91. // Break rcpt into local part and domain part
  92. $parsed_rcpt = parse_email($rcpt);
  93. // Skip if not a mailcow handled domain
  94. try {
  95. if (!$redis->hGet('DOMAIN_MAP', $parsed_rcpt['domain'])) {
  96. continue;
  97. }
  98. }
  99. catch (RedisException $e) {
  100. error_log("QUARANTINE: " . $e . PHP_EOL);
  101. http_response_code(504);
  102. exit;
  103. }
  104. // Skip if domain is excluded
  105. if (in_array($parsed_rcpt['domain'], $exclude_domains)) {
  106. error_log(sprintf("QUARANTINE: Skipped domain %s", $parsed_rcpt['domain']) . PHP_EOL);
  107. continue;
  108. }
  109. // Always assume rcpt is not a final mailbox but an alias for a mailbox or further aliases
  110. //
  111. // rcpt
  112. // |
  113. // mailbox <-- goto ---> alias1, alias2, mailbox2
  114. // | |
  115. // mailbox3 |
  116. // |
  117. // alias3 ---> mailbox4
  118. //
  119. try {
  120. $stmt = $pdo->prepare("SELECT `goto` FROM `alias` WHERE `address` = :rcpt AND `active` = '1'");
  121. $stmt->execute(array(
  122. ':rcpt' => $rcpt
  123. ));
  124. $gotos = $stmt->fetch(PDO::FETCH_ASSOC)['goto'];
  125. if (empty($gotos)) {
  126. $stmt = $pdo->prepare("SELECT `goto` FROM `alias` WHERE `address` = :rcpt AND `active` = '1'");
  127. $stmt->execute(array(
  128. ':rcpt' => '@' . $parsed_rcpt['domain']
  129. ));
  130. $gotos = $stmt->fetch(PDO::FETCH_ASSOC)['goto'];
  131. }
  132. if (empty($gotos)) {
  133. $stmt = $pdo->prepare("SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :rcpt AND `active` = '1'");
  134. $stmt->execute(array(':rcpt' => $parsed_rcpt['domain']));
  135. $goto_branch = $stmt->fetch(PDO::FETCH_ASSOC)['target_domain'];
  136. if ($goto_branch) {
  137. $gotos = $parsed_rcpt['local'] . '@' . $goto_branch;
  138. }
  139. }
  140. $gotos_array = explode(',', $gotos);
  141. $loop_c = 0;
  142. while (count($gotos_array) != 0 && $loop_c <= 20) {
  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. // Merge goto branch array derived from previous loop (if any), filter duplicates and unset goto branch array
  183. if (!empty($goto_branch_array)) {
  184. $gotos_array = array_unique(array_merge($gotos_array, $goto_branch_array));
  185. unset($goto_branch_array);
  186. }
  187. // Reindex array
  188. $gotos_array = array_values($gotos_array);
  189. // Force exit if loop cannot be solved
  190. // Postfix does not allow for alias loops, so this should never happen.
  191. $loop_c++;
  192. error_log("RCPT RESOVLER: http pipe: goto array count on loop #". $loop_c . " is " . count($gotos_array) . PHP_EOL);
  193. }
  194. }
  195. catch (PDOException $e) {
  196. error_log("RCPT RESOVLER: " . $e->getMessage() . PHP_EOL);
  197. http_response_code(502);
  198. exit;
  199. }
  200. }
  201. foreach ($rcpt_final_mailboxes as $rcpt_final) {
  202. error_log("QUARANTINE: quarantine pipe: processing quarantine message for rcpt " . $rcpt_final . PHP_EOL);
  203. try {
  204. $stmt = $pdo->prepare("INSERT INTO `quarantine` (`qid`, `subject`, `score`, `sender`, `rcpt`, `symbols`, `user`, `ip`, `msg`, `action`, `fuzzy_hashes`)
  205. VALUES (:qid, :subject, :score, :sender, :rcpt, :symbols, :user, :ip, :msg, :action, :fuzzy_hashes)");
  206. $stmt->execute(array(
  207. ':qid' => $qid,
  208. ':subject' => $subject,
  209. ':score' => $score,
  210. ':sender' => $sender,
  211. ':rcpt' => $rcpt_final,
  212. ':symbols' => $symbols,
  213. ':user' => $user,
  214. ':ip' => $ip,
  215. ':msg' => $raw_data,
  216. ':action' => $action,
  217. ':fuzzy_hashes' => $fuzzy
  218. ));
  219. $lastId = $pdo->lastInsertId();
  220. $stmt_update = $pdo->prepare("UPDATE `quarantine` SET `qhash` = SHA2(CONCAT(`id`, `qid`), 256) WHERE `id` = :id");
  221. $stmt_update->execute(array(':id' => $lastId));
  222. $stmt = $pdo->prepare('DELETE FROM `quarantine` WHERE `rcpt` = :rcpt AND `id` NOT IN (
  223. SELECT `id`
  224. FROM (
  225. SELECT `id`
  226. FROM `quarantine`
  227. WHERE `rcpt` = :rcpt2
  228. ORDER BY id DESC
  229. LIMIT :retention_size
  230. ) x
  231. );');
  232. $stmt->execute(array(
  233. ':rcpt' => $rcpt_final,
  234. ':rcpt2' => $rcpt_final,
  235. ':retention_size' => $retention_size
  236. ));
  237. }
  238. catch (PDOException $e) {
  239. error_log("QUARANTINE: " . $e->getMessage() . PHP_EOL);
  240. http_response_code(503);
  241. exit;
  242. }
  243. }