tap.py 13 KB

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