# Author: Stuart D. Gathman <stuart@bmsi.com>
# Copyright 2006 Business Management Systems, Inc.
# This code is under the GNU General Public License.  See COPYING for details.

# Heuristically determine whether a DSN is for a delivery failure.
# False positives waste time, but don't hurt anything, since we
# also look for our signed Message-ID.  These actually shouldn't ever
# happen, because you are not supposed to send a DSN for a DSN.  However,
# since some MTAs do in fact send these for our DSNs, we make use of
# the info to blacklist senders.

# examples we don't yet recognize:
#
# wiley-268-8196.roadrunner.nf.net at ('205.251.174.46', 4810)
# cbl-sd-02-79.aster.com.do at ('200.88.62.79', 4153)

import re

subjpats = (
 r'^failure notice',
 r'^returned mail',
 r'^undeliverable',
 r'^delivery\b.*\bfailure',
)
resubj = re.compile('|'.join(subjpats),re.IGNORECASE)

def is_faildsn(subj):
  """Return True if subject if for a delivery failure.
  Examples:

  >>> is_faildsn('Delivery Status Notification (Failure)')
  True
  >>> is_faildsn('DELIVERY FAILURE: Error delivering to bsaccone')
  True
  >>> is_faildsn('DELIVERY STATUS (POSSIBLE SPAM)')
  False
  """
  return bool(resubj.match(subj))

if __name__ == '__main__':
  import doctest
  import faildsn
  doctest.testmod(faildsn)
