PageRenderTime 49ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/src/mailman/app/bounces.py

https://gitlab.com/noc0lour/mailman
Python | 263 lines | 154 code | 24 blank | 85 comment | 20 complexity | df3d751559c5b08ddd95ea3f02098e58 MD5 | raw file
  1. # Copyright (C) 2007-2016 by the Free Software Foundation, Inc.
  2. #
  3. # This file is part of GNU Mailman.
  4. #
  5. # GNU Mailman is free software: you can redistribute it and/or modify it under
  6. # the terms of the GNU General Public License as published by the Free
  7. # Software Foundation, either version 3 of the License, or (at your option)
  8. # any later version.
  9. #
  10. # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT
  11. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12. # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  13. # more details.
  14. #
  15. # You should have received a copy of the GNU General Public License along with
  16. # GNU Mailman. If not, see <http://www.gnu.org/licenses/>.
  17. """Application level bounce handling."""
  18. import re
  19. import uuid
  20. import logging
  21. from email.mime.message import MIMEMessage
  22. from email.mime.text import MIMEText
  23. from email.utils import parseaddr
  24. from mailman import public
  25. from mailman.config import config
  26. from mailman.core.i18n import _
  27. from mailman.email.message import OwnerNotification, UserNotification
  28. from mailman.interfaces.bounce import UnrecognizedBounceDisposition
  29. from mailman.interfaces.listmanager import IListManager
  30. from mailman.interfaces.pending import IPendable, IPendings
  31. from mailman.interfaces.subscriptions import ISubscriptionService
  32. from mailman.utilities.email import split_email
  33. from mailman.utilities.i18n import make
  34. from mailman.utilities.string import oneline
  35. from string import Template
  36. from zope.component import getUtility
  37. from zope.interface import implementer
  38. log = logging.getLogger('mailman.config')
  39. elog = logging.getLogger('mailman.error')
  40. blog = logging.getLogger('mailman.bounce')
  41. DOT = '.'
  42. @public
  43. def bounce_message(mlist, msg, error=None):
  44. """Bounce the message back to the original author.
  45. :param mlist: The mailing list that the message was posted to.
  46. :type mlist: `IMailingList`
  47. :param msg: The original message.
  48. :type msg: `email.message.Message`
  49. :param error: Optional exception causing the bounce. The exception
  50. instance must have a `.message` attribute.
  51. :type error: Exception
  52. """
  53. # Bounce a message back to the sender, with an error message if provided
  54. # in the exception argument. .sender might be None or the empty string.
  55. if not msg.sender:
  56. # We can't bounce the message if we don't know who it's supposed to go
  57. # to.
  58. return
  59. subject = msg.get('subject', _('(no subject)'))
  60. subject = oneline(subject, mlist.preferred_language.charset)
  61. if error is None:
  62. notice = _('[No bounce details are available]')
  63. else:
  64. notice = _(error.message)
  65. # Currently we always craft bounces as MIME messages.
  66. bmsg = UserNotification(msg.sender, mlist.owner_address, subject,
  67. lang=mlist.preferred_language)
  68. # BAW: Be sure you set the type before trying to attach, or you'll get
  69. # a MultipartConversionError.
  70. bmsg.set_type('multipart/mixed')
  71. txt = MIMEText(notice, _charset=mlist.preferred_language.charset)
  72. bmsg.attach(txt)
  73. bmsg.attach(MIMEMessage(msg))
  74. bmsg.send(mlist)
  75. class _BaseVERPParser:
  76. """Base class for parsing VERP messages.
  77. Sadly not every MTA bounces VERP messages correctly, or consistently.
  78. First, the To: header is checked, then Delivered-To: (Postfix),
  79. Envelope-To: (Exim) and Apparently-To:. Note that there can be multiple
  80. headers so we need to search them all
  81. """
  82. def __init__(self, pattern):
  83. self._pattern = pattern
  84. self._cre = re.compile(pattern, re.IGNORECASE)
  85. def get_verp(self, mlist, msg):
  86. """Extract a set of VERP bounce addresses.
  87. :param mlist: The mailing list being checked.
  88. :type mlist: `IMailingList`
  89. :param msg: The message being parsed.
  90. :type msg: `email.message.Message`
  91. :return: The set of addresses extracted from the VERP headers.
  92. :rtype: set of strings
  93. """
  94. blocal, bdomain = split_email(mlist.bounces_address)
  95. values = set()
  96. verp_matches = set()
  97. for header in ('to', 'delivered-to', 'envelope-to', 'apparently-to'):
  98. values.update(msg.get_all(header, []))
  99. for field in values:
  100. address = parseaddr(field)[1]
  101. if not address:
  102. # This header was empty.
  103. continue
  104. mo = self._cre.search(address)
  105. if not mo:
  106. # This did not match the VERP regexp.
  107. continue
  108. try:
  109. if blocal != mo.group('bounces'):
  110. # This was not a bounce to our mailing list.
  111. continue
  112. original_address = self._get_address(mo)
  113. except IndexError:
  114. elog.error('Bad VERP pattern: {0}'.format(self._pattern))
  115. return set()
  116. else:
  117. if original_address is not None:
  118. verp_matches.add(original_address)
  119. return verp_matches
  120. @public
  121. class StandardVERP(_BaseVERPParser):
  122. def __init__(self):
  123. super().__init__(config.mta.verp_regexp)
  124. def _get_address(self, match_object):
  125. return '{0}@{1}'.format(*match_object.group('local', 'domain'))
  126. @public
  127. class ProbeVERP(_BaseVERPParser):
  128. def __init__(self):
  129. super().__init__(config.mta.verp_probe_regexp)
  130. def _get_address(self, match_object):
  131. # Extract the token and get the matching address.
  132. token = match_object.group('token')
  133. pendable = getUtility(IPendings).confirm(token)
  134. if pendable is None:
  135. # The token must have already been confirmed, or it may have been
  136. # evicted from the database already.
  137. return None
  138. # We had to pend the uuid as a unicode.
  139. member_id = uuid.UUID(hex=pendable['member_id'])
  140. member = getUtility(ISubscriptionService).get_member(member_id)
  141. if member is None:
  142. return None
  143. return member.address.email
  144. @implementer(IPendable)
  145. class _ProbePendable(dict):
  146. """The pendable dictionary for probe messages."""
  147. PEND_TYPE = 'probe'
  148. @public
  149. def send_probe(member, msg):
  150. """Send a VERP probe to the member.
  151. :param member: The member to send the probe to. From this object, both
  152. the user and the mailing list can be determined.
  153. :type member: IMember
  154. :param msg: The bouncing message that caused the probe to be sent.
  155. :type msg:
  156. :return: The token representing this probe in the pendings database.
  157. :rtype: string
  158. """
  159. mlist = getUtility(IListManager).get_by_list_id(
  160. member.mailing_list.list_id)
  161. text = make('probe.txt', mlist, member.preferred_language.code,
  162. listname=mlist.fqdn_listname,
  163. address=member.address.email,
  164. optionsurl=member.options_url,
  165. owneraddr=mlist.owner_address,
  166. )
  167. message_id = msg['message-id']
  168. if isinstance(message_id, bytes):
  169. message_id = message_id.decode('ascii')
  170. pendable = _ProbePendable(
  171. # We can only pend unicodes.
  172. member_id=member.member_id.hex,
  173. message_id=message_id,
  174. )
  175. token = getUtility(IPendings).add(pendable)
  176. mailbox, domain_parts = split_email(mlist.bounces_address)
  177. probe_sender = Template(config.mta.verp_probe_format).safe_substitute(
  178. bounces=mailbox,
  179. token=token,
  180. domain=DOT.join(domain_parts),
  181. )
  182. # Calculate the Subject header, in the member's preferred language.
  183. with _.using(member.preferred_language.code):
  184. subject = _('$mlist.display_name mailing list probe message')
  185. # Craft the probe message. This will be a multipart where the first part
  186. # is the probe text and the second part is the message that caused this
  187. # probe to be sent.
  188. probe = UserNotification(member.address.email, probe_sender,
  189. subject, lang=member.preferred_language)
  190. probe.set_type('multipart/mixed')
  191. notice = MIMEText(text, _charset=mlist.preferred_language.charset)
  192. probe.attach(notice)
  193. probe.attach(MIMEMessage(msg))
  194. # Probes should not have the Precedence: bulk header.
  195. probe.send(mlist, envsender=probe_sender, verp=False, probe_token=token,
  196. add_precedence=False)
  197. return token
  198. @public
  199. def maybe_forward(mlist, msg):
  200. """Possibly forward bounce messages with no recognizable addresses.
  201. :param mlist: The mailing list.
  202. :type mlist: `IMailingList`
  203. :param msg: The bounce message to scan.
  204. :type msg: `Message`
  205. """
  206. message_id = msg['message-id']
  207. if (mlist.forward_unrecognized_bounces_to
  208. is UnrecognizedBounceDisposition.discard):
  209. blog.error('Discarding unrecognized bounce: {0}'.format(message_id))
  210. return
  211. # The notification is either going to go to the list's administrators
  212. # (owners and moderators), or to the site administrators. Most of the
  213. # notification is exactly the same in either case.
  214. adminurl = mlist.script_url('admin') + '/bounce'
  215. subject = _('Uncaught bounce notification')
  216. text = MIMEText(
  217. make('unrecognized.txt', mlist, adminurl=adminurl),
  218. _charset=mlist.preferred_language.charset)
  219. attachment = MIMEMessage(msg)
  220. if (mlist.forward_unrecognized_bounces_to
  221. is UnrecognizedBounceDisposition.administrators):
  222. keywords = dict(roster=mlist.administrators)
  223. elif (mlist.forward_unrecognized_bounces_to
  224. is UnrecognizedBounceDisposition.site_owner):
  225. keywords = {}
  226. else:
  227. raise AssertionError('Invalid forwarding disposition: {0}'.format(
  228. mlist.forward_unrecognized_bounces_to))
  229. # Create the notification and send it.
  230. notice = OwnerNotification(mlist, subject, **keywords)
  231. notice.set_type('multipart/mixed')
  232. notice.attach(text)
  233. notice.attach(attachment)
  234. notice.send(mlist)