protocols.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. # -*- test-case-name: twisted.mail.test.test_mail -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Mail protocol support.
  6. """
  7. from __future__ import absolute_import, division
  8. from twisted.mail import pop3
  9. from twisted.mail import smtp
  10. from twisted.internet import protocol
  11. from twisted.internet import defer
  12. from twisted.copyright import longversion
  13. from twisted.python import log
  14. from twisted.python.compat import networkString
  15. from twisted.cred.credentials import CramMD5Credentials, UsernamePassword
  16. from twisted.cred.error import UnauthorizedLogin
  17. from twisted.mail import relay
  18. from zope.interface import implementer
  19. @implementer(smtp.IMessageDelivery)
  20. class DomainDeliveryBase:
  21. """
  22. A base class for message delivery using the domains of a mail service.
  23. @ivar service: See L{__init__}
  24. @ivar user: See L{__init__}
  25. @ivar host: See L{__init__}
  26. @type protocolName: L{bytes}
  27. @ivar protocolName: The protocol being used to deliver the mail.
  28. Sub-classes should set this appropriately.
  29. """
  30. service = None
  31. protocolName = None
  32. def __init__(self, service, user, host=smtp.DNSNAME):
  33. """
  34. @type service: L{MailService}
  35. @param service: A mail service.
  36. @type user: L{bytes} or L{None}
  37. @param user: The authenticated SMTP user.
  38. @type host: L{bytes}
  39. @param host: The hostname.
  40. """
  41. self.service = service
  42. self.user = user
  43. self.host = host
  44. def receivedHeader(self, helo, origin, recipients):
  45. """
  46. Generate a received header string for a message.
  47. @type helo: 2-L{tuple} of (L{bytes}, L{bytes})
  48. @param helo: The client's identity as sent in the HELO command and its
  49. IP address.
  50. @type origin: L{Address}
  51. @param origin: The origination address of the message.
  52. @type recipients: L{list} of L{User}
  53. @param recipients: The destination addresses for the message.
  54. @rtype: L{bytes}
  55. @return: A received header string.
  56. """
  57. authStr = heloStr = b""
  58. if self.user:
  59. authStr = b" auth=" + self.user.encode('xtext')
  60. if helo[0]:
  61. heloStr = b" helo=" + helo[0]
  62. fromUser = (b"from " + helo[0] + b" ([" + helo[1] + b"]" +
  63. heloStr + authStr)
  64. by = (b"by " + self.host + b" with " + self.protocolName +
  65. b" (" + networkString(longversion) + b")")
  66. forUser = (b"for <" + b' '.join(map(bytes, recipients)) + b"> " +
  67. smtp.rfc822date())
  68. return (b"Received: " + fromUser + b"\n\t" + by +
  69. b"\n\t" + forUser)
  70. def validateTo(self, user):
  71. """
  72. Validate the address for which a message is destined.
  73. @type user: L{User}
  74. @param user: The destination address.
  75. @rtype: L{Deferred <defer.Deferred>} which successfully fires with
  76. no-argument callable which returns L{IMessage <smtp.IMessage>}
  77. provider.
  78. @return: A deferred which successfully fires with a no-argument
  79. callable which returns a message receiver for the destination.
  80. @raise SMTPBadRcpt: When messages cannot be accepted for the
  81. destination address.
  82. """
  83. # XXX - Yick. This needs cleaning up.
  84. if self.user and self.service.queue:
  85. d = self.service.domains.get(user.dest.domain, None)
  86. if d is None:
  87. d = relay.DomainQueuer(self.service, True)
  88. else:
  89. d = self.service.domains[user.dest.domain]
  90. return defer.maybeDeferred(d.exists, user)
  91. def validateFrom(self, helo, origin):
  92. """
  93. Validate the address from which a message originates.
  94. @type helo: 2-L{tuple} of (L{bytes}, L{bytes})
  95. @param helo: The client's identity as sent in the HELO command and its
  96. IP address.
  97. @type origin: L{Address}
  98. @param origin: The origination address of the message.
  99. @rtype: L{Address}
  100. @return: The origination address.
  101. @raise SMTPBadSender: When messages cannot be accepted from the
  102. origination address.
  103. """
  104. if not helo:
  105. raise smtp.SMTPBadSender(origin, 503,
  106. "Who are you? Say HELO first.")
  107. if origin.local != b'' and origin.domain == b'':
  108. raise smtp.SMTPBadSender(origin, 501,
  109. "Sender address must contain domain.")
  110. return origin
  111. class SMTPDomainDelivery(DomainDeliveryBase):
  112. """
  113. A domain delivery base class for use in an SMTP server.
  114. """
  115. protocolName = b'smtp'
  116. class ESMTPDomainDelivery(DomainDeliveryBase):
  117. """
  118. A domain delivery base class for use in an ESMTP server.
  119. """
  120. protocolName = b'esmtp'
  121. class SMTPFactory(smtp.SMTPFactory):
  122. """
  123. An SMTP server protocol factory.
  124. @ivar service: See L{__init__}
  125. @ivar portal: See L{__init__}
  126. @type protocol: no-argument callable which returns a L{Protocol
  127. <protocol.Protocol>} subclass
  128. @ivar protocol: A callable which creates a protocol. The default value is
  129. L{SMTP}.
  130. """
  131. protocol = smtp.SMTP
  132. portal = None
  133. def __init__(self, service, portal = None):
  134. """
  135. @type service: L{MailService}
  136. @param service: An email service.
  137. @type portal: L{Portal <twisted.cred.portal.Portal>} or
  138. L{None}
  139. @param portal: A portal to use for authentication.
  140. """
  141. smtp.SMTPFactory.__init__(self)
  142. self.service = service
  143. self.portal = portal
  144. def buildProtocol(self, addr):
  145. """
  146. Create an instance of an SMTP server protocol.
  147. @type addr: L{IAddress <twisted.internet.interfaces.IAddress>} provider
  148. @param addr: The address of the SMTP client.
  149. @rtype: L{SMTP}
  150. @return: An SMTP protocol.
  151. """
  152. log.msg('Connection from %s' % (addr,))
  153. p = smtp.SMTPFactory.buildProtocol(self, addr)
  154. p.service = self.service
  155. p.portal = self.portal
  156. return p
  157. class ESMTPFactory(SMTPFactory):
  158. """
  159. An ESMTP server protocol factory.
  160. @type protocol: no-argument callable which returns a L{Protocol
  161. <protocol.Protocol>} subclass
  162. @ivar protocol: A callable which creates a protocol. The default value is
  163. L{ESMTP}.
  164. @type context: L{IOpenSSLContextFactory
  165. <twisted.internet.interfaces.IOpenSSLContextFactory>} or L{None}
  166. @ivar context: A factory to generate contexts to be used in negotiating
  167. encrypted communication.
  168. @type challengers: L{dict} mapping L{bytes} to no-argument callable which
  169. returns L{ICredentials <twisted.cred.credentials.ICredentials>}
  170. subclass provider.
  171. @ivar challengers: A mapping of acceptable authorization mechanism to
  172. callable which creates credentials to use for authentication.
  173. """
  174. protocol = smtp.ESMTP
  175. context = None
  176. def __init__(self, *args):
  177. """
  178. @param args: Arguments for L{SMTPFactory.__init__}
  179. @see: L{SMTPFactory.__init__}
  180. """
  181. SMTPFactory.__init__(self, *args)
  182. self.challengers = {
  183. b'CRAM-MD5': CramMD5Credentials
  184. }
  185. def buildProtocol(self, addr):
  186. """
  187. Create an instance of an ESMTP server protocol.
  188. @type addr: L{IAddress <twisted.internet.interfaces.IAddress>} provider
  189. @param addr: The address of the ESMTP client.
  190. @rtype: L{ESMTP}
  191. @return: An ESMTP protocol.
  192. """
  193. p = SMTPFactory.buildProtocol(self, addr)
  194. p.challengers = self.challengers
  195. p.ctx = self.context
  196. return p
  197. class VirtualPOP3(pop3.POP3):
  198. """
  199. A virtual hosting POP3 server.
  200. @type service: L{MailService}
  201. @ivar service: The email service that created this server. This must be
  202. set by the service.
  203. @type domainSpecifier: L{bytes}
  204. @ivar domainSpecifier: The character to use to split an email address into
  205. local-part and domain. The default is '@'.
  206. """
  207. service = None
  208. domainSpecifier = '@' # Gaagh! I hate POP3. No standardized way
  209. # to indicate user@host. '@' doesn't work
  210. # with NS, e.g.
  211. def authenticateUserAPOP(self, user, digest):
  212. """
  213. Perform APOP authentication.
  214. Override the default lookup scheme to allow virtual domains.
  215. @type user: L{bytes}
  216. @param user: The name of the user attempting to log in.
  217. @type digest: L{bytes}
  218. @param digest: The challenge response.
  219. @rtype: L{Deferred} which successfully results in 3-L{tuple} of
  220. (L{IMailbox <pop3.IMailbox>}, L{IMailbox <pop3.IMailbox>}
  221. provider, no-argument callable)
  222. @return: A deferred which fires when authentication is complete.
  223. If successful, it returns an L{IMailbox <pop3.IMailbox>} interface,
  224. a mailbox and a logout function. If authentication fails, the
  225. deferred fails with an L{UnauthorizedLogin
  226. <twisted.cred.error.UnauthorizedLogin>} error.
  227. """
  228. user, domain = self.lookupDomain(user)
  229. try:
  230. portal = self.service.lookupPortal(domain)
  231. except KeyError:
  232. return defer.fail(UnauthorizedLogin())
  233. else:
  234. return portal.login(
  235. pop3.APOPCredentials(self.magic, user, digest),
  236. None,
  237. pop3.IMailbox
  238. )
  239. def authenticateUserPASS(self, user, password):
  240. """
  241. Perform authentication for a username/password login.
  242. Override the default lookup scheme to allow virtual domains.
  243. @type user: L{bytes}
  244. @param user: The name of the user attempting to log in.
  245. @type password: L{bytes}
  246. @param password: The password to authenticate with.
  247. @rtype: L{Deferred} which successfully results in 3-L{tuple} of
  248. (L{IMailbox <pop3.IMailbox>}, L{IMailbox <pop3.IMailbox>}
  249. provider, no-argument callable)
  250. @return: A deferred which fires when authentication is complete.
  251. If successful, it returns an L{IMailbox <pop3.IMailbox>} interface,
  252. a mailbox and a logout function. If authentication fails, the
  253. deferred fails with an L{UnauthorizedLogin
  254. <twisted.cred.error.UnauthorizedLogin>} error.
  255. """
  256. user, domain = self.lookupDomain(user)
  257. try:
  258. portal = self.service.lookupPortal(domain)
  259. except KeyError:
  260. return defer.fail(UnauthorizedLogin())
  261. else:
  262. return portal.login(
  263. UsernamePassword(user, password),
  264. None,
  265. pop3.IMailbox
  266. )
  267. def lookupDomain(self, user):
  268. """
  269. Check whether a domain is among the virtual domains supported by the
  270. mail service.
  271. @type user: L{bytes}
  272. @param user: An email address.
  273. @rtype: 2-L{tuple} of (L{bytes}, L{bytes})
  274. @return: The local part and the domain part of the email address if the
  275. domain is supported.
  276. @raise POP3Error: When the domain is not supported by the mail service.
  277. """
  278. try:
  279. user, domain = user.split(self.domainSpecifier, 1)
  280. except ValueError:
  281. domain = ''
  282. if domain not in self.service.domains:
  283. raise pop3.POP3Error("no such domain %s" % domain)
  284. return user, domain
  285. class POP3Factory(protocol.ServerFactory):
  286. """
  287. A POP3 server protocol factory.
  288. @ivar service: See L{__init__}
  289. @type protocol: no-argument callable which returns a L{Protocol
  290. <protocol.Protocol>} subclass
  291. @ivar protocol: A callable which creates a protocol. The default value is
  292. L{VirtualPOP3}.
  293. """
  294. protocol = VirtualPOP3
  295. service = None
  296. def __init__(self, service):
  297. """
  298. @type service: L{MailService}
  299. @param service: An email service.
  300. """
  301. self.service = service
  302. def buildProtocol(self, addr):
  303. """
  304. Create an instance of a POP3 server protocol.
  305. @type addr: L{IAddress <twisted.internet.interfaces.IAddress>} provider
  306. @param addr: The address of the POP3 client.
  307. @rtype: L{POP3}
  308. @return: A POP3 protocol.
  309. """
  310. p = protocol.ServerFactory.buildProtocol(self, addr)
  311. p.service = self.service
  312. return p