You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

protocols.py 12KB

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