From 15c6f5a7a2f615ec6d510e913d7fb44d94fbafa4 Mon Sep 17 00:00:00 2001
From: Jared Hancock <jared@osticket.com>
Date: Thu, 20 Feb 2014 21:43:42 -0600
Subject: [PATCH] Predictable message-ids

Outbound message-ids are predictable, with a consistent code unique and
static to each osTicket installation. This will help detect email loops
where message is delivered back to the system in an email loop.
---
 include/class.mailer.php |  4 +++-
 include/class.thread.php | 13 +++++++++++++
 2 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/include/class.mailer.php b/include/class.mailer.php
index 41d82e8c8..c5837f683 100644
--- a/include/class.mailer.php
+++ b/include/class.mailer.php
@@ -100,7 +100,9 @@ class Mailer {
         $subject = preg_replace("/(\r\n|\r|\n)/s",'', trim($subject));
 
         /* Message ID - generated for each outgoing email */
-        $messageId = sprintf('<%s-%s>', Misc::randCode(16),
+        $messageId = sprintf('<%s-%s-%s>',
+            substr(md5('mail'.SECRET_SALT), -9),
+            Misc::randCode(9),
             ($this->getEmail()?$this->getEmail()->getEmail():'@osTicketMailer'));
 
         $headers = array (
diff --git a/include/class.thread.php b/include/class.thread.php
index 35ec91788..355e0890e 100644
--- a/include/class.thread.php
+++ b/include/class.thread.php
@@ -618,6 +618,19 @@ Class ThreadEntry {
             // Reporting success so the email can be moved or deleted.
             return true;
 
+        // Mail sent by this system will have a message-id format of
+        // <code-random-mailbox@domain.tld>
+        // where code is a predictable string based on the SECRET_SALT of
+        // this osTicket installation. If this incoming mail matches the
+        // code, then it very likely originated from this system and looped
+        @list($code) = explode('-', $mailinfo['mid'], 2);
+        if (0 === strcasecmp(ltrim($code, '<'), substr(md5('mail'.SECRET_SALT), -9))) {
+            // This mail was sent by this system. It was received due to
+            // some kind of mail delivery loop. It should not be considered
+            // a response to an existing thread entry
+            return true;
+        }
+
         $vars = array(
             'mid' =>    $mailinfo['mid'],
             'header' => $mailinfo['header'],
-- 
GitLab