pipe.php 8.8 KB

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