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.

mail.py 20KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. # -*- test-case-name: twisted.mail.test.test_mail -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Mail service support.
  6. """
  7. # System imports
  8. import os
  9. import warnings
  10. from zope.interface import implementer
  11. from twisted.application import internet, service
  12. from twisted.cred.portal import Portal
  13. # Twisted imports
  14. from twisted.internet import defer
  15. # Sibling imports
  16. from twisted.mail import protocols, smtp
  17. from twisted.mail.interfaces import IAliasableDomain, IDomain
  18. from twisted.python import log, util
  19. class DomainWithDefaultDict:
  20. """
  21. A simulated dictionary for mapping domain names to domain objects with
  22. a default value for non-existing keys.
  23. @ivar domains: See L{__init__}
  24. @ivar default: See L{__init__}
  25. """
  26. def __init__(self, domains, default):
  27. """
  28. @type domains: L{dict} of L{bytes} -> L{IDomain} provider
  29. @param domains: A mapping of domain name to domain object.
  30. @type default: L{IDomain} provider
  31. @param default: The default domain.
  32. """
  33. self.domains = domains
  34. self.default = default
  35. def setDefaultDomain(self, domain):
  36. """
  37. Set the default domain.
  38. @type domain: L{IDomain} provider
  39. @param domain: The default domain.
  40. """
  41. self.default = domain
  42. def has_key(self, name):
  43. """
  44. Test for the presence of a domain name in this dictionary.
  45. This always returns C{True} because a default value will be returned
  46. if the name doesn't exist in this dictionary.
  47. @type name: L{bytes}
  48. @param name: A domain name.
  49. @rtype: L{bool}
  50. @return: C{True} to indicate that the domain name is in this
  51. dictionary.
  52. """
  53. warnings.warn(
  54. "twisted.mail.mail.DomainWithDefaultDict.has_key was deprecated "
  55. "in Twisted 16.3.0. "
  56. "Use the `in` keyword instead.",
  57. category=DeprecationWarning,
  58. stacklevel=2,
  59. )
  60. return 1
  61. @classmethod
  62. def fromkeys(klass, keys, value=None):
  63. """
  64. Create a new L{DomainWithDefaultDict} with the specified keys.
  65. @type keys: iterable of L{bytes}
  66. @param keys: Domain names to serve as keys in the new dictionary.
  67. @type value: L{None} or L{IDomain} provider
  68. @param value: A domain object to serve as the value for all new keys
  69. in the dictionary.
  70. @rtype: L{DomainWithDefaultDict}
  71. @return: A new dictionary.
  72. """
  73. d = klass()
  74. for k in keys:
  75. d[k] = value
  76. return d
  77. def __contains__(self, name):
  78. """
  79. Test for the presence of a domain name in this dictionary.
  80. This always returns C{True} because a default value will be returned
  81. if the name doesn't exist in this dictionary.
  82. @type name: L{bytes}
  83. @param name: A domain name.
  84. @rtype: L{bool}
  85. @return: C{True} to indicate that the domain name is in this
  86. dictionary.
  87. """
  88. return 1
  89. def __getitem__(self, name):
  90. """
  91. Look up a domain name and, if it is present, return the domain object
  92. associated with it. Otherwise return the default domain.
  93. @type name: L{bytes}
  94. @param name: A domain name.
  95. @rtype: L{IDomain} provider or L{None}
  96. @return: A domain object.
  97. """
  98. return self.domains.get(name, self.default)
  99. def __setitem__(self, name, value):
  100. """
  101. Associate a domain object with a domain name in this dictionary.
  102. @type name: L{bytes}
  103. @param name: A domain name.
  104. @type value: L{IDomain} provider
  105. @param value: A domain object.
  106. """
  107. self.domains[name] = value
  108. def __delitem__(self, name):
  109. """
  110. Delete the entry for a domain name in this dictionary.
  111. @type name: L{bytes}
  112. @param name: A domain name.
  113. """
  114. del self.domains[name]
  115. def __iter__(self):
  116. """
  117. Return an iterator over the domain names in this dictionary.
  118. @rtype: iterator over L{bytes}
  119. @return: An iterator over the domain names.
  120. """
  121. return iter(self.domains)
  122. def __len__(self):
  123. """
  124. Return the number of domains in this dictionary.
  125. @rtype: L{int}
  126. @return: The number of domains in this dictionary.
  127. """
  128. return len(self.domains)
  129. def __str__(self) -> str:
  130. """
  131. Build an informal string representation of this dictionary.
  132. @rtype: L{bytes}
  133. @return: A string containing the mapping of domain names to domain
  134. objects.
  135. """
  136. return f"<DomainWithDefaultDict {self.domains}>"
  137. def __repr__(self) -> str:
  138. """
  139. Build an "official" string representation of this dictionary.
  140. @rtype: L{bytes}
  141. @return: A pseudo-executable string describing the underlying domain
  142. mapping of this object.
  143. """
  144. return f"DomainWithDefaultDict({self.domains})"
  145. def get(self, key, default=None):
  146. """
  147. Look up a domain name in this dictionary.
  148. @type key: L{bytes}
  149. @param key: A domain name.
  150. @type default: L{IDomain} provider or L{None}
  151. @param default: A domain object to be returned if the domain name is
  152. not in this dictionary.
  153. @rtype: L{IDomain} provider or L{None}
  154. @return: The domain object associated with the domain name if it is in
  155. this dictionary. Otherwise, the default value.
  156. """
  157. return self.domains.get(key, default)
  158. def copy(self):
  159. """
  160. Make a copy of this dictionary.
  161. @rtype: L{DomainWithDefaultDict}
  162. @return: A copy of this dictionary.
  163. """
  164. return DomainWithDefaultDict(self.domains.copy(), self.default)
  165. def iteritems(self):
  166. """
  167. Return an iterator over the domain name/domain object pairs in the
  168. dictionary.
  169. Using the returned iterator while adding or deleting entries from the
  170. dictionary may result in a L{RuntimeError} or failing to iterate over
  171. all the domain name/domain object pairs.
  172. @rtype: iterator over 2-L{tuple} of (E{1}) L{bytes},
  173. (E{2}) L{IDomain} provider or L{None}
  174. @return: An iterator over the domain name/domain object pairs.
  175. """
  176. return self.domains.iteritems()
  177. def iterkeys(self):
  178. """
  179. Return an iterator over the domain names in this dictionary.
  180. Using the returned iterator while adding or deleting entries from the
  181. dictionary may result in a L{RuntimeError} or failing to iterate over
  182. all the domain names.
  183. @rtype: iterator over L{bytes}
  184. @return: An iterator over the domain names.
  185. """
  186. return self.domains.iterkeys()
  187. def itervalues(self):
  188. """
  189. Return an iterator over the domain objects in this dictionary.
  190. Using the returned iterator while adding or deleting entries from the
  191. dictionary may result in a L{RuntimeError} or failing to iterate over
  192. all the domain objects.
  193. @rtype: iterator over L{IDomain} provider or
  194. L{None}
  195. @return: An iterator over the domain objects.
  196. """
  197. return self.domains.itervalues()
  198. def keys(self):
  199. """
  200. Return a list of all domain names in this dictionary.
  201. @rtype: L{list} of L{bytes}
  202. @return: The domain names in this dictionary.
  203. """
  204. return self.domains.keys()
  205. def values(self):
  206. """
  207. Return a list of all domain objects in this dictionary.
  208. @rtype: L{list} of L{IDomain} provider or L{None}
  209. @return: The domain objects in this dictionary.
  210. """
  211. return self.domains.values()
  212. def items(self):
  213. """
  214. Return a list of all domain name/domain object pairs in this
  215. dictionary.
  216. @rtype: L{list} of 2-L{tuple} of (E{1}) L{bytes}, (E{2}) L{IDomain}
  217. provider or L{None}
  218. @return: Domain name/domain object pairs in this dictionary.
  219. """
  220. return self.domains.items()
  221. def popitem(self):
  222. """
  223. Remove a random domain name/domain object pair from this dictionary and
  224. return it as a tuple.
  225. @rtype: 2-L{tuple} of (E{1}) L{bytes}, (E{2}) L{IDomain} provider or
  226. L{None}
  227. @return: A domain name/domain object pair.
  228. @raise KeyError: When this dictionary is empty.
  229. """
  230. return self.domains.popitem()
  231. def update(self, other):
  232. """
  233. Update this dictionary with domain name/domain object pairs from
  234. another dictionary.
  235. When this dictionary contains a domain name which is in the other
  236. dictionary, its value will be overwritten.
  237. @type other: L{dict} of L{bytes} -> L{IDomain} provider and/or
  238. L{bytes} -> L{None}
  239. @param other: Another dictionary of domain name/domain object pairs.
  240. @rtype: L{None}
  241. @return: None.
  242. """
  243. return self.domains.update(other)
  244. def clear(self):
  245. """
  246. Remove all items from this dictionary.
  247. @rtype: L{None}
  248. @return: None.
  249. """
  250. return self.domains.clear()
  251. def setdefault(self, key, default):
  252. """
  253. Return the domain object associated with the domain name if it is
  254. present in this dictionary. Otherwise, set the value for the
  255. domain name to the default and return that value.
  256. @type key: L{bytes}
  257. @param key: A domain name.
  258. @type default: L{IDomain} provider
  259. @param default: A domain object.
  260. @rtype: L{IDomain} provider or L{None}
  261. @return: The domain object associated with the domain name.
  262. """
  263. return self.domains.setdefault(key, default)
  264. @implementer(IDomain)
  265. class BounceDomain:
  266. """
  267. A domain with no users.
  268. This can be used to block off a domain.
  269. """
  270. def exists(self, user):
  271. """
  272. Raise an exception to indicate that the user does not exist in this
  273. domain.
  274. @type user: L{User}
  275. @param user: A user.
  276. @raise SMTPBadRcpt: When the given user does not exist in this domain.
  277. """
  278. raise smtp.SMTPBadRcpt(user)
  279. def willRelay(self, user, protocol):
  280. """
  281. Indicate that this domain will not relay.
  282. @type user: L{Address}
  283. @param user: The destination address.
  284. @type protocol: L{Protocol <twisted.internet.protocol.Protocol>}
  285. @param protocol: The protocol over which the message to be relayed is
  286. being received.
  287. @rtype: L{bool}
  288. @return: C{False}.
  289. """
  290. return False
  291. def addUser(self, user, password):
  292. """
  293. Ignore attempts to add a user to this domain.
  294. @type user: L{bytes}
  295. @param user: A username.
  296. @type password: L{bytes}
  297. @param password: A password.
  298. """
  299. pass
  300. def getCredentialsCheckers(self):
  301. """
  302. Return no credentials checkers for this domain.
  303. @rtype: L{list}
  304. @return: The empty list.
  305. """
  306. return []
  307. @implementer(smtp.IMessage)
  308. class FileMessage:
  309. """
  310. A message receiver which delivers a message to a file.
  311. @ivar fp: See L{__init__}.
  312. @ivar name: See L{__init__}.
  313. @ivar finalName: See L{__init__}.
  314. """
  315. def __init__(self, fp, name, finalName):
  316. """
  317. @type fp: file-like object
  318. @param fp: The file in which to store the message while it is being
  319. received.
  320. @type name: L{bytes}
  321. @param name: The full path name of the temporary file.
  322. @type finalName: L{bytes}
  323. @param finalName: The full path name that should be given to the file
  324. holding the message after it has been fully received.
  325. """
  326. self.fp = fp
  327. self.name = name
  328. self.finalName = finalName
  329. def lineReceived(self, line):
  330. """
  331. Write a received line to the file.
  332. @type line: L{bytes}
  333. @param line: A received line.
  334. """
  335. self.fp.write(line + b"\n")
  336. def eomReceived(self):
  337. """
  338. At the end of message, rename the file holding the message to its
  339. final name.
  340. @rtype: L{Deferred} which successfully results in L{bytes}
  341. @return: A deferred which returns the final name of the file.
  342. """
  343. self.fp.close()
  344. os.rename(self.name, self.finalName)
  345. return defer.succeed(self.finalName)
  346. def connectionLost(self):
  347. """
  348. Delete the file holding the partially received message.
  349. """
  350. self.fp.close()
  351. os.remove(self.name)
  352. class MailService(service.MultiService):
  353. """
  354. An email service.
  355. @type queue: L{Queue} or L{None}
  356. @ivar queue: A queue for outgoing messages.
  357. @type domains: L{dict} of L{bytes} -> L{IDomain} provider
  358. @ivar domains: A mapping of supported domain name to domain object.
  359. @type portals: L{dict} of L{bytes} -> L{Portal}
  360. @ivar portals: A mapping of domain name to authentication portal.
  361. @type aliases: L{None} or L{dict} of
  362. L{bytes} -> L{IAlias} provider
  363. @ivar aliases: A mapping of domain name to alias.
  364. @type smtpPortal: L{Portal}
  365. @ivar smtpPortal: A portal for authentication for the SMTP server.
  366. @type monitor: L{FileMonitoringService}
  367. @ivar monitor: A service to monitor changes to files.
  368. """
  369. queue = None
  370. domains = None
  371. portals = None
  372. aliases = None
  373. smtpPortal = None
  374. def __init__(self):
  375. """
  376. Initialize the mail service.
  377. """
  378. service.MultiService.__init__(self)
  379. # Domains and portals for "client" protocols - POP3, IMAP4, etc
  380. self.domains = DomainWithDefaultDict({}, BounceDomain())
  381. self.portals = {}
  382. self.monitor = FileMonitoringService()
  383. self.monitor.setServiceParent(self)
  384. self.smtpPortal = Portal(self)
  385. def getPOP3Factory(self):
  386. """
  387. Create a POP3 protocol factory.
  388. @rtype: L{POP3Factory}
  389. @return: A POP3 protocol factory.
  390. """
  391. return protocols.POP3Factory(self)
  392. def getSMTPFactory(self):
  393. """
  394. Create an SMTP protocol factory.
  395. @rtype: L{SMTPFactory <protocols.SMTPFactory>}
  396. @return: An SMTP protocol factory.
  397. """
  398. return protocols.SMTPFactory(self, self.smtpPortal)
  399. def getESMTPFactory(self):
  400. """
  401. Create an ESMTP protocol factory.
  402. @rtype: L{ESMTPFactory <protocols.ESMTPFactory>}
  403. @return: An ESMTP protocol factory.
  404. """
  405. return protocols.ESMTPFactory(self, self.smtpPortal)
  406. def addDomain(self, name, domain):
  407. """
  408. Add a domain for which the service will accept email.
  409. @type name: L{bytes}
  410. @param name: A domain name.
  411. @type domain: L{IDomain} provider
  412. @param domain: A domain object.
  413. """
  414. portal = Portal(domain)
  415. map(portal.registerChecker, domain.getCredentialsCheckers())
  416. self.domains[name] = domain
  417. self.portals[name] = portal
  418. if self.aliases and IAliasableDomain.providedBy(domain):
  419. domain.setAliasGroup(self.aliases)
  420. def setQueue(self, queue):
  421. """
  422. Set the queue for outgoing emails.
  423. @type queue: L{Queue}
  424. @param queue: A queue for outgoing messages.
  425. """
  426. self.queue = queue
  427. def requestAvatar(self, avatarId, mind, *interfaces):
  428. """
  429. Return a message delivery for an authenticated SMTP user.
  430. @type avatarId: L{bytes}
  431. @param avatarId: A string which identifies an authenticated user.
  432. @type mind: L{None}
  433. @param mind: Unused.
  434. @type interfaces: n-L{tuple} of C{zope.interface.Interface}
  435. @param interfaces: A group of interfaces one of which the avatar must
  436. support.
  437. @rtype: 3-L{tuple} of (E{1}) L{IMessageDelivery},
  438. (E{2}) L{ESMTPDomainDelivery}, (E{3}) no-argument callable
  439. @return: A tuple of the supported interface, a message delivery, and
  440. a logout function.
  441. @raise NotImplementedError: When the given interfaces do not include
  442. L{IMessageDelivery}.
  443. """
  444. if smtp.IMessageDelivery in interfaces:
  445. a = protocols.ESMTPDomainDelivery(self, avatarId)
  446. return smtp.IMessageDelivery, a, lambda: None
  447. raise NotImplementedError()
  448. def lookupPortal(self, name):
  449. """
  450. Find the portal for a domain.
  451. @type name: L{bytes}
  452. @param name: A domain name.
  453. @rtype: L{Portal}
  454. @return: A portal.
  455. """
  456. return self.portals[name]
  457. def defaultPortal(self):
  458. """
  459. Return the portal for the default domain.
  460. The default domain is named ''.
  461. @rtype: L{Portal}
  462. @return: The portal for the default domain.
  463. """
  464. return self.portals[""]
  465. class FileMonitoringService(internet.TimerService):
  466. """
  467. A service for monitoring changes to files.
  468. @type files: L{list} of L{list} of (E{1}) L{float}, (E{2}) L{bytes},
  469. (E{3}) callable which takes a L{bytes} argument, (E{4}) L{float}
  470. @ivar files: Information about files to be monitored. Each list entry
  471. provides the following information for a file: interval in seconds
  472. between checks, filename, callback function, time of last modification
  473. to the file.
  474. @type intervals: L{_IntervalDifferentialIterator
  475. <twisted.python.util._IntervalDifferentialIterator>}
  476. @ivar intervals: Intervals between successive file checks.
  477. @type _call: L{IDelayedCall <twisted.internet.interfaces.IDelayedCall>}
  478. provider
  479. @ivar _call: The next scheduled call to check a file.
  480. @type index: L{int}
  481. @ivar index: The index of the next file to be checked.
  482. """
  483. def __init__(self):
  484. """
  485. Initialize the file monitoring service.
  486. """
  487. self.files = []
  488. self.intervals = iter(util.IntervalDifferential([], 60))
  489. def startService(self):
  490. """
  491. Start the file monitoring service.
  492. """
  493. service.Service.startService(self)
  494. self._setupMonitor()
  495. def _setupMonitor(self):
  496. """
  497. Schedule the next monitoring call.
  498. """
  499. from twisted.internet import reactor
  500. t, self.index = self.intervals.next()
  501. self._call = reactor.callLater(t, self._monitor)
  502. def stopService(self):
  503. """
  504. Stop the file monitoring service.
  505. """
  506. service.Service.stopService(self)
  507. if self._call:
  508. self._call.cancel()
  509. self._call = None
  510. def monitorFile(self, name, callback, interval=10):
  511. """
  512. Start monitoring a file for changes.
  513. @type name: L{bytes}
  514. @param name: The name of a file to monitor.
  515. @type callback: callable which takes a L{bytes} argument
  516. @param callback: The function to call when the file has changed.
  517. @type interval: L{float}
  518. @param interval: The interval in seconds between checks.
  519. """
  520. try:
  521. mtime = os.path.getmtime(name)
  522. except BaseException:
  523. mtime = 0
  524. self.files.append([interval, name, callback, mtime])
  525. self.intervals.addInterval(interval)
  526. def unmonitorFile(self, name):
  527. """
  528. Stop monitoring a file.
  529. @type name: L{bytes}
  530. @param name: A file name.
  531. """
  532. for i in range(len(self.files)):
  533. if name == self.files[i][1]:
  534. self.intervals.removeInterval(self.files[i][0])
  535. del self.files[i]
  536. break
  537. def _monitor(self):
  538. """
  539. Monitor a file and make a callback if it has changed.
  540. """
  541. self._call = None
  542. if self.index is not None:
  543. name, callback, mtime = self.files[self.index][1:]
  544. try:
  545. now = os.path.getmtime(name)
  546. except BaseException:
  547. now = 0
  548. if now > mtime:
  549. log.msg(f"{name} changed, notifying listener")
  550. self.files[self.index][3] = now
  551. callback(name)
  552. self._setupMonitor()