pipe.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. // Functions
  28. function parse_email($email) {
  29. if(!filter_var($email, FILTER_VALIDATE_EMAIL)) return false;
  30. $a = strrpos($email, '@');
  31. return array('local' => substr($email, 0, $a), 'domain' => substr(substr($email, $a), 1));
  32. }
  33. if (!function_exists('getallheaders')) {
  34. function getallheaders() {
  35. if (!is_array($_SERVER)) {
  36. return array();
  37. }
  38. $headers = array();
  39. foreach ($_SERVER as $name => $value) {
  40. if (substr($name, 0, 5) == 'HTTP_') {
  41. $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
  42. }
  43. }
  44. return $headers;
  45. }
  46. }
  47. $raw_data_content = file_get_contents('php://input');
  48. $raw_data = mb_convert_encoding($raw_data_content, 'HTML-ENTITIES', "UTF-8");
  49. $headers = getallheaders();
  50. $qid = $headers['X-Rspamd-Qid'];
  51. $fuzzy = $headers['X-Rspamd-Fuzzy'];
  52. $subject = iconv_mime_decode($headers['X-Rspamd-Subject']);
  53. $score = $headers['X-Rspamd-Score'];
  54. $rcpts = $headers['X-Rspamd-Rcpt'];
  55. $user = $headers['X-Rspamd-User'];
  56. $ip = $headers['X-Rspamd-Ip'];
  57. $action = $headers['X-Rspamd-Action'];
  58. $sender = $headers['X-Rspamd-From'];
  59. $symbols = $headers['X-Rspamd-Symbols'];
  60. $raw_size = (int)$_SERVER['CONTENT_LENGTH'];
  61. if (empty($sender)) {
  62. error_log("QUARANTINE: Unknown sender, assuming empty-env-from@localhost" . PHP_EOL);
  63. $sender = 'empty-env-from@localhost';
  64. }
  65. if ($fuzzy == 'unknown') {
  66. $fuzzy = '[]';
  67. }
  68. try {
  69. $max_size = (int)$redis->Get('Q_MAX_SIZE');
  70. if (($max_size * 1048576) < $raw_size) {
  71. error_log(sprintf("QUARANTINE: Message too large: %d b exceeds %d b", $raw_size, ($max_size * 1048576)) . PHP_EOL);
  72. http_response_code(505);
  73. exit;
  74. }
  75. if ($exclude_domains = $redis->Get('Q_EXCLUDE_DOMAINS')) {
  76. $exclude_domains = json_decode($exclude_domains, true);
  77. }
  78. $retention_size = (int)$redis->Get('Q_RETENTION_SIZE');
  79. }
  80. catch (RedisException $e) {
  81. error_log("QUARANTINE: " . $e . PHP_EOL);
  82. http_response_code(504);
  83. exit;
  84. }
  85. $rcpt_final_mailboxes = array();
  86. // Loop through all rcpts
  87. foreach (json_decode($rcpts, true) as $rcpt) {
  88. // Remove tag
  89. $rcpt = preg_replace('/^(.*?)\+.*(@.*)$/', '$1$2', $rcpt);
  90. // Break rcpt into local part and domain part
  91. $parsed_rcpt = parse_email($rcpt);
  92. // Skip if not a mailcow handled domain
  93. try {
  94. if (!$redis->hGet('DOMAIN_MAP', $parsed_rcpt['domain'])) {
  95. continue;
  96. }
  97. }
  98. catch (RedisException $e) {
  99. error_log("QUARANTINE: " . $e . PHP_EOL);
  100. http_response_code(504);
  101. exit;
  102. }
  103. // Skip if domain is excluded
  104. if (in_array($parsed_rcpt['domain'], $exclude_domains)) {
  105. error_log(sprintf("QUARANTINE: Skipped domain %s", $parsed_rcpt['domain']) . PHP_EOL);
  106. continue;
  107. }
  108. // Always assume rcpt is not a final mailbox but an alias for a mailbox or further aliases
  109. //
  110. // rcpt
  111. // |
  112. // mailbox <-- goto ---> alias1, alias2, mailbox2
  113. // | |
  114. // mailbox3 |
  115. // |
  116. // alias3 ---> mailbox4
  117. //
  118. try {
  119. $stmt = $pdo->prepare("SELECT `goto` FROM `alias` WHERE `address` = :rcpt AND `active` = '1'");
  120. $stmt->execute(array(
  121. ':rcpt' => $rcpt
  122. ));
  123. $gotos = $stmt->fetch(PDO::FETCH_ASSOC)['goto'];
  124. if (empty($gotos)) {
  125. $stmt = $pdo->prepare("SELECT `goto` FROM `alias` WHERE `address` = :rcpt AND `active` = '1'");
  126. $stmt->execute(array(
  127. ':rcpt' => '@' . $parsed_rcpt['domain']
  128. ));
  129. $gotos = $stmt->fetch(PDO::FETCH_ASSOC)['goto'];
  130. }
  131. if (empty($gotos)) {
  132. $stmt = $pdo->prepare("SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :rcpt AND `active` = '1'");
  133. $stmt->execute(array(':rcpt' => $parsed_rcpt['domain']));
  134. $goto_branch = $stmt->fetch(PDO::FETCH_ASSOC)['target_domain'];
  135. if ($goto_branch) {
  136. $gotos = $parsed_rcpt['local'] . '@' . $goto_branch;
  137. }
  138. }
  139. $gotos_array = explode(',', $gotos);
  140. $loop_c = 0;
  141. while (count($gotos_array) != 0 && $loop_c <= 20) {
  142. // Loop through all found gotos
  143. foreach ($gotos_array as $index => &$goto) {
  144. error_log("RCPT RESOVLER: http pipe: query " . $goto . " as username from mailbox" . PHP_EOL);
  145. $stmt = $pdo->prepare("SELECT `username` FROM `mailbox` WHERE `username` = :goto AND (`active`= '1' OR `active`= '2');");
  146. $stmt->execute(array(':goto' => $goto));
  147. $username = $stmt->fetch(PDO::FETCH_ASSOC)['username'];
  148. if (!empty($username)) {
  149. error_log("RCPT RESOVLER: http pipe: mailbox found: " . $username . PHP_EOL);
  150. // Current goto is a mailbox, save to rcpt_final_mailboxes if not a duplicate
  151. if (!in_array($username, $rcpt_final_mailboxes)) {
  152. $rcpt_final_mailboxes[] = $username;
  153. }
  154. }
  155. else {
  156. $parsed_goto = parse_email($goto);
  157. if (!$redis->hGet('DOMAIN_MAP', $parsed_goto['domain'])) {
  158. error_log("RCPT RESOVLER:" . $goto . " is not a mailcow handled mailbox or alias address" . PHP_EOL);
  159. }
  160. else {
  161. $stmt = $pdo->prepare("SELECT `goto` FROM `alias` WHERE `address` = :goto AND `active` = '1'");
  162. $stmt->execute(array(':goto' => $goto));
  163. $goto_branch = $stmt->fetch(PDO::FETCH_ASSOC)['goto'];
  164. if ($goto_branch) {
  165. error_log("RCPT RESOVLER: http pipe: goto address " . $goto . " is an alias branch for " . $goto_branch . PHP_EOL);
  166. $goto_branch_array = explode(',', $goto_branch);
  167. } else {
  168. $stmt = $pdo->prepare("SELECT `target_domain` FROM `alias_domain` WHERE `alias_domain` = :domain AND `active` AND '1'");
  169. $stmt->execute(array(':domain' => $parsed_goto['domain']));
  170. $goto_branch = $stmt->fetch(PDO::FETCH_ASSOC)['target_domain'];
  171. if ($goto_branch) {
  172. error_log("RCPT RESOVLER: http pipe: goto domain " . $parsed_goto['domain'] . " is a domain alias branch for " . $goto_branch . PHP_EOL);
  173. $goto_branch_array = array($parsed_goto['local'] . '@' . $goto_branch);
  174. }
  175. }
  176. }
  177. }
  178. // goto item was processed, unset
  179. unset($gotos_array[$index]);
  180. }
  181. // Merge goto branch array derived from previous loop (if any), filter duplicates and unset goto branch array
  182. if (!empty($goto_branch_array)) {
  183. $gotos_array = array_unique(array_merge($gotos_array, $goto_branch_array));
  184. unset($goto_branch_array);
  185. }
  186. // Reindex array
  187. $gotos_array = array_values($gotos_array);
  188. // Force exit if loop cannot be solved
  189. // Postfix does not allow for alias loops, so this should never happen.
  190. $loop_c++;
  191. error_log("RCPT RESOVLER: http pipe: goto array count on loop #". $loop_c . " is " . count($gotos_array) . PHP_EOL);
  192. }
  193. }
  194. catch (PDOException $e) {
  195. error_log("RCPT RESOVLER: " . $e->getMessage() . PHP_EOL);
  196. http_response_code(502);
  197. exit;
  198. }
  199. }
  200. foreach ($rcpt_final_mailboxes as $rcpt_final) {
  201. error_log("QUARANTINE: quarantine pipe: processing quarantine message for rcpt " . $rcpt_final . PHP_EOL);
  202. try {
  203. $stmt = $pdo->prepare("INSERT INTO `quarantine` (`qid`, `subject`, `score`, `sender`, `rcpt`, `symbols`, `user`, `ip`, `msg`, `action`, `fuzzy_hashes`)
  204. VALUES (:qid, :subject, :score, :sender, :rcpt, :symbols, :user, :ip, :msg, :action, :fuzzy_hashes)");
  205. $stmt->execute(array(
  206. ':qid' => $qid,
  207. ':subject' => $subject,
  208. ':score' => $score,
  209. ':sender' => $sender,
  210. ':rcpt' => $rcpt_final,
  211. ':symbols' => $symbols,
  212. ':user' => $user,
  213. ':ip' => $ip,
  214. ':msg' => $raw_data,
  215. ':action' => $action,
  216. ':fuzzy_hashes' => $fuzzy
  217. ));
  218. $stmt = $pdo->prepare('DELETE FROM `quarantine` WHERE `rcpt` = :rcpt AND `id` NOT IN (
  219. SELECT `id`
  220. FROM (
  221. SELECT `id`
  222. FROM `quarantine`
  223. WHERE `rcpt` = :rcpt2
  224. ORDER BY id DESC
  225. LIMIT :retention_size
  226. ) x
  227. );');
  228. $stmt->execute(array(
  229. ':rcpt' => $rcpt_final,
  230. ':rcpt2' => $rcpt_final,
  231. ':retention_size' => $retention_size
  232. ));
  233. }
  234. catch (PDOException $e) {
  235. error_log("QUARANTINE: " . $e->getMessage() . PHP_EOL);
  236. http_response_code(503);
  237. exit;
  238. }
  239. }