Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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 zope.interface import implementer
  8. from twisted.copyright import longversion
  9. from twisted.cred.credentials import CramMD5Credentials, UsernamePassword
  10. from twisted.cred.error import UnauthorizedLogin
  11. from twisted.internet import defer, protocol
  12. from twisted.mail import pop3, relay, smtp
  13. from twisted.python import log
  14. @implementer(smtp.IMessageDelivery)
  15. class DomainDeliveryBase:
  16. """
  17. A base class for message delivery using the domains of a mail service.
  18. @ivar service: See L{__init__}
  19. @ivar user: See L{__init__}
  20. @ivar host: See L{__init__}
  21. @type protocolName: L{bytes}
  22. @ivar protocolName: The protocol being used to deliver the mail.
  23. Sub-classes should set this appropriately.
  24. """
  25. service = None
  26. protocolName: bytes = b"not-implemented-protocol"
  27. def __init__(self, service, user, host=smtp.DNSNAME):
  28. """
  29. @type service: L{MailService}
  30. @param service: A mail service.
  31. @type user: L{bytes} or L{None}
  32. @param user: The authenticated SMTP user.
  33. @type host: L{bytes}
  34. @param host: The hostname.
  35. """
  36. self.service = service
  37. self.user = user
  38. self.host = host
  39. def receivedHeader(self, helo, origin, recipients):
  40. """
  41. Generate a received header string for a message.
  42. @type helo: 2-L{tuple} of (L{bytes}, L{bytes})
  43. @param helo: The client's identity as sent in the HELO command and its
  44. IP address.
  45. @type origin: L{Address}
  46. @param origin: The origination address of the message.
  47. @type recipients: L{list} of L{User}
  48. @param recipients: The destination addresses for the message.
  49. @rtype: L{bytes}
  50. @return: A received header string.
  51. """
  52. authStr = heloStr = b""
  53. if self.user:
  54. authStr = b" auth=" + self.user.encode("xtext")
  55. if helo[0]:
  56. heloStr = b" helo=" + helo[0]
  57. fromUser = b"from " + helo[0] + b" ([" + helo[1] + b"]" + heloStr + authStr
  58. by = (
  59. b"by "
  60. + self.host
  61. + b" with "
  62. + self.protocolName
  63. + b" ("
  64. + longversion.encode("ascii")
  65. + b")"
  66. )
  67. forUser = (
  68. b"for <" + b" ".join(map(bytes, recipients)) + b"> " + smtp.rfc822date()
  69. )
  70. return b"Received: " + fromUser + b"\n\t" + by + b"\n\t" + forUser
  71. def validateTo(self, user):
  72. """
  73. Validate the address for which a message is destined.
  74. @type user: L{User}
  75. @param user: The destination address.
  76. @rtype: L{Deferred <defer.Deferred>} which successfully fires with
  77. no-argument callable which returns L{IMessage <smtp.IMessage>}
  78. provider.
  79. @return: A deferred which successfully fires with a no-argument
  80. callable which returns a message receiver for the destination.
  81. @raise SMTPBadRcpt: When messages cannot be accepted for the
  82. destination address.
  83. """
  84. # XXX - Yick. This needs cleaning up.
  85. if self.user and self.service.queue:
  86. d = self.service.domains.get(user.dest.domain, None)
  87. if d is None:
  88. d = relay.DomainQueuer(self.service, True)
  89. else:
  90. d = self.service.domains[user.dest.domain]
  91. return defer.maybeDeferred(d.exists, user)
  92. def validateFrom(self, helo, origin):
  93. """
  94. Validate the address from which a message originates.
  95. @type helo: 2-L{tuple} of (L{bytes}, L{bytes})
  96. @param helo: The client's identity as sent in the HELO command and its
  97. IP address.
  98. @type origin: L{Address}
  99. @param origin: The origination address of the message.
  100. @rtype: L{Address}
  101. @return: The origination address.
  102. @raise SMTPBadSender: When messages cannot be accepted from the
  103. origination address.
  104. """
  105. if not helo:
  106. raise smtp.SMTPBadSender(origin, 503, "Who are you? Say HELO first.")
  107. if origin.local != b"" and origin.domain == b"":
  108. raise smtp.SMTPBadSender(origin, 501, "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(f"Connection from {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 = {b"CRAM-MD5": CramMD5Credentials}
  182. def buildProtocol(self, addr):
  183. """
  184. Create an instance of an ESMTP server protocol.
  185. @type addr: L{IAddress <twisted.internet.interfaces.IAddress>} provider
  186. @param addr: The address of the ESMTP client.
  187. @rtype: L{ESMTP}
  188. @return: An ESMTP protocol.
  189. """
  190. p = SMTPFactory.buildProtocol(self, addr)
  191. p.challengers = self.challengers
  192. p.ctx = self.context
  193. return p
  194. class VirtualPOP3(pop3.POP3):
  195. """
  196. A virtual hosting POP3 server.
  197. @type service: L{MailService}
  198. @ivar service: The email service that created this server. This must be
  199. set by the service.
  200. @type domainSpecifier: L{bytes}
  201. @ivar domainSpecifier: The character to use to split an email address into
  202. local-part and domain. The default is '@'.
  203. """
  204. service = None
  205. domainSpecifier = b"@" # Gaagh! I hate POP3. No standardized way
  206. # to indicate user@host. '@' doesn't work
  207. # with NS, e.g.
  208. def authenticateUserAPOP(self, user, digest):
  209. """
  210. Perform APOP authentication.
  211. Override the default lookup scheme to allow virtual domains.
  212. @type user: L{bytes}
  213. @param user: The name of the user attempting to log in.
  214. @type digest: L{bytes}
  215. @param digest: The challenge response.
  216. @rtype: L{Deferred} which successfully results in 3-L{tuple} of
  217. (L{IMailbox <pop3.IMailbox>}, L{IMailbox <pop3.IMailbox>}
  218. provider, no-argument callable)
  219. @return: A deferred which fires when authentication is complete.
  220. If successful, it returns an L{IMailbox <pop3.IMailbox>} interface,
  221. a mailbox and a logout function. If authentication fails, the
  222. deferred fails with an L{UnauthorizedLogin
  223. <twisted.cred.error.UnauthorizedLogin>} error.
  224. """
  225. user, domain = self.lookupDomain(user)
  226. try:
  227. portal = self.service.lookupPortal(domain)
  228. except KeyError:
  229. return defer.fail(UnauthorizedLogin())
  230. else:
  231. return portal.login(
  232. pop3.APOPCredentials(self.magic, user, digest), None, pop3.IMailbox
  233. )
  234. def authenticateUserPASS(self, user, password):
  235. """
  236. Perform authentication for a username/password login.
  237. Override the default lookup scheme to allow virtual domains.
  238. @type user: L{bytes}
  239. @param user: The name of the user attempting to log in.
  240. @type password: L{bytes}
  241. @param password: The password to authenticate with.
  242. @rtype: L{Deferred} which successfully results in 3-L{tuple} of
  243. (L{IMailbox <pop3.IMailbox>}, L{IMailbox <pop3.IMailbox>}
  244. provider, no-argument callable)
  245. @return: A deferred which fires when authentication is complete.
  246. If successful, it returns an L{IMailbox <pop3.IMailbox>} interface,
  247. a mailbox and a logout function. If authentication fails, the
  248. deferred fails with an L{UnauthorizedLogin
  249. <twisted.cred.error.UnauthorizedLogin>} error.
  250. """
  251. user, domain = self.lookupDomain(user)
  252. try:
  253. portal = self.service.lookupPortal(domain)
  254. except KeyError:
  255. return defer.fail(UnauthorizedLogin())
  256. else:
  257. return portal.login(UsernamePassword(user, password), None, pop3.IMailbox)
  258. def lookupDomain(self, user):
  259. """
  260. Check whether a domain is among the virtual domains supported by the
  261. mail service.
  262. @type user: L{bytes}
  263. @param user: An email address.
  264. @rtype: 2-L{tuple} of (L{bytes}, L{bytes})
  265. @return: The local part and the domain part of the email address if the
  266. domain is supported.
  267. @raise POP3Error: When the domain is not supported by the mail service.
  268. """
  269. try:
  270. user, domain = user.split(self.domainSpecifier, 1)
  271. except ValueError:
  272. domain = b""
  273. if domain not in self.service.domains:
  274. raise pop3.POP3Error("no such domain {}".format(domain.decode("utf-8")))
  275. return user, domain
  276. class POP3Factory(protocol.ServerFactory):
  277. """
  278. A POP3 server protocol factory.
  279. @ivar service: See L{__init__}
  280. @type protocol: no-argument callable which returns a L{Protocol
  281. <protocol.Protocol>} subclass
  282. @ivar protocol: A callable which creates a protocol. The default value is
  283. L{VirtualPOP3}.
  284. """
  285. protocol = VirtualPOP3
  286. service = None
  287. def __init__(self, service):
  288. """
  289. @type service: L{MailService}
  290. @param service: An email service.
  291. """
  292. self.service = service
  293. def buildProtocol(self, addr):
  294. """
  295. Create an instance of a POP3 server protocol.
  296. @type addr: L{IAddress <twisted.internet.interfaces.IAddress>} provider
  297. @param addr: The address of the POP3 client.
  298. @rtype: L{POP3}
  299. @return: A POP3 protocol.
  300. """
  301. p = protocol.ServerFactory.buildProtocol(self, addr)
  302. p.service = self.service
  303. return p