pipe.php 7.4 KB

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