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.

tap.py 12KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. # -*- test-case-name: twisted.mail.test.test_options -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Support for creating mail servers with twistd.
  6. """
  7. import os
  8. from twisted.application import internet
  9. from twisted.cred import checkers, strcred
  10. from twisted.internet import endpoints
  11. from twisted.mail import alias, mail, maildir, relay, relaymanager
  12. from twisted.python import usage
  13. class Options(usage.Options, strcred.AuthOptionMixin):
  14. """
  15. An options list parser for twistd mail.
  16. @type synopsis: L{bytes}
  17. @ivar synopsis: A description of options for use in the usage message.
  18. @type optParameters: L{list} of L{list} of (0) L{bytes}, (1) L{bytes},
  19. (2) L{object}, (3) L{bytes}, (4) L{None} or
  20. callable which takes L{bytes} and returns L{object}
  21. @ivar optParameters: Information about supported parameters. See
  22. L{Options <twisted.python.usage.Options>} for details.
  23. @type optFlags: L{list} of L{list} of (0) L{bytes}, (1) L{bytes} or
  24. L{None}, (2) L{bytes}
  25. @ivar optFlags: Information about supported flags. See
  26. L{Options <twisted.python.usage.Options>} for details.
  27. @type _protoDefaults: L{dict} mapping L{bytes} to L{int}
  28. @ivar _protoDefaults: A mapping of default service to port.
  29. @type compData: L{Completions <usage.Completions>}
  30. @ivar compData: Metadata for the shell tab completion system.
  31. @type longdesc: L{bytes}
  32. @ivar longdesc: A long description of the plugin for use in the usage
  33. message.
  34. @type service: L{MailService}
  35. @ivar service: The email service.
  36. @type last_domain: L{IDomain} provider or L{None}
  37. @ivar last_domain: The most recently specified domain.
  38. """
  39. synopsis = "[options]"
  40. optParameters = [
  41. [
  42. "relay",
  43. "R",
  44. None,
  45. "Relay messages according to their envelope 'To', using "
  46. "the given path as a queue directory.",
  47. ],
  48. ["hostname", "H", None, "The hostname by which to identify this server."],
  49. ]
  50. optFlags = [
  51. ["esmtp", "E", "Use RFC 1425/1869 SMTP extensions"],
  52. ["disable-anonymous", None, "Disallow non-authenticated SMTP connections"],
  53. ["no-pop3", None, "Disable the default POP3 server."],
  54. ["no-smtp", None, "Disable the default SMTP server."],
  55. ]
  56. _protoDefaults = {
  57. "pop3": 8110,
  58. "smtp": 8025,
  59. }
  60. compData = usage.Completions(optActions={"hostname": usage.CompleteHostnames()})
  61. longdesc = """
  62. An SMTP / POP3 email server plugin for twistd.
  63. Examples:
  64. 1. SMTP and POP server
  65. twistd mail --maildirdbmdomain=example.com=/tmp/example.com
  66. --user=joe=password
  67. Starts an SMTP server that only accepts emails to joe@example.com and saves
  68. them to /tmp/example.com.
  69. Also starts a POP mail server which will allow a client to log in using
  70. username: joe@example.com and password: password and collect any email that
  71. has been saved in /tmp/example.com.
  72. 2. SMTP relay
  73. twistd mail --relay=/tmp/mail_queue
  74. Starts an SMTP server that accepts emails to any email address and relays
  75. them to an appropriate remote SMTP server. Queued emails will be
  76. temporarily stored in /tmp/mail_queue.
  77. """
  78. def __init__(self):
  79. """
  80. Parse options and create a mail service.
  81. """
  82. usage.Options.__init__(self)
  83. self.service = mail.MailService()
  84. self.last_domain = None
  85. for service in self._protoDefaults:
  86. self[service] = []
  87. def addEndpoint(self, service, description):
  88. """
  89. Add an endpoint to a service.
  90. @type service: L{bytes}
  91. @param service: A service, either C{b'smtp'} or C{b'pop3'}.
  92. @type description: L{bytes}
  93. @param description: An endpoint description string or a TCP port
  94. number.
  95. """
  96. from twisted.internet import reactor
  97. self[service].append(endpoints.serverFromString(reactor, description))
  98. def opt_pop3(self, description):
  99. """
  100. Add a POP3 port listener on the specified endpoint.
  101. You can listen on multiple ports by specifying multiple --pop3 options.
  102. """
  103. self.addEndpoint("pop3", description)
  104. opt_p = opt_pop3
  105. def opt_smtp(self, description):
  106. """
  107. Add an SMTP port listener on the specified endpoint.
  108. You can listen on multiple ports by specifying multiple --smtp options.
  109. """
  110. self.addEndpoint("smtp", description)
  111. opt_s = opt_smtp
  112. def opt_default(self):
  113. """
  114. Make the most recently specified domain the default domain.
  115. """
  116. if self.last_domain:
  117. self.service.addDomain("", self.last_domain)
  118. else:
  119. raise usage.UsageError("Specify a domain before specifying using --default")
  120. opt_D = opt_default
  121. def opt_maildirdbmdomain(self, domain):
  122. """
  123. Generate an SMTP/POP3 virtual domain.
  124. This option requires an argument of the form 'NAME=PATH' where NAME is
  125. the DNS domain name for which email will be accepted and where PATH is
  126. a the filesystem path to a Maildir folder.
  127. [Example: 'example.com=/tmp/example.com']
  128. """
  129. try:
  130. name, path = domain.split("=")
  131. except ValueError:
  132. raise usage.UsageError(
  133. "Argument to --maildirdbmdomain must be of the form 'name=path'"
  134. )
  135. self.last_domain = maildir.MaildirDirdbmDomain(
  136. self.service, os.path.abspath(path)
  137. )
  138. self.service.addDomain(name, self.last_domain)
  139. opt_d = opt_maildirdbmdomain
  140. def opt_user(self, user_pass):
  141. """
  142. Add a user and password to the last specified domain.
  143. """
  144. try:
  145. user, password = user_pass.split("=", 1)
  146. except ValueError:
  147. raise usage.UsageError(
  148. "Argument to --user must be of the form 'user=password'"
  149. )
  150. if self.last_domain:
  151. self.last_domain.addUser(user, password)
  152. else:
  153. raise usage.UsageError("Specify a domain before specifying users")
  154. opt_u = opt_user
  155. def opt_bounce_to_postmaster(self):
  156. """
  157. Send undeliverable messages to the postmaster.
  158. """
  159. self.last_domain.postmaster = 1
  160. opt_b = opt_bounce_to_postmaster
  161. def opt_aliases(self, filename):
  162. """
  163. Specify an aliases(5) file to use for the last specified domain.
  164. """
  165. if self.last_domain is not None:
  166. if mail.IAliasableDomain.providedBy(self.last_domain):
  167. aliases = alias.loadAliasFile(self.service.domains, filename)
  168. self.last_domain.setAliasGroup(aliases)
  169. self.service.monitor.monitorFile(
  170. filename, AliasUpdater(self.service.domains, self.last_domain)
  171. )
  172. else:
  173. raise usage.UsageError(
  174. "%s does not support alias files"
  175. % (self.last_domain.__class__.__name__,)
  176. )
  177. else:
  178. raise usage.UsageError("Specify a domain before specifying aliases")
  179. opt_A = opt_aliases
  180. def _getEndpoints(self, reactor, service):
  181. """
  182. Return a list of endpoints for the specified service, constructing
  183. defaults if necessary.
  184. If no endpoints were configured for the service and the protocol
  185. was not explicitly disabled with a I{--no-*} option, a default
  186. endpoint for the service is created.
  187. @type reactor: L{IReactorTCP <twisted.internet.interfaces.IReactorTCP>}
  188. provider
  189. @param reactor: If any endpoints are created, the reactor with
  190. which they are created.
  191. @type service: L{bytes}
  192. @param service: The type of service for which to retrieve endpoints,
  193. either C{b'pop3'} or C{b'smtp'}.
  194. @rtype: L{list} of L{IStreamServerEndpoint
  195. <twisted.internet.interfaces.IStreamServerEndpoint>} provider
  196. @return: The endpoints for the specified service as configured by the
  197. command line parameters.
  198. """
  199. if self[service]:
  200. # If there are any services set up, just return those.
  201. return self[service]
  202. elif self["no-" + service]:
  203. # If there are no services, but the service was explicitly disabled,
  204. # return nothing.
  205. return []
  206. else:
  207. # Otherwise, return the old default service.
  208. return [endpoints.TCP4ServerEndpoint(reactor, self._protoDefaults[service])]
  209. def postOptions(self):
  210. """
  211. Check the validity of the specified set of options and
  212. configure authentication.
  213. @raise UsageError: When the set of options is invalid.
  214. """
  215. from twisted.internet import reactor
  216. if self["esmtp"] and self["hostname"] is None:
  217. raise usage.UsageError("--esmtp requires --hostname")
  218. # If the --auth option was passed, this will be present -- otherwise,
  219. # it won't be, which is also a perfectly valid state.
  220. if "credCheckers" in self:
  221. for ch in self["credCheckers"]:
  222. self.service.smtpPortal.registerChecker(ch)
  223. if not self["disable-anonymous"]:
  224. self.service.smtpPortal.registerChecker(checkers.AllowAnonymousAccess())
  225. anything = False
  226. for service in self._protoDefaults:
  227. self[service] = self._getEndpoints(reactor, service)
  228. if self[service]:
  229. anything = True
  230. if not anything:
  231. raise usage.UsageError("You cannot disable all protocols")
  232. class AliasUpdater:
  233. """
  234. A callable object which updates the aliases for a domain from an aliases(5)
  235. file.
  236. @ivar domains: See L{__init__}.
  237. @ivar domain: See L{__init__}.
  238. """
  239. def __init__(self, domains, domain):
  240. """
  241. @type domains: L{dict} mapping L{bytes} to L{IDomain} provider
  242. @param domains: A mapping of domain name to domain object
  243. @type domain: L{IAliasableDomain} provider
  244. @param domain: The domain to update.
  245. """
  246. self.domains = domains
  247. self.domain = domain
  248. def __call__(self, new):
  249. """
  250. Update the aliases for a domain from an aliases(5) file.
  251. @type new: L{bytes}
  252. @param new: The name of an aliases(5) file.
  253. """
  254. self.domain.setAliasGroup(alias.loadAliasFile(self.domains, new))
  255. def makeService(config):
  256. """
  257. Configure a service for operating a mail server.
  258. The returned service may include POP3 servers, SMTP servers, or both,
  259. depending on the configuration passed in. If there are multiple servers,
  260. they will share all of their non-network state (i.e. the same user accounts
  261. are available on all of them).
  262. @type config: L{Options <usage.Options>}
  263. @param config: Configuration options specifying which servers to include in
  264. the returned service and where they should keep mail data.
  265. @rtype: L{IService <twisted.application.service.IService>} provider
  266. @return: A service which contains the requested mail servers.
  267. """
  268. if config["esmtp"]:
  269. rmType = relaymanager.SmartHostESMTPRelayingManager
  270. smtpFactory = config.service.getESMTPFactory
  271. else:
  272. rmType = relaymanager.SmartHostSMTPRelayingManager
  273. smtpFactory = config.service.getSMTPFactory
  274. if config["relay"]:
  275. dir = config["relay"]
  276. if not os.path.isdir(dir):
  277. os.mkdir(dir)
  278. config.service.setQueue(relaymanager.Queue(dir))
  279. default = relay.DomainQueuer(config.service)
  280. manager = rmType(config.service.queue)
  281. if config["esmtp"]:
  282. manager.fArgs += (None, None)
  283. manager.fArgs += (config["hostname"],)
  284. helper = relaymanager.RelayStateHelper(manager, 1)
  285. helper.setServiceParent(config.service)
  286. config.service.domains.setDefaultDomain(default)
  287. if config["pop3"]:
  288. f = config.service.getPOP3Factory()
  289. for endpoint in config["pop3"]:
  290. svc = internet.StreamServerEndpointService(endpoint, f)
  291. svc.setServiceParent(config.service)
  292. if config["smtp"]:
  293. f = smtpFactory()
  294. if config["hostname"]:
  295. f.domain = config["hostname"]
  296. f.fArgs = (f.domain,)
  297. if config["esmtp"]:
  298. f.fArgs = (None, None) + f.fArgs
  299. for endpoint in config["smtp"]:
  300. svc = internet.StreamServerEndpointService(endpoint, f)
  301. svc.setServiceParent(config.service)
  302. return config.service