pipe.php 7.4 KB

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